我目前正在尝试使用 Pygame 创建一个简单版本的 Breakout 游戏。问题是我想让我的球棒在屏幕上移动,为此我需要处理事件以及当你按下右/左箭头时球棒立即右/左移动的事实。但是我的代码不起作用;每当我按下键时,球棒的长度就会增加,而不是简单地移动。我已经浏览了代码和示例,但我仍然迷路了。
这是我的代码:
import pygame, sys
pygame.init()
width, height = 800, 600
screen = pygame.display.set_mode([width, height])
bat_speed = 30
bat = pygame.image.load('bat.png').convert()
batrect = bat.get_rect()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
batrect = batrect.move(-bat_speed, 0)
if (batrect.left < 0):
batrect.left = 0
if event.key == pygame.K_RIGHT:
batrect = batrect.move(bat_speed, 0)
if (batrect.right > width):
batrect.right = width
screen.blit(bat, batrect)
pygame.display.flip()
pygame.quit()