THE SNAKE GAME BY NABEEL ANWAR (014-BSCS-2010)
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).
Your system should have installed visual studio 2010 or above and windows7 or above to run this game.
Three classes are part of this code :
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++)
SnakeTimer.Enabled = false;
MessageBox.Show("snake is dead.");
if (snake.SnakeRec.X 290)
if (snake.SnakeRec.Y 290)
V) restarting the game if collission happen.
MAJOR FUNCTIONS OF Snake.cs :
i) creation of snake in constructor “Snake()”
CODE OF THE Snake():
snakeRec = new Rectangle;
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)
iii) incrementing and decrementing the X and Y co-ordinates of rectangle, like this :
CODE OF THE METHOD MoveDown() :
public void MoveDown()
snakeRec.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.