import pygame def run_game(): ## Initialize the pygame submodules and set up the display window. pygame.init() width = 800 height = 800 my_win = pygame.display.set_mode((width,height)) ## Load resources player_l = pygame.image.load("worm_left.gif") player_l = player_l.convert() player_r = pygame.image.load("worm_right.gif") player_r = player_r.convert() ## Initialize game objects. # the player x = 0 y = 0 xspeed = 0 yspeed = 0 w = player_r.get_width() h = player_r.get_height() player_pic = player_r # the obstacle (creating a rectangle at x=200, y=100 with width=200 and height=100) obstacle_rect = pygame.Rect(200, 100, 200, 100) clock = pygame.time.Clock() ## GAME LOOP starts keepGoing = True while (keepGoing): ## handle events for event in pygame.event.get(): if event.type == pygame.QUIT: keepGoing = False # intercept key presses and use 'wasd' to move the player elif event.type == pygame.KEYDOWN: key = pygame.key.name(event.key) if key == "w": yspeed = -0.2 elif key == "s": yspeed = 0.2 elif key == "a": xspeed = -0.2 elif key == "d": xspeed = 0.2 # intercept key releases to stop motion appropriately elif event.type == pygame.KEYUP: key = pygame.key.name(event.key) if key == "w" and yspeed < 0: yspeed = 0 elif key == "s" and yspeed > 0: yspeed = 0 elif key == "a" and xspeed < 0: xspeed = 0 elif key == "d" and xspeed > 0: xspeed = 0 ## update game objects dt = clock.tick() x = x + xspeed * dt y = y + yspeed * dt if xspeed > 0: player_pic = player_r elif xspeed < 0: player_pic = player_l # otherwise, if xspeed==0 we keep the picture as it is # check whether player is colliding with the light green patch # if so move player back to beginning player_rect = pygame.Rect(x, y, w, h) if player_rect.colliderect(obstacle_rect): x = 0 y = 0 xspeed = 0 yspeed = 0 print "Ouch!!!" ## draw picture and update display my_win.fill(pygame.color.Color("darkgreen")) pygame.draw.rect(my_win, (0, 255, 0), obstacle_rect) my_win.blit(player_pic, (x, y)) pygame.display.update() ## GAME LOOP ends pygame.quit() run_game()