如何解决我如何使蛇自行移动?蟒蛇
我希望蛇自动进食,但它不会动。我已经尝试过一些诸如使用while的事情。
while not exit_game:
while(snake_x < food_x):
velocity_x = init_velocity
velocity_y = 0
while(snake_x > food_x):
velocity_x = - init_velocity
velocity_y = 0
while(snake_y < food_y):
velocity_y = - init_velocity
velocity_x = 0
while(snake_y > food_y):
velocity_y = init_velocity
velocity_x = 0
解决方法
您尚未发布代码,因此我无法给您确切的答案,但这是使蛇食的一种方法。我们将假定蛇和食物仅是两个矩形。因此,首先,您需要知道蛇需要朝哪个方向移动才能获取食物。可以使用矢量来表示该方向。
directionx = snakex - foodx
directiony = snakey - foody
然后,您可以使用数学库中的atan2
函数来计算食物和蛇之间的角度。 This解释了atan2函数的工作方式。然后,您可以简单地计算该角度的正弦值并将其添加到蛇的y值,并将该角度的cos添加到蛇的x值。了解this为何起作用。
示例:
import pygame
import math
D = pygame.display.set_mode((1200,600))
snakex = 100
snakey = 100
foodx = 1000
foody = 500
while True:
D.fill((255,255,255))
pygame.event.get()
pygame.draw.rect(D,(0,0),(foodx,foody,20,20))#drawing our food
pygame.draw.rect(D,(snakex,snakey,20))#drawing our snake
directionx = foodx - snakex #Calculating the direction in x-axis
directiony = foody - snakey #Calculating the direction in y-axis
angle = math.atan2(directiony,directionx)# notice atan2 takes y first and then x
snakex += math.cos(angle)
snakey += math.sin(angle)
pygame.display.flip()
,
用if代替whiles。但是随后,您需要(在游戏的每次迭代中)将该速度添加到用于蛇位置的变量中。否则,它将不会移动。祝你好运!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。