Now with sprites

Published November 09, 2007
In my quest to figure out how to make only the current position of the snow image show (instead of leaving a trail) I discovered that I should be using pygame sprites as they make life much easier. As a bonus I learned how to support the mouse.

Current code here:
#Setup: I import all the modules hereimport sysimport osimport pygameimport randomimport mathfrom pygame.locals import *progpath = os.getcwd()+"/"keys=[False]*324snow_file_name = '\snow.bmp' #this is the filename for the sprite I will usedef kill(): #this function is for killing the window and quitting    pygame.display.quit()    pygame.quit()    returndef load_image(name, colorkey=None): #this function is for loading the image to us in the program    fullname ='c:\Python24' + name    try:        image = pygame.image.load(fullname)    except pygame.error, message:        print 'Cannot load image:,%s', name        raise SystemExit, message    image = image.convert()    if colorkey is not None:        if colorkey is -1:            colorkey = image.get_at((0,0))        image.set_colorkey(colorkey, RLEACCEL)    print('hi')    return image, image.get_rect()class Snow(pygame.sprite.Sprite): #this class handles loading the image that I use as a mouse pointer and tracking and drawing it    def __init__(self): #initialization        pygame.sprite.Sprite.__init__(self)        self.image, self.rect = load_image(snow_file_name, -1)    def update(self): #actions for frame update        pos = pygame.mouse.get_pos()        self.rect.midtop = pos        ######################################################def main():    pygame.init()    pygame.font.init()    w=320.0 #screen width    h=200.0 #height       screen = pygame.display.set_mode((int(w*2),int(h)))    pygame.display.set_caption("Trial")    pygame.mouse.set_visible(0)    clock=pygame.time.Clock()    background = pygame.Surface(screen.get_size())    background = background.convert()    background.fill((250,250,250))    if pygame.font: #add text to background        font = pygame.font.Font(None, 36)        text = font.render("TEST", 1, (10,10,10))        textpos = text.get_rect()        textpos.centerx = background.get_rect().centerx        background.blit(text, textpos)    screen.blit(background, (0,0))     pygame.display.flip() #background is now displayed    snow = Snow() #sprite instance    allsprites = pygame.sprite.RenderPlain((snow)) #container            #Main loop    while True:        #Event handling        clock.tick(60)        for event in pygame.event.get():            if event.type==QUIT:                kill()                return            if event.type==KEYDOWN:                if event.key==K_ESCAPE:                    kill()                    return                keys[event.key]=True            elif event.type==KEYUP:                keys[event.key]=False                print event        allsprites.update() #calls update function of all sprites               screen.blit(background, (0,0)) #redraw background        allsprites.draw(screen) #redraw sprites        pygame.display.flip() #show new screen        if __name__=="__main__": main()


It took me a while to figure out how it all worked but it was worth it.

Basically I still have the same image loading and quitting function and most of my event handler remains unchanged. Then I define my Snow class. All this class does is load the snow image and then keep track of its position for the update.

This time I define a surface background that will be used to draw the background to the screen. This will be very useful later for drawing the non-moving parts of a level.

I create an instance of Snow() and put it in a container allsprites. The container is not really necessary for this program but seems like a good practice that will make it less hardcoded.

Most of my event handler is the same. I have removed the keyboard input. The rest is painfully easy. I just have to update all the sprites. I would assume if any of my sprites were using preprogramed or AI based movement I could imbed that in the update() function of their class and handle all of it with just one line of code in the main loop (w00t!).

Finally I redraw the background, draw all the sprites (there is only one), and the flip the new screen into place.

So easy. So nice.

Previous Entry Draw Snow with WASD
0 likes 0 comments

Comments

Nobody has left a comment. You can be the first!
You must log in to join the conversation.
Don't have a GameDev.net account? Sign up!