Snake Game

Snake game concept and mechanics

Snake is a popular and simple game found in many variations across most platforms that support graphics. From the oldest mobiles capable of supporting games to any modern OS, and arcade machines that predate both, you'll be able to find this addicting game.

Play the Snake example

This example will give code with comments and descriptions of function, however, it assumes the reader has a reasonable knowledge of programming.

The premise to this game is simple:

  • The game takes place in an enclosed area
  • The snake is made of segments that follow one another; each segment will effectively take the same path as the head (front of the snake)
  • The snake is always moving - the player simply changes the direction of movement
  • Randomly placed "food" appears on the map
  • When the snake touches the food, it consumes it. The length of the snakes body increases, and the player gains a point
  • If the snake touches the outer perimeter of the map, or another part of its own body, the game ends

With this in mind, our game must complete the following basic process whilst the game is running:

while [not lost game]:
	if [user direction input]: change direction

	nextPos = [position of snake head] + [movement in current direction]

	if nextPos==[outside map bounds]: lost game
	if nextPos==[in snake body except last entry]: lost game

	[snake body].prepend( nextPos )

	if nextPos==foodPos:
		foodPos = [random map position, not on snake]
		increase score
		[snake body].pop()

With this in mind, lets look at how our snake game is put together.

Page loaded in 0.007 second(s).