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/C++ is perfect for beginners looking to sharpen their C++ skills!
Key Features of Snake Game in C++
- Snake Movement: The snake moves continuously following the previous.
- Food: The snake grows when it eats food
- Collision Detection: Game ends if the snake hits its own body.
- Scoring: The score increases each time 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.
Complete Source Code: Snake Game in C++ 2025
#include<bits/stdc++.h>
#include<conio.h> // For key press detection (kbhit)
#include<windows.h> // 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, &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 && currentDirection != DOWN) {
currentDirection = newDirection;
} else if (newDirection == DOWN && currentDirection != UP) {
currentDirection = newDirection;
} else if (newDirection == LEFT && currentDirection != RIGHT) {
currentDirection = newDirection;
} else if (newDirection == RIGHT && 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 > 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 < snakeLength; i++) {
if (body[0].x == body[i].x && 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 && 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 << "Score: " << 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 < gameSnake->getLength(); i++) {
setCursorPosition(gameSnake->body[i].x, gameSnake->body[i].y);
cout << SNAKE_SYMBOL; // Print the snake symbol at each body part
}
// Draw the food
setCursorPosition(foodPosition.x, foodPosition.y);
cout << 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->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->body[0].x && foodPosition.y == gameSnake->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->changeDirection(UP); // Change direction to UP
} else if (key == 'a' || key == 'A') {
gameSnake->changeDirection(LEFT); // Change direction to LEFT
} else if (key == 's' || key == 'S') {
gameSnake->changeDirection(DOWN); // Change direction to DOWN
} else if (key == 'd' || key == 'D') {
gameSnake->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->updateGame()) {
game->processInput(); // Get user input (to change snake direction)
game->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 << "Game Over!" << endl;
cout << "Final Score: " << game->currentScore << 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