HomeTurtlegraficsGPanelRoboticsGameGrid WebTigerPython
 Python - Online
snakeGame
Deutsch   English   

SNAKE GAME

 

 

GAME DESCRIPTION

 

Snake is a well-known computer game in which you control a snake through a playing field so that it can find food. The snake grows longer with every bite of food.

Our implementation adheres to the following game rules:

  • The snake can be moved using the cursor keys
  • The mouse is automatically generated at a random position in the grid
  • After each mouse is eaten, the snake grows one segment longer and a new mouse is generated
  • f the snake collides with the edge or its tail, it's Game Over
  • Goal: Create the longest snake possible.

 

 

You can adjust the speed of movement by changing the simulation period (400).

The snake consists of a head and a tail, which consists of a number of parts (TailSegment). Only the head is controlled with the cursor keys; the remaining parts follow. Programming this following behaviour is the most difficult part of this task. The segments are stored in a list called tail. This list allows the growing snake to be displayed elegantly. The individual tail segments are moved by accessing the individual list elements via an index.  

Program:

# SnakeGame.py

from gamegrid import *

# ---------------- class Snake ----------------
class Snake(Actor):
    def __init__(self):
         Actor.__init__(self, True, "sprites/snakehead.gif")
         self.tail = [] 

    def reset(self):
        for i in range(2):
           segment = TailSegment()
           addActor(segment, Location(snake.getX(), snake.getY() + i + 1))
           self.tail.append(segment)      

    def tryToEat(self, lastLocation):
        actor = getOneActorAt(self.getLocation(), Food)
        if actor != None:
            newSegment = TailSegment()
            addActor(newSegment, lastLocation)
            self.tail.append(newSegment)
            actor.removeSelf()
            addActor(Food(), getRandomEmptyLocation())
  
    def act(self): 
        lastIndex = len(self.tail) - 1
        if lastIndex > -1:
            lastLocation = self.tail[lastIndex].getLocation()
            for i in range (lastIndex, 0, -1):
                self.tail[i].setLocation(self.tail[i-1].getLocation())
            self.tail[0].setLocation(self.getLocation())
        
        self.move() 

        a = getOneActorAt(self.getLocation(), TailSegment)
        if not self.isInGrid() or a != None:
             removeAllActors()
             addActor(Actor("sprites/gameover.gif"), Location(9, 9))
             return   

        self.tryToEat(lastLocation)  

# ---------------- class Tailsegment----------------
class TailSegment(Actor):
    def __init__(self):
        Actor.__init__(self, "sprites/snaketail.gif")
 
# ---------------- class Food ----------------
class Food(Actor):
    def __init__(self):
        Actor.__init__(self, "sprites/mouse.gif")
 
def keyCallback(keyCode):
        if keyCode == 38: # UP
            snake.setDirection(270)
        if keyCode == 40: # DOWN
            snake.setDirection(90)
        if keyCode == 39: # RIGHT
            snake.setDirection(0)
        if keyCode == 37: # LEFT
            snake.setDirection(180)  
 
makeGameGrid(20, 20, 20, Color.gray, False, keyRepeated = keyCallback)
snake = Snake()
addActor(snake, Location(10,10))
snake.setDirection(Location.NORTH)
food = Food()
addActor(Food(), getRandomEmptyLocation())
show()
setSimulationPeriod(400)
doRun()
► Copy to clipboard

 

 

Explanations of the programme code

 
1. self.tail = []: is an empty list, intended to store the tail segments. tail is an instance variable of the Snake class, therefore self must be prefixed
2. tail.append(segment): adds a segment to the list
3.
reset(self): the reset() method is called automatically when the actor is added to the game grid
4. addActor(segment, Location(snake.getX(), snake.getY() + i + 1)): adds a segment to the game window at the position below the snake's head

5. lastIndex = len(tail) - 1: the snake is moved by giving the last segment the position of the previous link, which in turn gets the position of the previous one, and so on. The first segment gets the position of the snake's head. Since the index numbers of a list always start at 0, the last index is 1 less than the number of list elements

6. lastLocation = tail[lastIndex].getLocation(): position of the last sub-segment (used to position the new segment when eating)

7. for i in range(lastIndex, 0, -1):
tail[i].setLocation(tail[i-1].getLocation()) : the tail segments are moved, starting with the last sub-segment

8. tail[0].setLocation(self.getLocation()): segment with index 0 gets the position of the head

9. not self.isInGrid() : causes GameOver

10. a = getOneActorAt(self.getLocation(), TailSegment): if there is an actor TailSegment at the position of the snake's head, the snake has run over its tail, which also results in GameOver