我如何使蛇自行移动?蟒蛇

时间:2020-08-23 15:19:31

标签: 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(snake_y < food_y):
        velocity_y = - init_velocity
        velocity_x = 0

    while(snake_y > food_y):
        velocity_y = init_velocity
        velocity_x = 0

2 个答案:

答案 0 :(得分:2)

您尚未发布代码,因此我无法给您确切的答案,但这是使蛇食的一种方法。我们将假定蛇和食物仅是两个矩形。因此,首先,您需要知道蛇需要朝哪个方向移动才能获取食物。可以使用矢量来表示该方向。

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, 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()

答案 1 :(得分:0)

用if代替whiles。但是随后,您需要(在游戏的每次迭代中)将该速度添加到用于蛇位置的变量中。否则,它将不会移动。祝你好运!