如何让蛇在上面移动´;他自己的?python
我想让蛇自动去拿食物,但它不动。我试过几种方法,比如使用while如何让蛇在上面移动´;他自己的?python,python,python-3.x,pygame,Python,Python 3.x,Pygame,我想让蛇自动去拿食物,但它不动。我试过几种方法,比如使用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(s
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
不退出游戏时:
而(蛇x<食物x):
速度x=初始速度
速度_y=0
而(蛇>食物):
速度x=-初始速度
速度_y=0
而(蛇肉<食物):
速度y=-初始速度
速度_x=0
而(蛇>食物):
速度y=初始速度
速度_x=0
将whiles替换为if。但接下来你需要(在游戏的每次迭代中)将速度添加到你用于蛇位置的变量中。否则,它不会移动。祝你好运 你还没有发布代码,所以我不能给你确切的答案,但这里有一种方法可以让蛇去吃东西。我们假设蛇和食物只是两个矩形。因此,首先你需要知道你的蛇需要向哪个方向移动才能获得食物。这个方向可以用向量表示
directionx = snakex - foodx
directiony = snakey - foody
然后,您可以使用数学库中的atan2
函数计算出食物和蛇之间的角度。解释atan2函数的工作原理。然后,您可以简单地计算该角度的sin,并将其添加到蛇的y值,然后将该角度的cos添加到蛇的x值。看看为什么有效
例如:
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, 0), (foodx, foody, 20, 20))#drawing our food
pygame.draw.rect(D, (0, 0, 0), (snakex, snakey, 20, 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()
只有外环应该保留。其他whiles应替换为if。(但这一切都取决于此处未显示的代码)