Technology Careers
HDFC Data Digits HDFC ERGO Technocrat Kotak Mahindra Bank-PGP in Full Stack Software Engineering CSB Bank-Digital Transformation Skills Program FreeCharge by Axis Bank - FinTech Engineering Program Post Graduate Program in Full Stack Software Engineering
Banking and Finance Careers
Axis Bank – Priority Banking Program Axis Bank Young Bankers Program HDFC - Relationship Manager Axis Bank - Virtual Sales & Relationship Management Program Excelerate - Wealth Manager Program HDFC - Certification in Virtual Relationship Management HDFC- Trade Finance Operations IndusInd Bank – Banking Sales and Business Development Bajaj Finserv – Beyond Program
Add To Bookmark

Developing a Snake Game in C


By NIIT Editorial

Published on 19/08/2021

8 minutes

 

Introduction to Game Development

Game development is a flexible niche and can be initiated by a big game development studio or even by a single individual. The art of creating games, describing their design, developing it, and releasing a game is known as game development. Concept generation, design building, test and release are also included in game development. Make sure that you take care of the game mechanics, player engagement, rewards and level design while creating any game. Forming a perfect company is not necessarily required if one possesses all the proper skills to create a game, interacting with the user, and manipulating the elements of the games. 

Various stages of game development

Following are the different stages of game development: 

 

  1. Planning
  2. Pre-production
  3. Production
  4. Testing
  5. Pre-launch
  6. Launch
  7. Post-production

Current scenario of the gaming world

While the unprecedented pandemic had led to the upheaval of the entire economy, it boosted the entertainment industry in a way that people resorted to gaming to kill their time. According to a survey in March 2020, the gamers in the US were observed and they spent 45% more of their time playing video games during quarantine than that before. Esports made billions during this situation. Even after the downturn of the pandemic, video games development has soared. It gained a lot of traction. The top-notch live streaming platform of the world Twitch experienced a heavy boom in first-time downloads.

While it hiked to 14% in the US, Italy, on the other hand, observed an astounding 41% increase. They are assisted by various games development software that helps them in providing an exceptional gaming experience. Let’s have a look at some essential software that majorly contribute to video games development.

 

After discussing the current scenarios of the booming gaming industry, let’s get to one of the most popular millennial games – Snake. Let’s learn how can we create this famous game with the help of one of the best programming languages C.  

Make sure that before heading over to the programming segment, you are familiar with some of the following functionalities of the game:

-          Represent the snake with a 0 (zero) symbol.

-          Represent the fruit/prey by using an asterisk (*) symbol.

-          Move the snake in any direction as per the user by using the keys – W, A, S, D.

-          Increase the score by 10 points, when the snake eats a fruit.

-          You will see that the fruit is generated automatically within the boundaries.

-          As soon as the snake touches the boundary, the game gets over.

Let’s get started with the steps to develop the snake game in C:

-          Note that the user-defined functions will be four.

-          You need to build a specific boundary in which the game has to be played.

-          The fruits are randomly generated.

-          As soon as the snake eats the fruit, make sure that you increase the score.

The already created user-defined functions in this program are as follows:

-          Draw: In this function, the boundary will be created to play the game.

-          Setup: The position of the fruit is within the boundary.

-          Input: The input is taken by the function from the keyboard.

-          Logic: Logic sets the movement of the snake.

Here’s the outline boundary of the C program using draw():

// C program to build the outline

// boundary using Boundary()

#include <stdio.h>

#include <stdlib.h>

 

//Game Variables

int i, j, Length = 28;

int width = 28, game_over, Score;

 

// Function to draw a boundary

void Boundary()

{

 

for (i = 0; i < Length; i++) {

     for (j = 0; j < width; j++) {

         if (i==0 || i==width - 1 || j == 0

             || j == Length - 1) {

                printf("*");

         }

         else {

                printf(" ");

         }

     }

        printf("\n");

}

}

 

//  Driver Function

int main()

