Reputation: 31
import pygame
pygame.init()
gameDisplay= pygame.display.set_mode((800,600))
pygame.display.set_caption("My game!")
gameEnd = False
gameDisplay.fill(white)
pygame.draw.rect(gameDisplay, black, [400,300,10,10])
pygame.display.update()
lead_x = 300
lead_y = 300
while not gameEnd:
for start in pygame.event.get():
if start.type == pygame.QUIT:
gameEnd = True
if start.type == pygame.KEYDOWN:
if start.key == pygame.K_LEFT:
lead_x -= 10
if start.key == pygame.K_RIGHT:
lead_x += 10
pygame.quit()
Upvotes: 3
Views: 63
Reputation: 211239
You've to use the coordinates (lead_x
, lead_y
) in the call of pygame.draw.rect
.
Clearing the display (.fill()
), drawing the rectangle (pygame.draw.rect()
) and the update of the display (pygame.display.update()
) has to be done in the main loop. So the window is continuously redrawn and the rectangle is drawn at the current position in every frame:
import pygame
pygame.init()
gameDisplay= pygame.display.set_mode((800,600))
pygame.display.set_caption("My game!")
black = ( 0, 0, 0)
white = (255,255,255)
lead_x = 300
lead_y = 300
gameEnd = False
while not gameEnd:
for start in pygame.event.get():
if start.type == pygame.QUIT:
gameEnd = True
if start.type == pygame.KEYDOWN:
if start.key == pygame.K_LEFT:
lead_x -= 10
if start.key == pygame.K_RIGHT:
lead_x += 10
# clear window
gameDisplay.fill(white)
# draw rectangle at the current position (lead_x, lead_y)
pygame.draw.rect(gameDisplay, black, [lead_x,lead_y,10,10])
# update the display
pygame.display.update()
Upvotes: 3