[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] placement of graphics code



import random
x=random.randint(0,9)
guess = None
while (guess != x):
    guess = int( raw_input( "guess?" ))
    if (guess > x):
        print "Too high"
    elif (guess < x):
        print "Too low"
    else:
        print "you got it"

Here's how I did this using pygsear:
http://www.nongnu.org/pygsear/


# guess.py
import math
import random
import os

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


class Button(StationaryTextButton):
def __init__(self, game, n):
self.game = game
self.num = n
StationaryTextButton.__init__(self, game.window, text=str(n), callback=self.cb, border=0)

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


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

b = Button(self, n)
self.events.add(b.events)

self.buttons[n] = b

x1 = x0 + x * dx
y1 = y0 + y * dy
b.setPosition((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()
#end guess.py

I am not sure if the Button really needs to know about the Game,
but I find that tends to happen pretty often. Maybe I could define
the callback in the Game, and pass that to the button... I should
probably study up on MVC myself :o)

_________________________________________________________________
The new MSN 8: advanced junk mail protection and 2 months FREE* http://join.msn.com/?page=features/junkmail