×

Snake Game in C

Snake game in C is basic desktop console program which was created in 1970’s. It is an old classic game which was played by every child across the world. This snake game has no graphics in it and it is considered as mini project for the students who are beginners and wants to learn and understand the C language efficiently.

The basic idea to implement and play this game is using W, A, S and D keys drive the snake within the console window and there is fruit which we need to make the snake. The fruit is placed randomly in the console window. The game is played only within the console window.

The game instructions are as follows:

  • The snake in the game is represented with the symbol 0.
  • The snake can be driven in the console window in any directions by using the keys W, A, S and D. only within the console window.
  • The fruit for the snake is represented by *(asterisk) symbol.
  • Whenever the snake eats the fruit, the scoreboard increases by 10 points every time.
  • The fruit for the snake is placed randomly within the boundaries of the wall.
  • The game comes to an end whenever the snake touches the wall of any side.

Some technical aspects for the snake program are:

  • User defined functions and Built-in functions.
  • Building a boundary for the game.
  • Generating randomly placed fruit for the snake.
  • Increasing score board after eating fruit.

User defined functions

We require mainly 4 different types of user defined functions and they are as follows:

  • Setup ()
  • Draw ()
  • Input ()
  • Logic ()

Setup ()

This function is used to arrange the fruit for the snake in the random position within the boundary console window.

Draw ()

This function is implemented and deployed for creating the boundary for the required snake game in which the game is played.

Input ()

This function plays the main role in the snake program because this function helps in taking the input values from the user through keyboard.

Logic()

This function is used to allocate and set the movement positions of the snake in the console window.

Built-in functions

We require two built in C functions and they are as follows:

  • Kbhit ()
  • rand ()

Kbhit ()

This function in C programming language is used to crosscheck and determine if a key is pressed or not. To implement this function, we need to include the header file conio.h because whenever a key is pressed, it returns a non-zero value or else zero.

Rand ()

This is declared in the header file stdlib.h because whenever the rand () function is declared it returns a random integer value.

We require 3 header files and some variables to declare in the pre processor section and declaration section.

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

And the variable declaration follows as:

inti, j ;
int height = 20, width = 20, gameover, score;
int x, y;
int fruitx, fruiyty, flag ;

Let’s deploy the code for the building of the boundaries of the console window:

Code:

// C program to deploy and construct the console boundary window for the snake game.
#include <stdio.h>
#include <stdlib.h>
inti, j, height = 10;
intwidth = 10, gameover, score;
  
// Function to construct the boundary walls for the game
voiddraw ()
{
    // 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{
                printf (" ");
            }
        }
        printf("\n");
    }
}
  
// Driver Code
intmain ()
{
    // Function Call
    draw ();
 
  return0;
}

Output:

# # # # # # # # # # 
##
#                #
#                #
#		 #
#		 #
#		 #
#		 #
#		 #
# # # # # # # # # #

By using all the functions and declaring all the required aspects the whole code for deploying the snake game is:

// C program to deploy the complete snake game
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
  
inti, j, height = 10, width = 10;
intgameover, score;
intx, y, fruitx, fruity, flag;
  
// Function to generate the fruit inside the boundary walls
voidsetup ()
{
    gameover = 0;
  
    // Storing height and width of the window
    x = height / 2;
    y = width / 2;
label1:
    fruitx = rand () % 20;
    if(fruitx == 0)
        gotolabel1;
label2:
    fruity = rand () % 20;
    if(fruity == 0)
        gotolabel2;
    score = 0;
}
  
// Function to draw the boundaries of the snake game
voiddraw ()
{
    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");
                elseif(i == fruitx
                         && j == fruity)
                    printf("*");
                else
                    printf(" ");
            }
        }
        printf("\n");
    }
  
    //displaying the score after the game ends
    printf ("score = %d", score);
    printf("\n");
    printf("press X to quit the game");
}
  
// taking input
voidinput()
{
    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':
            gameover = 1;
            break;
        }
    }
}
  
//logic behind movement
voidlogic ()
{
    sleep(0.01);
    switch(flag) {
    case1:
        y--;
        break;
    case2:
        x++;
        break;
    case3:
        y++;
        break;
    case4:
        x--;
        break;
    default:
        break;
    }
  
    // game over consideration
    if(x < 0 || x > height
        || y < 0 || y > width)
        gameover = 1;
  
//updation of score if snake reaches fruit
    if(x == fruitx && y == fruity) {
    label3:
        fruitx = rand() % 20;
        if(fruitx == 0)
            gotolabel3;
  
    // after eating the given fruit generate another new fruit
    label4:
        fruity = rand() % 20;
        if(fruity == 0)
            gotolabel4;
        score += 10;
    }
}
  
