×

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

gets() function in C

gets() is a pre-define or built-in function present in the stdio.h header file. stdio stands for standard input and output. gets() function is used to read a stream and store...

4 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.

Passing Array to Function in C

Need to pass Arrays? The need to pass arrays to a function arises when we need to pass a list of values to a given function. During the course of our programming...

4 minutes read.

Random Access - Lseek in C

Introduction lseek is a system call that is used to alter the location of the read/write pointer of a file descriptor. The lseek system call basically moves the current read/write location...

4 minutes read.

Find a subarray with a given sum.

Find a subarray with a given sum. The simple solution is to recognize all subarrays one by one and to check each subarray's sum. The quick solution follows the following program. Algorithm: From...

4 minutes read.

Kruskal algorithm in C

Given a weighted graph, Kruskal's algorithm generates a spanning tree with the lowest possible weights. Start by creating an edge list for the given graph, including the weights. Sort the...

3 minutes read.

Palindrome Number in C

What is a Palindrome? A number that doesn't change when reversed is known as a palindrome. We reverse a number and compare it to the original number to determine whether it is...

4 minutes read.

Multithreading in C interview questions

Q1. What exactly is a thread? Ans: A thread is a brief sequence of instructions intended to be planned and carried out by the CPU apart from the parent process. Q2. Can...

4 minutes read.

Derived Data Types in C

A variable in a program occupies some space in the computer's memory where some value is stored. Each variable in C has an associated data type. A value to be...

4 minutes read.

How to use Typedef Struct in C

The “typedef” is a predefined keyword in C programming language which is used to declare the new name to an existing type of variable. For better understanding, if you declare a...

3 minutes read.

Function in C

Function is a group of statements that are used to perform any task. In other words, we can say that a function is a self- contained a block of programs...

3 minutes read.

Self-referential structure in C

Self-referential structure in C A self-referential structure is a structure that can have members which point to a structure variable of the same type. They can have one or more pointers...

3 minutes read.

Control statement in C

What is a control statement? A control statement helps us to control the flow of the program. The control statement helps us to execute the program's instructions in a user-defined order....

8 minutes read.

How to open a C file on android mobile

A C file is a file that has a .c extension and contains code written in the C language. C is a computer programming language developed by Dennis Ritchie at...

4 minutes read.

Stdio.h in C

Header files are used to make the programmer’s efforts a lot easier. In order to make the programming simple, there are a number of libraries which are included as predefined...

4 minutes read.

Find reverse of an array in C using functions

Introduction: Here, we describe how to find the reverse array in C using functions. Suppose you have an array with n elements. I need to display the elements present in...

3 minutes read.

Dos.h Header File in C Language

Dos.h is a header file in C. Interrupt handling, sound generation, date and time functions, and other tasks can be performed using the functions in this library. This is exclusive to...

4 minutes read.

If else Programs in C Programming

If else Programs in C programming The if-else statement in C is based on some particular conditions to perform the operations. If and only if the given condition is valid, the operations listed in...

4 minutes read.

Pointer arithmetic in C

In the C programming language, a pointer is an address which stores a numeric value. Hence, a developer can perform several arithmetic operations on the same just as one does...

4 minutes read.

First Fit Program in C

This is one of the easiest ways to allocate memory. The main goal is to divide the memory into several fixed sizes. In C, there is only one process for...

3 minutes read.