DEV Community

Divyanshu Shekhar
Divyanshu Shekhar

Posted on

Create Snake Game in C++: A Step-by-Step Guide

In this blog, we will learn how to create a Snake game using C++. The Snake game is a classic and popular game in which the player controls a snake that moves around the screen, trying to eat food and avoid colliding with walls or its own tail. We will go through the process step by step and explain the necessary functions and parameters used in the code.


Before we start coding, make sure you have a basic understanding of C++ programming language and the concepts of variables, loops, and functions.

Also, make sure you have a C++ compiler installed on your system. You can choose any popular compiler such as GCC or Microsoft Visual C++. Set up your development environment by installing the compiler and a suitable integrated development environment (IDE) such as Code::Blocks or Visual Studio.

Setting Up the Snake Game

Let’s start by setting up the basic structure of our Snake game. We will define the necessary variables and initialize the game’s initial state.

#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <Windows.h>

bool gameOver;

const int width = 20;
const int height = 20;

int x, y, fruitX, fruitY, score;

int tailX[100], tailY[100];
int nTail;

std::string fruit = "*";

enum eDirections
    STOP = 0,

eDirections dir;

void Setup()
    gameOver = false;
    dir = STOP;
    x = width / 2;
    y = height / 2;
    fruitX = rand() % width + 1;
    fruitY = rand() % height + 1;
    score = 0;
Enter fullscreen mode Exit fullscreen mode

In the code above, we have declared the necessary variables for the game. Here’s a brief explanation of each variable:

  • gameOver: Keeps track of whether the game is over or not. width and height: Define the dimensions of the game screen. x and y: Represent the current position of the snake.
  • fruitX and fruitY: Represent the position of the fruit that the snake needs to eat. score: Stores the player’s score.
  • tailX and tailY: Arrays to store the positions of the snake’s tail.
  • nTail: Keeps track of the length of the snake’s tail. fruit: Represents the character used to display the fruit on the screen.
  • eDirections: An enumeration to represent the possible directions the snake can move.
  • The Setup() function initializes these variables with their initial values, positioning the snake at the center of the screen and randomly placing the fruit.

Read more from the original post Snake Game. Find the blog on Google Snake Game.

Top comments (0)