{

Boundary(); // Function Call

 

return 0;

//  Driver Function

int main()

{

Boundary(); // Function Call

 

return 0;

}

Output

setup(): This function is used to write the code to generate the food within the boundary using rand() function.

Using rand()%20 because the size of the boundary is length = 20 and width = 20 so the food will generate within the boundary.

 

void setup()

{

       game_over=0;

       int x=Length/2;

       int y=width/2;

      

       state1:

                  int foodx=rand()%20;

                  if(foodx==0)

                  goto state1;

       state2:

                  int food_y=rand()%20;

                  if(food_y==0)

                  goto state2;

       Score=0;

}

Input(): In this function, the programmer writes the code to take the input from the keyboard (U, H, J, K, Q keys).

void input()

{

       if(kbhit())

       {

                  switch(getch())

                  {

                            case 'a':

                                      flag=1;

                                      break;

                            case 's':

                                      flag=2;

                                      break;

                            case 'd':

                                      flag=3;

                                      break;

                            case 'w':

                                      flag=4;

                                      break;

                            case 'x':

                                      game_over=1;

                                      break;

                  }

       }

}

 

Algorithm(): Here, write all the logic for this program like for the movement of the snake, for increasing the score, when the snake will touch the boundary the game will be over, to exit the game and the random generation of the food once the snake will eat the food.

 

void Algorithm()

 

{

       sleep(0.01);

       switch(flag)

       {

                  case 1:

                            y--;

                            break;

                  case 2:

                            x++;

                            break;

                  case 3:

                            y++;

                            break;

                  case 4:

                            x--;

                            break;

                  default:

                            break;

       }

      

       if(x<0 || x>Length || y<0 || y>width)

         game_over=1;

       if(x==foodx && y==food_y)

       {

                  state3:

                            foodx=rand()%20;

                            if(foodx==0)

                            goto state3;

                  state4:

                            food_y=rand()%20;

                            if(food_y==0)

                            goto state4;

                             

                  Score+=10;

       }

}

 

sleep(): This function in C is a function that delays the program execution for the given number of seconds. In this code sleep() is used to slow down the movement of the snake so it will be easy for the user to play.

main(): From the main() function the execution of the program starts. It calls all the functions.

 

 

 

void main()

{

       sleep();

       while(!game_over)

       {

                  Boundary();

                  input();

                  Algorithm();

       }

}

 

 

Complete C program to build the snake game is below:

 

// C program to build the complete

// snake game

#include <conio.h>

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

 

int i, j, Length = 28, width = 28;

int game_over, Score;

int X Y, foodx, food_y, flag;

 

// Function to generate the food

// within the boundary

void setup()

{

game_over = 0;

 

// Stores Length and width

X = Length / 2;

Y = width / 2;

state1:

foodx = rand() % 20;

if (foodx == 0)

     goto state1;

state2:

food_y = rand() % 20;

if (food_y == 0)

     goto state2;

    

Score = 0;

}

 

// Function to make the boundaries

void Boundary()

{

    system("cls");

for (k = 0; k < Length; k++) {

     for (j = 0; j < width; j++) {

         if (k == 0 || k == width - 1

             || j == 0

             || j == Length - 1) {

                printf("*");

         }

         else {

             if (k==X && k==Y)

                    printf("0");

                else if (k == foodx

                         && j == food_y)

                    printf("#");

                else

                    printf(" ");

         }

     }

        printf("\n");

}

 

// Print the score after the ending of game.

    printf("Score = %d", Score);

    printf("\n");

    printf("Press Q to end the game");

}

 

// Function to take the input

void input()

{

if (kbhit()) {

    switch (getch()) {

     case 'h':

         flag = 1;

         break;

     case 'j':

         flag = 2;

         break;

     case 'k':

         flag = 3;

         break;

     case 'u':

         flag = 4;

         break;

     case 'q':

            game_over = 1;

         break;

     }

}

}

 

// Function for the logic behind

// each and every movement of the snake

void Algorithm()

{

sleep(0.01);

switch (flag) {

case 1:

     Y--;

     break;

    case 2:

     X++;

     break;

case 3:

     Y++;

     break;

case 4:

     X--;

     break;

default:

     break;

}

 

// If the game is over

if (Y < 0 || Y > width || X < 0 || X> Length)

     game_over = 1;

 

// If snake reaches the food

// then update the score

if ((X == foodx) && (Y == food_y)) {

state3:

     foodx = rand() % 20;

     if (foodx == 0)

         goto state3;

 

// After eating the above food

// generate new food

state4:

     food_y = rand() % 20;

     if (food_y == 0)

         goto state4;

        

     Score += 10;

}

}

 

// Driver Code

void main()

 // Generate boundary

setup();

 

// Until the game is over

while (!game_over) {

 

     // Function Call

     Boundary();

     input();

        Algorithm();

}

}

Output

With this tutorial, you will learn to create a basic Snake game. To understand game development better, and to learn the development of other games you can check out the Game Development Course that is offered by NIIT.



Game Development Course

Becoming a Game Developer: A Course for Programmers. Design and Build Your Own Game using Unity.

Job Placement Assistance

Course duration: 20 weeks

Top