| Deutsch English |
![]()
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:
You can adjust the speed of movement by changing the simulation period (400).
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() |
Explanations of the programme code |
|
![]()