How do I make the snake move on it´s own? Python

Viewed 182

I want the snake to go automatically for the food, but it doesnt move. I´ve tried several things like using 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 Answers

You haven't posted the code so i cannot give you the exact answer but here is one way to make a snake go to the food. We will assume that snake and food are just 2 rectangles. So firstly you will need to know what direction your snake needs to move in to get the food. This direction can be represented using vectors.

directionx = snakex - foodx
directiony = snakey - foody

Then you can work out the angle between the food and the snake using the atan2 function from math library. This explains how atan2 function works. Then you can simply calculate the sin of that angle and add it to the y-value of the snake and add cos of that angle to x-value of the snake. See why this works.

Example:

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

Replace whiles with if's. But then you need to add (at every iteration of the game) that velocity to the variables you use for snake position. Otherwise, it won't move. Good luck!

Related