Hello I am new to pygame.
When I am trying to move my rect
right or left. The rectangle does not move from one position to other rather it expands/extends towards right or left.
Why?
import pygame, sys, time
pygame.init()
red = (255, 0, 0)
gameDisplay = pygame.display.set_mode((800, 600))
pygame.display.set_caption('MyGame')
move_x = 200
move_y = 200
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
move_x -= 10
if event.key == pygame.K_RIGHT:
move_x += 10
# pygame.Rect.move(10, 10)
# gameDisplay.fill(white, rect=[move_x, move_y, 10, 100])
pygame.draw.rect(gameDisplay, red, [move_x, move_y, 10, 10])
pygame.display.update()
pygame.display.flip()
Please see the image above. How it looks like after pressing right or left keys.
Use surface.fill before drawing.
The
[0, 0, 0]
I used is black in RGB codes. You should declare something likeAs a constant to avoid repetition. So please change that and use it like above.
Be careful not to draw anything before the
fill
method, it will be erased because you filled the screen with something else.Edit: I just realized you already defined
red
. It is probably better if you declared it all caps.RED
. Because it is a global constant as PEP-8 suggests.