Subscribe via Email:

 Snake Game using Java Applet

 Written by on 26 January 2011


Problem Definition: To develop a snack game using java applet.

Data Structure: A Queue with 2-D array .

Logic Description :

 

Handling Lines:

  • In this program Queue is implemented with 2-D array which contains f (front) and r (rear) to point head and tail of snake.
  • Seven variables shown in below image contain data about each of line that the snake moves according to key pressed.


  • The value of ‘ f ’ is incremented when a new line of the snake is generated. And ‘ r ’ is incremented when the last line of snake gets its length to zero, as shown below.

  • As Shown in above figure when up button pressed ‘ f ‘ is incremented from index 0 to 1 and all seven variable rows will be initialized as below:
    1. (x1,y1) will be copied to (x0,y0) and (x1,y1) of new line
    2. length will be 0, and incremented in iteration.
    3. Direction will be set according the key pressed.

  • The length of a line to which ‘ r ‘ points will be decremented in each iteration.
  • When a new line pointed by ‘ f ‘ goes over the boundary of screen a new line is generated from opposite side in a same direction of previous one ,  and   now ‘ f ‘ will point to that newly generated line.
  • And rows data for new entry is initialized.

Get the Point:

  • A random function is used to generate the point that going to be eaten by snake.
  • To make it visible enough u can make rectangle of 1X1, so that it acquires 4 pixel and can be visible enough.
  • When header point (x1,y1) of  ‘ f ‘ line meets the randomly generated point/rectangle length of 'r ’ line is incremented, no other changes require.

Handling Collision:

  • In this section it is checked that, whether the header point of ‘ f ‘ line is meets to any existing point of snake.
  • For that whole the Queue from ‘ r ‘ to ‘ f ‘ is traced.

It divides this checking in two parts,

First one, for all the lines having upward or downward direction (with Direction flag 2 or 4).


  1. First we needs to check whether X-coordinate of header point(x1,y1) and X-coordinate of existing line is same or not?
  2. If its not then there will no match, but if it is same than we have two option as shown in above figure.
  3. For that now we needs to check for Y-coordinate of header point and existing ling by trashing from y0 to y1 for each vertical existing line.
  • Same method can be applied for next option for Horizontal lines with direction of Right side or left side (Direction flag 1 or 3).


You can find the code & game, by clicking here.

Enjoy gaming with Java Applet!

 

Recommended "Tech" Blogs!

Recommended "Sports" Blogs!

Recommended Websites!

ADIT College Websitee>
iMindse>

Websites mentioned above are works of colleagues/friends of people working at [OC] offclassroom.