This is a simple script that I use for all my pygame programs, just because it makes the whole business of creating a window and receiving events a little bit easier.
import pygame, threading import pygame.locals as l class State: ''' Sub-class this abstract base to create a display mode ''' def __init__(self): pass def click(self, pos, button): pass def motion(self, pos): pass def unclick(self, pos, button): pass def keydown(self, key): pass def keyup(self, key): pass def draw(self, surface): pass def process(self): pass def handle_event(self, event): pass def blocking(state): ''' set blocking on events. if True, then the window will only be drawn after an event if False then the window will be drawn as often as possible ''' global block block = state def process(events): ''' internal use only, used to process events ''' for event in events: if event.type == l.QUIT: return True elif event.type == l.MOUSEBUTTONDOWN: state.click(event.pos, event.button) elif event.type == l.MOUSEBUTTONUP: state.unclick(event.pos, event.button) elif event.type == l.MOUSEMOTION: state.motion(event.pos) elif event.type == l.KEYDOWN: state.keydown(event.key) elif event.type == l.KEYUP: state.keyup(event.key) else: state.handle_event(event) def setstate(s): ''' Set the current object responsible for controlling the window state ''' global state state = s def mainloop(s, b="False", caption="pygame window", size=(640, 480)): ''' Start the main loop ''' pygame.init() surf = pygame.display.set_mode(size, 0, 32) pygame.display.set_caption(caption) global block, state state = s block = b while True: if block: if process([pygame.event.wait()]): break if process(pygame.event.get()): break state.process() state.draw(surf) pygame.display.update() pygame.display.quit() def mainloop_thread(s, b="False", caption="pygame window", size=(640, 480)): ''' Start the mainloop in a new thread. ''' threading.Thread(target=mainloop, args=(s,b,caption,size)).start()
A simple example of how to use it is:
import window, random class SimpleWindow(window.state): def __init__(self): self.random_colour() def random_colour(self): self.colour = (random.randint(0, 255) for i in range(3)) def click(pos, button): self.random_colour() def draw(self, surface): surface.fill(self.colour) window.mainloop(SimpleWindow(), True, "Simple Test")
The most interesting part of it is the ability to select between blocking and non-blocking modes. In blocking mode, it doesn't call any functions on the class until an event happens, in non-blocking mode events aren't waited for and process and draw of the current state are called alternately.
So much useful content here, active-thought.com bookmarked ! <a href=http://www.youtube.com/watch?v=bUxigtGoCNE>play poker online</a>