Adam Rose Adam Rose - 2 months ago 6
Python Question

Issue with keyboard events or other

I'm trying to make a box move around on the screen using the arrow keys. Though when I press the arrow keys, nothing happens. Since I can't see, where I am doing something wrong, and I cant find a visualizer that supports pygame, I will have to ask you. Here is the code:

import pygame, sys

FPS = 60
Clock = pygame.time.Clock()


SURF = pygame.display.set_mode((600, 700))
pygame.display.set_caption("BOX GAME V1.0")

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

box_x = 50
box_y = 50

box = (box_x, box_y, 50, 50)

while True:
SURF.fill(BLACK), RED, (200, 150), 25)
pygame.draw.rect(SURF, WHITE, box)

for event in pygame.event.get():
if event.type == pygame.QUIT:
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
box_x -= 20
elif event.key == pygame.K_RIGHT:
box_x += 20
elif event.key == pygame.K_UP:
box_y -= 20
elif event.key == pygame.K_DOWN:
box_y += 20



I'm assuming that the game runs and the box doesn't move despite your keyboard input. If I'm right then it's the fact that you aren't updating the box position each time through the while loop.

The line pygame.draw.rect(SURF, WHITE, box) references the box that you define before starting the game loop, but this box's position doesn't get updated. Just update the box position before drawing it. This can be done by moving box = (box_x, box_y, 50, 50) to the top of the game loop.

while True:
    box = (box_x, box_y, 50, 50)

    SURF.fill(BLACK), RED, (200, 150), 25)
    pygame.draw.rect(SURF, WHITE, box)

    ### key press logic