# Snake Game in C

Snake Game was quite a popular game in the late 90s. It was developed and published by Gremlin in the year 1976. Since then, different versions of the snake game have become popular on different platforms due to their easy, engaging, and interactive user experience and implementation. One such platform which made snake game a household name was Nokia which featured snake game on almost every device with names such as snake, snake II, snake xenzia, snake III, etc. Snake Game in C is a simple console program with no graphics.

Problem Description

Write a C program to create a snake game.

Problem Solution

Game Play:
In this game the player is given with a rectangular boundary along with snake and a fruit (primarily, a dot/square), the snake is allowed to move right-left-top and bottom and as it eats the fruit its size grows and points increases and as the snake collide with the boundary the game gets over.

Proposed Functionality:

1. The snake is represented by 0.
2. The fruit is represented by *.
3. Move the snake in direction with the keys F, D, J, K keys.
4. With every fruit the snake eats the score increases by 5 points.
5. Fruits will be generated automatically within the boundary.
6. The game terminates as the snake collides with the boundary.

Coding Approach:

• Create a function named Draw() under this function the boundary of game will be specified.
• Create a function named Fruits() which will generate the fruits randomly within the boundary.
• Create a function named Input() under this function the user input from the keyboard is taken.
• Create a function named Logic() which contains the logic set of movement of snake in the game.
Psuedo Code:

1. Draw() Function
This function creates the square box with border ‘#’ to identify the game area.
Code:

```#include <stdio.h>
#include <stdlib.h>

int i,j;
int height = 40;
int width = 40;

void draw()
{
for (i = 0; i < height; i++)
{
for (j = 0; j < width; j++)
{
if (i == 0 || i == width - 1 || j == 0 || j == height - 1)
{
printf("#");
}
else
{
printf(" ");
}
}
printf("\n");
}
}

int main()
{
draw();
return 0;
}```

2. Fruits() Function
This function is used to set the position of fruit within the game boundary.
Code:

```void fruits()
{
gameover = 0;

x = height / 2;
y = width / 2;
fruitsx:
fruitx = rand() % 40;
if (fruitx == 0)
goto fruitsx;
fruitsy:
fruity = rand() % 40;
if (fruity == 0)
goto fruitsy;
score = 0;
}```

3. Input() Function
This function takes the input from the keyboard and further stores the value in the flag as shown below.
Code:

```void input()
{
if (kbhit())
{
switch (getch())
{
case 'f':
flag = 1;
break;
case 'd':
flag = 2;
break;
case 'j':
flag = 3;
break;
case 'k':
flag = 4;
break;
case 'x':
gameover = 1;
break;
}
}
}```

4. Logic() Function:
This is the heart of program which control the movement of snake, updation of score and termination of program.
Code:

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
```void logic()
{
sleep(1);
switch (flag)
{
case 1:
x++;
break;
case 2:
y--;
break;
case 3:
y++;
break;
case 4:
x--;
break;
default:
break;
}
if (x < 0 || x > height || y < 0 || y > width)
gameover = 1;

if (x == fruitx && y == fruity)
{
logicx:
fruitx = rand() % 40;
if (fruitx == 0)
goto logicx;

logicy:
fruity = rand() % 40;
if (fruity == 0)
goto logicy;
score += 5;
}
}```
Program/Source Code

Here is source code of the C program to create a snake game. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

```/*
* Snake Game Program in C
*/

#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int i, j, height = 20, width = 20;
int gameover, score;
int x, y, fruitx, fruity, flag;

// fruit generation within the boundary
void fruits()
{
gameover = 0;

// store height and width
x = height / 2;
y = width / 2;
fruitsx:
fruitx = rand() % 20;
if (fruitx == 0)
goto fruitsx;
fruitsy:
fruity = rand() % 20;
if (fruity == 0)
goto fruitsy;
score = 0;
}

void draw()
{
system("cls");
for (i = 0; i < height; i++)
{
for (j = 0; j < width; j++)
{
if (i == 0 || i == width - 1 || j == 0 || j == height - 1)
{
printf("#");
}
else
{
if (i == x && j == y)
printf("0");
else if (i == fruitx
&& j == fruity)
printf("*");
else
printf(" ");
}
}
printf("\n");
}
printf("score = %d", score);
printf("\n");
printf("press X to quit the game");
}

void input()
{
if (kbhit())
{
switch (getch())
{
case 'f':
flag = 1;
break;
case 'd':
flag = 2;
break;
case 'j':
flag = 3;
break;
case 'k':
flag = 4;
break;
case 'x':
gameover = 1;
break;
}
}
}

void logic()
{
sleep(1);
switch (flag)
{
case 1:
x++;
break;
case 2:
y--;
break;
case 3:
x--;
break;
case 4:
y++;
break;
default:
break;
}

// game over
if (x < 0 || x > height || y < 0 || y > width)
gameover = 1;

// snake reaches the fruit and the score gets updated
if (x == fruitx && y == fruity)
{
logicx:
fruitx = rand() % 20;
if (fruitx == 0)
goto logicx;

// generation of new fruit after eating the current one
logicy:
fruity = rand() % 20;
if (fruity == 0)
goto logicy;
score += 5;
}
}

void main()
{
// boundary generation
fruits();

// till the game is over
while (!gameover)
{
draw();
input();
logic();
}
}```
Program Explanation

1. sleep() function delays the program execution by given number of seconds thus making is easier for user to play the game.
2. rand() is used to generate random integer values and rand()%20 will generate the fruits within the boundary of snake game.
3. unitstd.h header file contains the function sleep().
4. khbit() function in C is used to determine whether a key is pressed on keyboard or not.
5. It is present in header file conio.h and return non zero value if key is pressed and zero if key is not pressed.

Program Output:
```####################
#  0               #
#                  #
#                  #
#                  #
#                  #
#                  #
#                  #
#                  #
#                  #
#                  #
#                  #
#                  #
#                  #
#                  #
#                  #
#        *         #
#                  #
#                  #
#                  #
#                  #
####################
Score = 10
Press X to quit the game.```

Conclusion:
Snake game in general is quite easy to implement user is requested to play along with the code for better understanding of logic and the game.

To practice programs on every topic in C, please visit “Programming Examples in C”, “Data Structures in C” and “Algorithms in C”.

If you find any mistake above, kindly email to [email protected]

Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!