Skip to content

codehelping.com

  • Home
  • Projects
  • Blog
  • Contact Us
  • About Us

Build Snake Game in C++: 2025 CodeHelping

Posted on December 7, 2024April 6, 2025 By Omkar Pathak No Comments on Build Snake Game in C++: 2025 CodeHelping
C++ Projects, Project

Want to build your own Snake Game in C++? This guide walks you through the process step by step. You’ll learn how to handle movement, detect collisions, and make the game interactive. It’s a fun way to practice loops, arrays, and real-time input handling. The Snake Game in C++ is perfect for beginners looking to sharpen their C++ skills!

Snake Game in C++ Source Code Project

Snake Game in C++ Project Overview:

  • For Up, Down, Left & Right: Press W, S, A, and D on keyword respectively.
Source: Our codehelping youtube channel

Why C++ for the Snake Game Project?

Because C++ offers low-level control over the system while still being relatively easy to use, with libraries like <conio.h> for keyboard input and <windows.h> for handling screen graphics, C++ is perfect for building text-based games.

Key Features: Snake Game in C++

  • Snake Movement: The snake moves continuously, and each segment follows the previous one.
  • Food: The snake grows when it eats food, which spawns randomly.
  • Collision Detection: The game ends if the snake hits its own body.
  • Scoring: The score increases each time the snake eats food.

Structure of theSnake Game

  • Coordinates: A structure to represent positions on the screen.
  • Snake Class: Handles the snake’s body, direction, and movement.
  • GameBoard Class: Manages the game logic, including food spawning, drawing, and score tracking.
  • User Input and Display: For user input, I used the conio.h library’s kbhit() and getch() functions to detect key presses. To display the game on the screen, I used the windows.h library to control the cursor position and clear the screen after every move.

Movement Logic: I had to ensure that the snake’s body segments move correctly after every input and that the snake grows after eating food. This involved shifting the body parts and updating the head’s position based on the current direction.

Game Over Detection: I implemented collision detection to end the game if the snake hits itself.

Complete Source Code: Snake Game in C++ 2025

#include&lt;bits/stdc++.h&gt;
#include&lt;conio.h&gt;  // For key press detection (kbhit)
#include&lt;windows.h&gt;  // For setting console screen buffer

using namespace std;

#define MAX_SNAKE_LENGTH 1000  // Maximum length of the snake

// Direction Constants
const char UP = 'U';  // Upward direction
const char DOWN = 'D';  // Downward direction
const char LEFT = 'L';  // Leftward direction
const char RIGHT = 'R';  // Rightward direction

int screenWidth, screenHeight;

// Function to initialize the screen size
void initializeConsoleScreen()
{
    HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
    GetConsoleScreenBufferInfo(consoleHandle, &amp;consoleInfo);
    screenHeight = consoleInfo.srWindow.Bottom - consoleInfo.srWindow.Top + 1;
    screenWidth = consoleInfo.srWindow.Right - consoleInfo.srWindow.Left + 1;
}

// Structure to represent a point (coordinates) on the screen
struct Coordinates {
    int x;  // X-coordinate (horizontal position)
    int y;  // Y-coordinate (vertical position)

    // Default constructor
    Coordinates() {}

    // Constructor to initialize point with specific x and y values
    Coordinates(int xPos, int yPos) {
        x = xPos;
        y = yPos;
    }
};

// Class representing the Snake object
class Snake {
    int snakeLength;  // Current length of the snake
    char currentDirection;  // Current direction the snake is moving

public:
    Coordinates body[MAX_SNAKE_LENGTH];  // Array of body segments (coordinates of the snake)

    // Constructor to initialize snake starting position
    Snake(int startX, int startY) {
        snakeLength = 1;  // Snake initially has 1 segment
        body[0] = Coordinates(startX, startY);  // Set the initial position of the snake
        currentDirection = RIGHT;  // Initially, the snake moves to the right
    }

    // Function to return the length of the snake
    int getLength() {
        return snakeLength;
    }

    // Function to change the direction of the snake
    void changeDirection(char newDirection) {
        // Check that the snake can't go in the opposite direction
        if (newDirection == UP &amp;&amp; currentDirection != DOWN) {
            currentDirection = newDirection;
        } else if (newDirection == DOWN &amp;&amp; currentDirection != UP) {
            currentDirection = newDirection;
        } else if (newDirection == LEFT &amp;&amp; currentDirection != RIGHT) {
            currentDirection = newDirection;
        } else if (newDirection == RIGHT &amp;&amp; currentDirection != LEFT) {
            currentDirection = newDirection;
        }
    }

    // Function to move the snake and check for collisions or food consumption
    bool moveSnake(Coordinates foodPosition) {

        // Move each body segment to the position of the segment in front of it
        for (int i = snakeLength - 1; i &gt; 0; i--) {
            body[i] = body[i - 1];  // Move the body segment
        }

        // Move the head of the snake based on its current direction
        switch(currentDirection) {
            int temp;
            case UP:
                temp = body[0].y;
                body[0].y = temp - 1;
                break;
            case DOWN:
                temp = body[0].y;
                body[0].y = temp + 1;
                break;
            case RIGHT:
                temp = body[0].x;
                body[0].x = temp + 1;
                break;
            case LEFT:
                temp = body[0].x;
                body[0].x = temp - 1;
                break;
        }

        // Check if the snake bites itself (collides with its body)
        for (int i = 1; i &lt; snakeLength; i++) {
            if (body[0].x == body[i].x &amp;&amp; body[0].y == body[i].y) {
                return false;  // Snake collided with itself, game over
            }
        }

        // Check if the snake eats the food
        if (foodPosition.x == body[0].x &amp;&amp; foodPosition.y == body[0].y) {
            body[snakeLength] = Coordinates(body[snakeLength - 1].x, body[snakeLength - 1].y);  // Add a new body segment at the tail
            snakeLength++;  // Increase the snake's length
        }

        return true;  // Snake is still alive and hasn't collided
    }
};

