我在 replit.com 中使用 pygame,每当我运行它时,它都不会显示任何错误,但左键和下键不起作用。我不明白我做错了什么。
import pygame pygame.init() width, height = 800, 600 backgroundColor = 33, 33, 33 color = (0, 128, 255) screen = pygame.display.set_mode((width, height)) player_x = 30 player_y = -30 while True: screen.fill(backgroundColor) for event in pygame.event.get(): if(event.type == pygame.KEYDOWN): if(event.key == pygame.K_RIGHT): player_x += 10 for event in pygame.event.get(): if(event.type == pygame.KEYDOWN): if(event.key == pygame.K_LEFT): player_x -= 10 for event in pygame.event.get(): if(event.type == pygame.KEYDOWN): if(event.key == pygame.K_DOWN): player_y += 10 pygame.draw.rect(screen, color, pygame.Rect(player_x, 30, 60, 60)) pygame.display.update()```
首先,您必须修改while循环中的代码。这里不需要多个for循环,只需在一个for循环中检查用户输入即可。同样在while循环的倒数第二行,您还没有考虑玩家的 y 轴移动,即player_y.
while
for
player_y
最后,就在while循环上方的行中,将播放器的 y 坐标设置为,30而不是-30使其完全显示在屏幕上。
30
-30
player_y = 30 while True: screen.fill(backgroundColor) for event in pygame.event.get(): if(event.type == pygame.KEYDOWN): if(event.key == pygame.K_RIGHT): player_x += 10 if(event.key == pygame.K_LEFT): player_x -= 10 if(event.key == pygame.K_DOWN): player_y += 10 pygame.draw.rect(screen, color, (player_x, player_y, 50, 50)) pygame.display.update()