Java – Making a snake

As you probably know, I am an online student at the Software University in Bulgaria, Sofia.

This week, we had to submit a simple game in Java, developed by me and 4 other online students as a team. After some dispute, we all have agreed to make a snake. I will not go into details, why none of us was able to make it for the presentation of the game and I will simply present the code of the game. Considering the fact, that none of the code is written by me, as far as I am still a learner in Java (and I had some quite lame problems installing Eclipse), the main target of this article is to analyze the code line by line and to understand how it actually works.

If you just want to play the snake, I have used this manual here to create an exe file. The *.exe file is located here.

So, let’s start with the code. It would be quite challenging to try to understand how it works. Anyway, I will give it a try!

Mainly, we have 2 classes – 1 main class, called and another one, concerning the panel in which the game is shown. So, we start with the main class:

The second class is RenderPanel.Java:

So, how does it work?

The first thing, which is executed is the main method in

It instantiates a new object Snake. The new object is created with the following characteristics:

Once, the object is created, we see the magic happening. It generates a new object jframe, setting default visibility, size and location. Then it adds and instantiates a new render panel with the line:

Then it adds keyListener (with this we manage to navigate the snake) and it starts the game with the startGame() line. The start Game method looks like this:

In start game we see some initiation of objects – head, random and apple are initiated. So, where is the magic, moving the snake? It is in the public snake, where we create a instantiate a new RenderPanel. Once, we instantiate it, we go to the class, where we paint it with given colors.

So far so good! The game is outstanding, enjoy it!

Tagged with: , ,