Snake Game Using Python

AI Snake Game using Python

Snake Game using Python:-

The single-player variant of Snake is a well-known and popular video game that requires a player to navigate a line-based representation of a snake through a two-dimensional playing area while avoiding collisions with the walls of the playing area and the body of the snake itself.

A score and the snake length are increased whenever the snake is moved through items representing food

Installing Libraries:-

Pygame: pip install pygame

Reinforcement  Learning:-

Reinforcement learning (RL) is an area of machine learning concerned with how software agents ought to take actions in an environment in order to maximize the notion of cumulative reward.

Greedy Solver in Snake Game Using Python – Path Solver:-

  • The snake eats the food along the shortest path if it thinks the snake will be safe.
  • Otherwise, it makes the snake wander around until a safe path can be found.
  • As it needs path searching, it depends on [Path Solver]

Hamilton solver in Snake Game – Path Solver:-

  • This builds a Hamiltonian cycle on the game map first and directs the snake to eat the food along the cycle path.
  • To reduce the intermediate steps the snake takes to success, it enables the snake to take shortcuts if possible.
  • Again, it depends on finding the longest path.

Non-ML Techniques

  • The game Snake actually has a trivial, unbeatable solution. Create a cyclic path that goes through every square on the board without crossing itself (this is known as a Hamiltonian Cycle), and then just keep following this cyclical path until the snake’s head is as long as the entire path. This will work every time, but it is very boring and also wastes a lot of moves. In an NxN grid, it will take ~N² apples to grow a tail long enough to fill the board.
  • If the apples appear randomly, we would expect that the snake will need to pass through half the currently open squares to reach the apple from its current position or around N²/2 moves at the start of the game. Since this number decreases as the snake gets longer, we expect that on average, the snake will need ~N⁴/4 moves to beat the game using this strategy. This is about 40,000 moves for a 20×20 board.

Source Code of Manul Snake Game using Python:-

import pygame, random, sys
from pygame.locals import *
def collide(x1, x2, y1, y2, w1, w2, h1, h2):

if x1+w1>x2 and x1<x2+w2 and y1+h1>y2 and y1<y2+h2:
return True
return False

def die(screen, score):

f=pygame.font.SysFont('Arial', 30);t=f.render('Your score was: '+str(score), True, (0, 0, 0));screen.blit(t, (10, 270));pygame.display.update();pygame.time.wait(2000);sys.exit(0)

xs = [290, 290, 290, 290, 290];ys = [290, 270, 250, 230, 210];dirs = 0;score = 0;
applepos = (random.randint(0, 590), random.randint(0, 590));

s=pygame.display.set_mode((600, 600));
appleimage = pygame.Surface((10, 10));
appleimage.fill((0, 255, 0));
img = pygame.Surface((20, 20));
img.fill((255, 0, 0));
f = pygame.font.SysFont('Arial', 20);
clock = pygame.time.Clock()
while True:

for e in pygame.event.get():

if e.type == QUIT:

elif e.type == KEYDOWN:

if e.key == K_UP and dirs != 0:dirs = 2
elif e.key == K_DOWN and dirs != 2:dirs = 0
elif e.key == K_LEFT and dirs != 1:dirs = 3
elif e.key == K_RIGHT and dirs != 3:dirs = 1

i = len(xs)-1
while i >= 2:

if collide(xs[0], xs[i], ys[0], ys[i], 20, 20, 20, 20):
die(s, score)
i-= 1

if collide(xs[0], applepos[0], ys[0], applepos[1], 20, 10, 20, 10):


if xs[0] < 0 or xs[0] > 580 or ys[0] < 0 or ys[0] > 580:

die(s, score)

i = len(xs)-1
while i >= 1:

xs[i] = xs[i-1];ys[i] = ys[i-1];i -= 1

if dirs==0:ys[0] += 20
elif dirs==1:xs[0] += 20
elif dirs==2:ys[0] -= 20
elif dirs==3:xs[0] -= 20
s.fill((255, 255, 255))
for i in range(0, len(xs)):

s.blit(img, (xs[i], ys[i]))

s.blit(appleimage, applepos);t=f.render(str(score), True, (0, 0, 0));s.blit(t, (10, 10));pygame.display.update()


Source Code of AI Snake Game using Python:-

from import Game, GameConf, GameMode

greedy = "GreedySolver"
hamilton = "HamiltonSolver"

normal = GameMode.NORMAL

conf = GameConf()
conf.solver_name = hamilton
conf.mode = normal
print("Solver: %s " % (conf.solver_name))
print("Mode: %s" %(conf.mode))

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.