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

Re: [pygame] Very beginner level question



It means it doesn't yet know what 'pygame' means. Adding the line 'import pygame' fixes that.

[ Note: If you aren't already, make sure you're Using a text editor like scite, Notepad++, geany, or a similar one helps a ton. Syntax hilighting and code folding are very useful. Geany has a couple python features that are nice too. ]


Here is some template code you can use. It creates a window, fills the screen, gets keyboard input, and loops. ( press Escape to quit ).

# About: basic 'emtpy' template that runs, but doesn't do much.
WINDOW_TITLE = "pygame template code"

try:
import pygame
from pygame.locals import *
except ImportError, err:
print "Couldn't load module. %s" % (err)
sys.exit(2)

class Game():
"""game Main entry point. handles intialization of game and graphics.
methods:
__init__(width, height) : init
members:
screen : screen display surface
done : if ever set to False, game will quit.
bLimitFPS, fps_limit : toggle capping FPS to 40 fps.
"""
done = False
def __init__(self, width=800, height=600):
"""Initialize PyGame"""
pygame.init()
self.width, self.height = width, height
self.screen = pygame.display.set_mode(( self.width, self.height ))
pygame.display.set_caption( WINDOW_TITLE )
self.bLimitFPS = True
self.fps_limit = 40
self.clock = pygame.time.Clock()

def main_loop(self):
"""Game() main loop
main game loop does:
1) get input / events
2) update / physics
3) draw
"""
while not self.done:
self.handle_events()
self.update()
self.draw()
# delay here: toggle FPS cap 
if self.bLimitFPS: self.clock.tick( self.fps_limit )
else: self.clock.tick()
def update(self):
self.now = pygame.time.get_ticks()
# todo: move your sprites here
def handle_events(self):
"""do regular events. Also sends copies to Note()s, etc..."""
# handle events,
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT: sys.exit()
# event: keydown
elif event.type == KEYDOWN:
# exit on 'escape'
if (event.key == K_ESCAPE): self.done = True
elif event.type == MOUSEBUTTONDOWN:
x,y = event.pos
button = event.button
# todo: do something on mouseclick

def draw(self):
"""render screen"""
# first clear screen, then update.
self.screen.fill( (230,230,153) )
# todo: draw sprites here

pygame.display.flip()

# == entry point ==
if __name__ == "__main__":
print WINDOW_TITLE
print "Press ESCAPE to quit"
# create the game, and start looping
game = Game(640,480)
game.main_loop()

--
Jake