1

guys. I'm writing 'Atari Breakout' game in pygame. How can I move this paddle with keys?

paddle = pygame.Rect(300, 220, 40, 5)
pygame.draw.rect(screen, WHITE, paddle, 0)

I've tried a few ways from stackoverflow, but nothing works.

Can you help me write function that moves paddle to right and left, when I'm pressing keys on keyboard, please?

That's my code:

import sys
import pygame

pygame.init()

FRAME_SIZE = (600, 400)

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)

screen = pygame.display.set_mode(FRAME_SIZE)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    screen.fill(BLACK)

    #objects
    game_frame = pygame.Rect(100, 50, 400, 200)
    pygame.draw.rect(screen, WHITE, game_frame, 5)
    paddle = pygame.Rect(300, 220, 40, 5)
    pygame.draw.rect(screen, WHITE, paddle, 0)
    ball = pygame.Rect(300, 200, 5, 5)
    pygame.draw.rect(screen, RED, ball, 0)

    pygame.display.flip()

1 Answers1

0

Create the pygame.Rect objects before the application loop. Change the position of the rectangles in the loop when a key is pressed:

keys = pygame.key.get_pressed()
paddle.x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * 5

Limit the position of the paddle with the frame:

paddle.left = max(paddle.left, game_frame.left)
paddle.right = min(paddle.right, game_frame.right)

Minimal example:

import sys
import pygame

FRAME_SIZE = (600, 400)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)

pygame.init()
screen = pygame.display.set_mode(FRAME_SIZE)
clock = pygame.time.Clock()

game_frame = pygame.Rect(100, 50, 400, 200)
paddle = pygame.Rect(300, 220, 40, 5)
ball = pygame.Rect(300, 200, 5, 5)

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
            
    keys = pygame.key.get_pressed()
    paddle.x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * 5
    paddle.left = max(paddle.left, game_frame.left)
    paddle.right = min(paddle.right, game_frame.right)

    screen.fill(BLACK)
    pygame.draw.rect(screen, WHITE, game_frame, 5)
    pygame.draw.rect(screen, WHITE, paddle, 0)
    pygame.draw.rect(screen, RED, ball, 0)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
sys.exit()
Rabbid76
  • 177,135
  • 25
  • 101
  • 146