diff --git a/pacman.py b/pacman.py index 0a2d738..3b2ef03 100644 --- a/pacman.py +++ b/pacman.py @@ -20,8 +20,15 @@ # rectangle around pacman pacmanrect = pacman.get_rect() -# pacman not moving initially -moving = False +# pacman not moving or touching walls initially +move_left = False +move_right = False +move_up = False +move_down = False +touch_left = False +touch_right = False +touch_top = False +touch_bottom = False # the game loop while 1: @@ -30,23 +37,54 @@ if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: - moving = True - speed = [-8, 0] + move_left = True + # moving left ensures not touching right wall + touch_right = False + # set all other directions to be false + move_right = False + move_up = False + move_down = False if event.key == pygame.K_RIGHT: - moving = True - speed = [8, 0] + move_right = True + touch_left = False + # set all other directions to be false + move_left = False + move_down = False + move_up = False if event.key == pygame.K_UP: - moving = True - speed = [0, -8] + move_up = True + touch_bottom = False + # set all other directions to be false + move_right = False + move_left = False + move_down = False if event.key == pygame.K_DOWN: - moving = True - speed = [0, 8] - if moving: - pacmanrect = pacmanrect.move(speed) - if pacmanrect.left < 0 or pacmanrect.right > width: - moving = False - if pacmanrect.top < 0 or pacmanrect.bottom > height: - moving = False + move_down = True + touch_top = False + # set all other directions to be false + move_up = False + move_left = False + move_right = False + if move_left and not touch_left: + pacmanrect = pacmanrect.move([-8,0]) + if move_right and not touch_right: + pacmanrect = pacmanrect.move([8,0]) + if move_up and not touch_top: + pacmanrect = pacmanrect.move([0, -8]) + if move_down and not touch_bottom: + pacmanrect = pacmanrect.move([0, 8]) + if pacmanrect.left < 0: + move_left = False + touch_left = True + if pacmanrect.right > width: + move_right = False + touch_right = True + if pacmanrect.top < 0: + move_top = False + touch_top = True + if pacmanrect.bottom > height: + move_bottom = False + touch_bottom = True screen.fill(black) screen.blit(pacman, pacmanrect)