How To Make Snake Game Using C++

by | Jan 4, 2022 | C/C++, Coding

Introduction

In this article, we will learn to create a snake game using C++ programming language. The snake game is top-rated among players and is available on all devices. The game is designed so that the snake can move in every direction, whether left, right, upward, or downward. The snake moves in search of food. The score increases as the snake eat the food. The game is quite simple but exciting while playing. 

  1. It is a single-player game.
  2. The snake is represented with @.
  3. The fruit is represented with X.
  4. The snake can move in any of the four directions as per the player’s control.
  5. As the snake eats the fruit, the score increases.
  6. The game ends as soon as the snake touches the boundary.
  7. When the game ends, ‘Dead’ gets displayed on the screen.

Requirements For Running The Project

To run this project, you must have installed IDE for running and compiling the C++ source code. We recommend Dev C++ or Code Blocks for a better experience.

Refer to the links below to download the Dev C++ or Code Blocks IDE.

https://sourceforge.net/projects/embarcadero-devcpp/

https://sourceforge.net/projects/codeblocks/

Project Implementation

#include <iostream>

#include <windows.h>




using namespace std;




struct SNAKE_POSITION

{

    int X,Y;

};





class family 

{

    static const int H;

    static const int W;

    char ** F;

    family(const family &);

    family operator=(const family &);

public:

    family() {

        F = new char*[family::H];

        for(int c = 0; c < family::H; ++c) {

            F[c] = new char[family::W];

        }

    }

    ~family() {

        for(int c = 0; c < family::H; ++c) {

            delete[] F[c];

        }

        delete[] F;

    }




    void print() {

        for(int c = 0; c < H; ++c) {

            for(int r = 0; r < W; ++r) {

                cout << F[c][r];

            }

            cout << endl;

        }

    }




    void clear() {

        for(int c = 0; c < H; ++c) {

            for(int r = 0; r < W; ++r) {

                F[c][r] = ' ';

            }

        }

    }




    int get_W() const {return W;}

    int get_H() const {return H;}





    void draw(int y, int x, char what) {

        //y = (y < 0) ? 0 : (y >= H ? H - 1 : y);

        //x = (x < 0) ? 0 : (x >= W ? W - 1 : x);




        F[y][x] = what;

    }




} F;





class food_cls {

    SNAKE_POSITION pos;

    char symbol;

public:

    food_cls(): symbol('X'), pos() {

        pos.X = pos.Y = -1;

    }




    void set_pos(int X, int Y) {

        pos.X = X;

        pos.Y = Y;

    }




    void reposition(const family & F) {

        pos.X = rand() % F.get_W();

        pos.Y = rand() % F.get_H();

    }




    int get_X() const {return pos.X;}

    int get_Y() const {return pos.Y;}

    char get_symbol() const {return symbol;}

} food;




class snake_cls {

    enum {UP, DOWN, LEFT, RIGHT} dir;

    char symbol, head_symbol;

    SNAKE_POSITION pos[100];

    SNAKE_POSITION & head;

    int speed;

    int size;

    bool can_turn;

public:

    snake_cls(int X, int Y):

        symbol('#'), head_symbol('@'), pos(),

        speed(1), size(1), dir(RIGHT),

        head(pos[0]), can_turn(true)

    {

        pos[0].X = X;

        pos[0].Y = Y;

    }




    bool check_food(const food_cls & food) {

        if(food.get_X() == head.X && food.get_Y() == head.Y) {

            size += 1;

            return true;

        }

        return false;

    }




    void get_input(const family & F) {

        if(GetAsyncKeyState(VK_UP) && dir != DOWN) {

            dir = UP;

        }

        if(GetAsyncKeyState(VK_DOWN) && dir != UP) {

            dir = DOWN;

        }

        if(GetAsyncKeyState(VK_LEFT) && dir != RIGHT) {

            dir = LEFT;

        }

        if(GetAsyncKeyState(VK_RIGHT) && dir != LEFT) {

            dir = RIGHT;

        }

    }




    void move(const family & F) {

        SNAKE_POSITION next = {0, 0};

        switch(dir) {

        case UP:

            next.Y = -speed;

            break;

        case DOWN:

            next.Y = speed;

            break;

        case LEFT:

            next.X = -speed;

            break;

        case RIGHT:

            next.X = speed;

        }

        for(int c = size - 1; c > 0; --c) {

            pos[c] = pos[c-1];

        }

        head.X += next.X;

        head.Y += next.Y;




        if(head.X < 0 || head.Y < 0 || head.X >= F.get_W() || head.Y >= F.get_H()) {

            throw "DEADD!!!!";

        }

    }




    void draw(family & F) {

        for(int c = 0; c < size; ++c) {

            if(c == 0) {

                F.draw(pos[c].Y, pos[c].X, head_symbol);

            } else {

                F.draw(pos[c].Y, pos[c].X, symbol);

            }

        }

    }




    int get_X() const { return head.X; }

    int get_Y() const { return head.Y; }

    char get_symbol() const { return symbol; }

} snake(1, 1);





const int family::H = 24;

const int family::W = 79;





int main() {

    F.clear();




    food.set_pos(5, 5);




    while(1) {

        F.clear();




        snake.get_input(F);

        try {

            snake.move(F);

        } catch (const char * er) {

            F.clear();

            cerr << er << endl;

            system("pause");

            return -1;

        }

        snake.draw(F);

        F.draw(food.get_Y(), food.get_X(), food.get_symbol());





        if(snake.check_food(food)) {

            food.reposition(F);

        }




        F.print();




        Sleep(1000/30);

        system("cls");

    }
return 0;
}

 

Output

Explanation

In the above-written code, ‘SNAKE POSITION’ is a structure declared with variables, ‘X’ and ‘Y’.

The game starts with the moving @ symbol as the snake and the size of the snake increases when it encounters X as food. 

There are various user-defined functions used in the above tasks for the proper functioning of the code. So, this is how you can code for snake game in the C++ programming language.

 

 

You May Also Like To Create…

0 Comments

Submit a Comment

Your email address will not be published.