Quickies – Introduction & Snake

About Quickies

Quickies are little game projects (usually clones of classic games) I mainly do as a practice for myself. Besides that I want to write about the challenges the project provided. On the respective project page you can also find playable builds of the game and the complete source code.
I try to do them in a rather short period of time so there might be bugs and rough edges. Please also notice that the source code is not perfect and I usually make some compromises in favor of a faster development time.

About and brief history

I guess I don’t have to say alot about the mechanics of snake. You control a snake within a fixed area and try to collect food. With every food “eaten” the snake grows. If you collide with the level boundaries or the snake itself you lose.

Snake originates from the game Blockade which was developed and published by Gremlin in 1976. It then was cloned and realeased by multiple companies. The first PC version, titled Worm, was programmed in 1978 by Perter Trefonas. (Source: wikipedia)

Creating the initial playable prototype took me about an hour or so. In total I spend something like two to three hours. The game looks pretty ugly I guess (programmer art)…

snake

Challenges

Snake is a pretty simple game of course but there are still some things to consider.

Movement
So the first “problem” was the movement of the snake. How do we make sure that each part of the snake gets the correct position in each frame? My solution was to iterate over each part but backwards. So starting with the last part of the snake, I simply assign the position of it’s predecessor. I iterate over all parts and do exactly the same – always assign the position of the part with index = index – 1. For the head of course there is no predecessor. So the head just get’s moved one unit depending on the user input.

for (int i = parts.Count - 1; i > 0; i--)
{
GameObject prev = parts[i - 1];
parts[i].transform.position = prev.transform.position;
}
parts[0].transform.position += dir;

Growth
The second thing I had to think about was increasing the size of the snake whenever the player collects food. What position do I assign to the new part? This can easily be achieved by calculating the position of last part – the position of the second last and then adding this to the position of the last part.

Vector3 newPos;
[...]
Vector3 diff = lastPart.transform.position - lastPartMinusOne.transform.position;
newPos = lastPart.transform.position + diff;

Link

The project page contains everything related to this game. It includes a playable WebGL version as well as a downloadable version for windows. The source code is also provided and can be downloaded.

That’s it for this quickie. Stay tuned for the next one!

Leave a Reply