// Driver Code
voidmain()
{
    intm, n;
  
    // Generate boundary
    setup();
  
    // Until the game is over
    while(!gameover) {
  
        // Function Call
        draw();
        input();
        logic();
    }
}

Output:

# # # # # # # # # # 
#      *           #
#                 #
#                 #
#		  #
#	0	  #
#		  #
#		  #
#		  #
# # # # # # # # # # 
# # # # # # # # # # 
#           0      #
#   *              #
#                 #
#		  #
#		  #
#		  #
#		  #
#		  #
# # # # # # # # # #

Related Topics

Program to Find Mode of an Array in C

Mode is the highest occurring value or number in a given set of data elements. In a group of data values, a value that occurs most frequently is considered to...

3 minutes read.

Formatted Input and output function in C

Formatted I/O functions display multiple outputs to the user by taking various inputs. All data types like int, float, char and double are supported by the formatted I/O function. In...

4 minutes read.

Array to function in C

Array to function in C We can create functions that receive an array as an argument. To pass an array into a function, we need to write the name of the...

4 minutes read.

Escape Sequence in C

An escape sequence is a sequence of character that used inside the string literal or character.  All the escape sequence is used with the backslash (\) symbol. The list of an...

1 minute read.

Pointer to pointer in C

A pointer to another pointer is another type of multiple indirections and a chain of many pointers. Generally, a pointer consists of the address of the variable. Once a pointer to...

4 minutes read.

Beep() function in C

Introduction: Beep is a function which is used in C programming language. The beep function uses to make a beep sound. In the C language, when we want to generate...

3 minutes read.

C Math Library

C Math Library The <math.h> header defines various mathematical functions and one macro. Many functions are available in this library to take double as an argument and then return double as...

4 minutes read.

While-Loop in C

Syntax of While Loop The syntax that has been used for the while loop in C programming language is: while (termination condition) {   // the body of the loop  } Working of While-Loop Initially, we...

3 minutes read.

Cbrt() function in C

Introduction: The Cbrt is a function used in C programming language. The cbrt() function is a math function. Using the cbrt function, we can do the cube root of a function. This...

4 minutes read.

Multiplication table program in C using For loop

Before we move on the program of multiplication table of any natural number, first we have to know about the For loop statement. The syntax of ‘for’ loop in C programming...

3 minutes read.

Decimal to Binary in C

What is a decimal number? A decimal number is a number represented in the decimal number system. This system of binary conversion uses base 10 to represent numbers, i.e. the digits...

3 minutes read.

What is required in each C Program?

Each C program must require one function, i.e., main() function. It is because when we execute the C program, C compiler looks for the main() function, and from here only...

5 minutes read.

Call Back Function in Embedded C

Callback function are one the most remarkable systems in C. A callback function is any code that is passed as a contention to another code, so this is the last...

3 minutes read.

Simple hash() function in C

Introduction In this context, we briefly discuss HASH FUNCTION, HASHING or HASH TABLE in C. It is a function used to map data and mapped arbitrary sizes to the fixed-size values. The...

7 minutes read.

Difference between Pre-increment and Post-increment in C

Increment operators are the kind of operators that are used to increment the cost of the operand by way of 1. In different words, the increment operator is an operator...

4 minutes read.

Write a program that produces different results in C and C++

In this tutorial, we'll explore several programs that, depending on whether they are developed using C or C++ compilers, will produce varying outputs. There are numerous similar programs, but we will just...

2 minutes read.

User Defined Functions in C

C Functions: A function is defined as a block of code that is used to perform some specific task. In functions, we use flower brackets ({}) which contain the set of programming...

5 minutes read.

How to use atoi() function in C

Introduction: The atoi() is a function used in C programming language. This function converts string characters to the integer value. The atoi() function converts the input string to the return type of...

4 minutes read.

Error handling in C

Error handling in C: The C programming standard does not provide direct convenience for handling the errors. However, being a system programming language, it definitely will give access to handling...

4 minutes read.

Segmentation Fault in C

Segmentation Fault in C In the C programming language, segmentation fault or segmentation violation or core dump is a condition that the hardware component raises to protect the memory by indicating...

4 minutes read.