python - 为什么我的正方形(蛇)只在对角线上移动?
问题描述
我正在编写 2 条蛇/汽车,而我的第一条蛇/汽车使用 WASD 键盘格式,运行良好。但是我的第二条蛇/汽车,它使用箭头键,只是沿对角线移动。我希望两条蛇/汽车都向各个方向移动(上、下、左、右和对角线),但现在,第二条蛇/汽车只对角线移动。
#initialize variables for player 1
car1x = 250
car1y = 300
car1width = 20
car1height = 20
car1dx = 0
car1dy = 0
speed = 3
#initialize variables for player 2
car2x = 500
car2y = 300
car2width = 20
car2height = 20
car2dx = 0
car2dy = 0
speed = 3
screen.fill(WHITE)
# set main loop to True so it will run
main = True
# main loop
while main:
for event in pygame.event.get(): # check for any events (i.e key press, mouse click etc.)
if event.type ==pygame.QUIT: # check to see if it was "x" at top right of screen
main = False # set the "main" variable to False to exit while loop
if event.type ==pygame.KEYDOWN:
if event.key == pygame.K_w:
car1dx = 0
car1dy = -speed
elif event.key == pygame.K_s:
car1dx = 0
car1dy = speed
elif event.key == pygame.K_a:
car1dx = -speed
car1dy = 0
elif event.key == pygame.K_d:
car1dx = speed
car1dy = 0
if event.key == pygame.K_UP:
car2dx = 0
car2dy = -speed
elif event.key == pygame.K_DOWN:
car2dx = 0
car2dy = speed
elif event.key == pygame.K_LEFT:
car2dx = -speed
car2dy = 0
elif event.key == pygame.K_RIGHT:
car2dx = speed
car2dy = 0
elif event.key == pygame.K_q:
pygame.quit()
if event.type == pygame.KEYUP:
if event.key in (pygame.K_w, pygame.K_s):
car1dx = 0
elif event.key in (pygame.K_a, pygame.K_d):
car1dy = 0
if event.key in (pygame.K_UP, pygame.K_DOWN):
car1dx = 0
elif event.key in (pygame.K_LEFT, pygame.K_RIGHT):
car1dy = 0
# move the x and y positions of the player
oldcar1x = car1x
oldcar1y = car1y
oldcar2x = car2x
oldcar2y = car2y
car1x = car1x + car1dx
car1y = car1y + car1dy
car2x = car2x + car2dx
car2y = car2y + car2dx
if car1x >= screenwidth:
car1x = oldcar1x
car1y = oldcar1y
if car2x >= screenwidth:
car2x = oldcar2x
car2y = oldcar2y
```
解决方案
在您的最终 if 语句中,看起来应该重置 Car2 的 dx/dy 的 KEYUP 事件正在设置 Car1 的 dx/dy 值。这可能是您的错误的来源。
推荐阅读
- gwt - GWT 错误:“gwt-module.dtd”中有“1”错误
- node.js - 如何在没有express的节点中使用greenlock模块
- raspberry-pi - 在树莓派启动两个 Discord Bot
- android - Android Emulator 由于内部错误而关闭:GPU Found
- javascript - 为什么我看不到渲染的元素在这里?
- python - Altair 复合图表(分层和连接)可以有不同的背景颜色吗?
- html - 按最大文本内容缩放表格列
- reactjs - 将第三方渲染道具组件转换为钩子
- sql - 如何删除特定表的所有记录,但最近 6 个月的数据除外
- ms-project - MS 项目 REST API