我正在制作蛇游戏。每当我按箭头键向一个方向移动然后按另一个方向的键,蛇就会对角线。 (例如,如果我先按下然后按下。)即使释放了上一个键,也会发生这种情况。我怎么能阻止这个?
# x and y marks the player's position
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -10
if event.key == pygame.K_RIGHT:
x_change = 10
if event.key == pygame.K_UP:
y_change = -10
if event.key == pygame.K_DOWN:
y_change = 10
x += x_change
y += y_change
我添加了y_change = 0
和x_change = 0
来重置值以仅保持正交移动。
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -10
y_change = 0
if event.key == pygame.K_RIGHT:
x_change = 10
y_change = 0
if event.key == pygame.K_UP:
y_change = -10
x_change = 0
if event.key == pygame.K_DOWN:
y_change = 10
x_change = 0
x += x_change
y += y_change