Reputation: 35
I am using the pygame module to make a simple game. Currently, I am trying to get a rectangle to move across my 500x500 screen, but it is only moving in x value (left and right).
Here's my code:
import pygame
pygame.init()
# Colors
white = (255, 255, 255)
black = (0, 0, 0)
blue = (0, 0, 255)
# Game Screen Dimensions
game_layout_length = 500
game_layout_width = 500
# Character Attributes
character_length = 10
character_width = 10
character_x = 0
character_y = 0
game_screen = pygame.display.set_mode((game_layout_width, game_layout_length))
game_close = False
game_lost = False
while not game_close:
while not game_lost:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_close = True
game_lost = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
character_x -= 10
elif event.key == pygame.K_RIGHT:
character_x += 10
elif event.key == pygame.K_DOWN:
character_y -= 10
elif event.key == pygame.K_UP:
character_y += 10
pygame.draw.rect(game_screen, blue, [character_x, character_y, character_length, character_width])
pygame.display.update()
print(f'{character_x, character_y}')
pygame.quit()
quit()
The line print(f'{character_x, character_y}')
is a debug line, and it shows that the value of "character_y" is changing, so I'm stuck trying to find out where the problem is.
Upvotes: 1
Views: 92
Reputation: 925
For moving down you need to increase the y and not decrease it and for moving up you need to decrease the y. Also you can fill the screen at each render to avoid the trailing rectangles.
import pygame
pygame.init()
# Colors
white = (255, 255, 255)
black = (0, 0, 0)
blue = (0, 0, 255)
# Game Screen Dimensions
game_layout_length = 500
game_layout_width = 500
# Character Attributes
character_length = 10
character_width = 10
character_x = 0
character_y = 0
game_screen = pygame.display.set_mode((game_layout_width, game_layout_length))
game_close = False
game_lost = False
while not game_close:
while not game_lost:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_close = True
game_lost = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
character_x -= 10
elif event.key == pygame.K_RIGHT:
character_x += 10
elif event.key == pygame.K_DOWN:
character_y += 10
elif event.key == pygame.K_UP:
character_y -= 10
game_screen.fill(black)
pygame.draw.rect(game_screen, blue, [character_x, character_y, character_length, character_width])
pygame.display.update()
print(f'{character_x, character_y}')
pygame.quit()
quit()
Upvotes: 1