THE SNAKE GAME BY NABEEL ANWAR (014-BSCS-2010)

THE SNAKE GAME BY NABEEL ANWAR (014-BSCS-2010)

INTRODUCTION:
This snake game is a simple classic game.It is a windows form application c#(.net framework) and it’s code represents a very good usage of “rectangle” class. The user can use navigation keys to control the snake (up,down,left,right).

FRAMEWORK REQUIRED:
Your system should have installed visual studio 2010 or above and windows7 or above to run this game.
——————————————————————————————————————————————
CODE WORKING:
Three classes are part of this code :
1) frmSnake.cs
2) Snake.cs
3) Snake_Food.cs

MAJOR FUNCTIONS OF frmSnake.cs :
i) initialization of snake by the constructor “frmSnake()”
ii) creation of random food “food = new Snake_Food(randFood);”
iii) handling of snake directions
iv) checking the collisSion of snake with itself and boundries by
using the method named as “Collission()”

CODE OF THE METHOD “Collission():

public void Collission()
{
for (int i = 1; i < snake.SnakeRec.Length; i++)
{
if(snake.SnakeRec[0].IntersectsWith(snake.SnakeRec[1]))
{
SnakeTimer.Enabled = false;
MessageBox.Show("snake is dead.");
}
}

if (snake.SnakeRec[0].X 290)
{
Restart();
}

if (snake.SnakeRec[0].Y 290)
{
Restart();
}
}

V) restarting the game if collission happen.
——————————————————————————————————————————————

MAJOR FUNCTIONS OF Snake.cs :
i) creation of snake in constructor “Snake()”
CODE OF THE Snake():

public Snake()
{
snakeRec = new Rectangle[3];
brush = new SolidBrush(Color.Blue);

x = 20; y = 0; width = 10; height = 10;

for (int i = 0; i < snakeRec.Length; i++)
{
snakeRec[i] = new Rectangle(x, y, width, height);
x -= 10;
}
}
ii) drawing the snake on Graphics paper by the function "public void DrawSnake(Graphics paper)"

CODE OF THE METHOD DrawSnake(Graphics paper):

public void DrawSnake(Graphics paper)
{
foreach (Rectangle rect in snakeRec)
{
paper.FillRectangle(brush, rect);
}
}
iii) incrementing and decrementing the X and Y co-ordinates of rectangle, like this :

CODE OF THE METHOD MoveDown() :

public void MoveDown()
{
DrawSnake();
snakeRec[0].Y += 10;
}
Similar methods are : public void MoveUp(),public void MoveRight(),public void MoveLeft().

iv) growing of snake if it has eaten a food rectangle by the method GrowSnake()
——————————————————————————————————————————————-
MAJOR FUNCTIONS OF Snake_Food.cs :

i) creation of random food rectangle by in overloaded constructor "Snake_Food(Random randFood)"
ii) setting food location using method "foodLocation(Random randFood)"
iii) drawing food on graphics paper by the method "DrawFood(Graphics paper)"
——————————————————————————————————————————————
here are some images where you can see how the game actually looks like while playing……..
I hope you’ll enjoy.
snake is dead
snake is about to eat a food rectanglethe snake collission with itself