# pygsear
# Copyright (C) 2003 Lee Harr
#
#
# This file is part of pygsear.
#
# pygsear is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# pygsear is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pygsear; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


import math
import random
import os

from pygsear.Game import Game
from pygsear.Widget import StationaryTextButton, Dialog_OK
from pygsear import conf


class GuessingGame(Game):
    def initialize(self):
        numbers = 200
        self.numbers = numbers
        self.choice = random.randrange(numbers)

        self.buttons = {}

        nx = int(math.sqrt(numbers))
        dx = (conf.WINWIDTH - 100) / float(nx)
        x0 = 40

        ny = int(numbers / float(nx))
        dy = (conf.WINHEIGHT - 100) / float(nx)
        y0 = 20

        nr = numbers - (nx * ny)

        for y in range(ny):
            for x in range(nx):
                n = x + (nx * y) + 1

                def cb(ev, num=n):
                    if num < self.choice:
                        self.erase_to(num)
                    elif num > self.choice:
                        self.erase_from(num)
                    else:
                        self.victory()

                b = StationaryTextButton(text=str(n), callback=cb, border=0)
                self.events.add(b.events)

                self.buttons[n] = b

                x1 = x0 + x * dx
                y1 = y0 + y * dy
                b.set_position((x1, y1))
                b.draw()

    def erase_to(self, num):
        d = Dialog_OK(message="%s is too low" % num)
        d.modal()
        for n in range(1, num+1):
            try:
                b = self.buttons[n]
                b.clear()
                b.events.disable()
                del(self.buttons[n])
            except KeyError:
                pass

    def erase_from(self, num):
        d = Dialog_OK(message="%s is too high" % num)
        d.modal()
        for n in range(num, self.numbers+1):
            try:
                b = self.buttons[n]
                b.clear()
                b.events.disable()
                del(self.buttons[n])
            except KeyError:
                pass

    def victory(self):
        d = Dialog_OK(message="Yes!\nThe correct number was %s" % self.choice)
        d.modal()
        os._exit(0)


if __name__ == '__main__':
    g = GuessingGame()
    d = Dialog_OK(message="Guess the correct number")
    d.modal()
    g.mainloop()

