如何使一个矩形物体在屏幕上缓慢移动



我是python编程的新手,现在开始编写简单的"蛇;游戏我试图让蛇头在屏幕上移动当按下箭头键时,头部应该不停地向那个方向移动,直到垂直按下箭头。我无法使蛇头(长方形(在一个方向上缓慢地不停地移动。我试着使用time.sleep((-->它使得整个代码被卡住了。我尝试使用for循环-->它只是让矩形快速地传输到另一个方向。

这是我的主要功能:

while not GameOver:
#create time delay of 10 milliseconds
pygame.time.delay(10)
# Get all of the events on the game's screen [all of the user's input]
# Loop on the user's activity and look for exit button pressing.
for event in pygame.event.get():
# If the user presses the X button:
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Define a shortcut name to "get_pressed" method in pygame:
keys = pygame.key.get_pressed()
# defining x location
x = head_position[0]
y = head_position[1]
# if he pressed left key
if keys[pygame.K_LEFT]:
# reducing location by constant
head_position[0] -= head_speed
elif keys[pygame.K_RIGHT]:
# increacing location by constant
head_position[0] += head_speed

elif keys[pygame.K_UP]:
# increacing location by constant
head_position[1] -= head_speed

elif keys[pygame.K_DOWN]:
# increacing location by constant
head_position[1] += head_speed
#If the head passes the screen Boundaries, it would pop in the other side.
if head_position[0] >= WIDTH:
head_position[0] = 0
elif head_position[0] < 0:
head_position[0] = WIDTH-head_size
elif head_position[1] >= HEIGHT:
head_position[1] = 0
elif head_position[1] < 0:
head_position[1] = HEIGHT-head_size

使用pygame.time模块控制每秒帧数。生成pygame.time.Clock对象。如果您将可选的帧速率参数传递给pygame.time.Clock.tick,该函数将延迟以保持游戏运行速度低于每秒给定的节拍:

clock = pygame.time.Clock()
while not GameOver:
clock.tick(10) # 10: the game runs with 10 frames per second
# [...]

如果你想让它在一次按键后以恒定的速度向一个方向移动,那么right=错误变量然后做一个密钥[pygame.K_YOURCHOICE]:right=真实

如果正确:head_pos[1或0]-=head_speed

相关内容

  • 没有找到相关文章

最新更新