// Class representing the game board
class GameBoard {
    Snake* gameSnake;  // Pointer to the Snake object
    const char SNAKE_SYMBOL = 'O';  // Symbol used to represent the snake on the screen
    Coordinates foodPosition;  // Position of the food
    const char FOOD_SYMBOL = 'o';  // Symbol used to represent the food

public:
    int currentScore;  // Current score of the player

    // Constructor to initialize the game board
    GameBoard() {
        spawnFood();  // Spawn food at a random location
        gameSnake = new Snake(10, 10);  // Create a new snake at position (10, 10)
        currentScore = 0;  // Initialize score to 0
    }

    // Destructor to clean up the memory
    ~GameBoard() {
        delete gameSnake;  // Delete the snake object
    }

    // Function to return the current score
    int getScore() {
        return currentScore;
    }

    // Function to spawn the food at a random location on the board
    void spawnFood() {
        int x = rand() % screenWidth;  // Random X-coordinate within screen width
        int y = rand() % screenHeight;  // Random Y-coordinate within screen height
        foodPosition = Coordinates(x, y);  // Set the food position
    }

    // Function to display the current score on the screen
    void displayScore() {
        setCursorPosition(screenWidth / 2, 0);  // Set cursor to the top center of the screen
        cout &lt;&lt; "Score: " &lt;&lt; currentScore;  // Display the score
    }

    // Function to set the cursor position on the screen (for drawing the snake and food)
    void setCursorPosition(int x, int y) {
        COORD coord;
        coord.X = x;
        coord.Y = y;
        SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
    }

    // Function to draw the snake and food on the screen
    void draw() {
        system("cls");  // Clear the screen before redrawing

        // Draw each segment of the snake
        for (int i = 0; i &lt; gameSnake-&gt;getLength(); i++) {
            setCursorPosition(gameSnake-&gt;body[i].x, gameSnake-&gt;body[i].y);
            cout &lt;&lt; SNAKE_SYMBOL;  // Print the snake symbol at each body part
        }

        // Draw the food
        setCursorPosition(foodPosition.x, foodPosition.y);
        cout &lt;&lt; FOOD_SYMBOL;  // Print the food symbol

        // Display the score
        displayScore();
    }

    // Function to update the game (move the snake, check for food, etc.)
    bool updateGame() {
        bool isAlive = gameSnake-&gt;moveSnake(foodPosition);  // Move the snake and check for collisions
        if (!isAlive) {
            return false;  // If the snake is dead, game over
        }

        // Check if the snake eats the food
        if (foodPosition.x == gameSnake-&gt;body[0].x &amp;&amp; foodPosition.y == gameSnake-&gt;body[0].y) {
            currentScore++;  // Increase score
            spawnFood();  // Spawn a new food item
        }

        return true;  // Game continues
    }

    // Function to get input from the user (keyboard)
    void processInput() {
        if (kbhit()) {  // Check if a key was pressed
            int key = getch();  // Get the pressed key
            if (key == 'w' || key == 'W') {
                gameSnake-&gt;changeDirection(UP);  // Change direction to UP
            } else if (key == 'a' || key == 'A') {
                gameSnake-&gt;changeDirection(LEFT);  // Change direction to LEFT
            } else if (key == 's' || key == 'S') {
                gameSnake-&gt;changeDirection(DOWN);  // Change direction to DOWN
            } else if (key == 'd' || key == 'D') {
                gameSnake-&gt;changeDirection(RIGHT);  // Change direction to RIGHT
            }
        }
    }
};

// Main function to run the game
int main() {
    srand(time(0));  // Seed the random number generator
    initializeConsoleScreen();  // Initialize the console screen size
    GameBoard* game = new GameBoard();  // Create a new game board

    // Main game loop
    while (game-&gt;updateGame()) {
        game-&gt;processInput();  // Get user input (to change snake direction)
        game-&gt;draw();  // Draw the game state (snake, food, score)
        Sleep(100);  // Sleep for 100 milliseconds to control the game speed
    }

    // If the game ends (snake dies), display final score
    cout &lt;&lt; "Game Over!" &lt;&lt; endl;
    cout &lt;&lt; "Final Score: " &lt;&lt; game-&gt;currentScore &lt;&lt; endl;

    return 0;
}

Conclusion: Snake Game in C++

Building the Snake Game in C++ is a great project that helps to refine C++ skills. It involved using classes for organization, handling user input, and understanding low-level console manipulation. The result is a simple but fun game that works entirely in the terminal.

Thanks a lot for visiting codehelping.com, for more C++ Projects visit: Link

Post navigation

❮ Previous Post: ATM Machine in C++: 2025 Complete Code
Next Post: Master Tic-Tac-Toe Game in C++: 2025 with Source Code ❯

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Home
  • Projects
  • Blog
  • Contact Us
  • About Us

Copyright © 2025 codehelping.com.

Theme: Oceanly by ScriptsTown

Social Chat is free, download and try it now here!