[英]The y value of my rectangle is not changing in pygame
I am using the pygame module to make a simple game.我正在使用 pygame 模块来制作一个简单的游戏。 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).
目前,我正在尝试让一个矩形在我的 500x500 屏幕上移动,但它只在 x 值(左右)中移动。
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. print(f'{character_x, character_y}')
行是调试行,它显示“character_y”的值正在变化,所以我一直试图找出问题所在。
For moving down you need to increase the y and not decrease it and for moving up you need to decrease the y.对于向下移动,您需要增加 y 而不是减少它,对于向上移动,您需要减少 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.