Search code examples
eventspygamekeybreakout

Breakout game with Pygame - Processing events


I'm currently trying to create a simple version of the game Breakout with Pygame. The problem is that I want to make my bat move on the screen, and for this I need to deal with events and the fact that, when you press the right/left arrow, the bat instantly moves right/left. However my code is not working; the length of the bat is increasing rather than simply moving whenever I press the key. I've looked through of codes and examples, but I'm still lost.

Here's my code:

import pygame, sys

pygame.init()

width, height = 800, 600
screen = pygame.display.set_mode([width, height])
bat_speed = 30
bat = pygame.image.load('bat.png').convert()
batrect = bat.get_rect()

while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:                        
                batrect = batrect.move(-bat_speed, 0)     
                if (batrect.left < 0):                           
                    batrect.left = 0      
            if event.key == pygame.K_RIGHT:                    
                batrect = batrect.move(bat_speed, 0)
                if (batrect.right > width):                            
                    batrect.right = width

    screen.blit(bat, batrect)
    pygame.display.flip()

pygame.quit()

Solution

  • When you blit something on the screen it'll stay there. What's happening is that you're blitting the bat at different locations, making it seem like the width of the bat increases. Simple fix would be to clear the screen before you draw the bat.

    while 1:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:                        
                    batrect = batrect.move(-bat_speed, 0)     
                    if (batrect.left < 0):                           
                        batrect.left = 0      
                elif event.key == pygame.K_RIGHT:                    
                    batrect = batrect.move(bat_speed, 0)
                    if (batrect.right > width):                            
                        batrect.right = width
    
        screen.fill((0, 0, 0))  # This will fill the screen with a black color.
        screen.blit(bat, batrect)
        pygame.display.flip()
    

    Also, use elif instead of multiple if when you don't want to check every condition, like I did above.