0% found this document useful (0 votes)
24 views15 pages

Console Snake Game in C++ OOP

This document details the development of a console-based Snake Game using C++ and Object-Oriented Programming (OOP) principles. It outlines the project's objectives, required components, and the application of OOP concepts such as encapsulation and inheritance. The project successfully demonstrates real-time game logic and includes features like high score tracking, making it a solid foundation for future enhancements.

Uploaded by

Abhushan Paudel
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views15 pages

Console Snake Game in C++ OOP

This document details the development of a console-based Snake Game using C++ and Object-Oriented Programming (OOP) principles. It outlines the project's objectives, required components, and the application of OOP concepts such as encapsulation and inheritance. The project successfully demonstrates real-time game logic and includes features like high score tracking, making it a solid foundation for future enhancements.

Uploaded by

Abhushan Paudel
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Acknowledgement:

We would like to express our sincere gratitude to our


instructors and mentors from the Department of
Electronics and Computer Engineering for their constant
guidance and support throughout the development of this
project. Special thanks to our classmates and seniors for
their help in debugging and solving the issues on the code.
We also acknowledge the online resources and open-
source community, without whom this project would not
have been possible.
Content Page:
1. Introduction……………………………………….1

2. Objective………………………………………….2

3. Components Required…………………………….3

4. OOP Concept’s Applied………………..…………4

5. Executable Code…………………………………5-10

6. Output…………………………………………….11

7. Discussion and Conclusion………………………...12


Introduction:
Games are an excellent way to apply programming
knowledge, especially when dealing with real-time logic,
interaction, and rendering. Among classic arcade games,
Snake remains one of the simplest yet most engaging. In
this project, we have implemented a console-based Snake
Game using C++ and the principles of Object-Oriented
Programming (OOP).
The game is played on a 2D grid. A snake moves in one of
four directions, controlled by the player. The goal is to "eat"
food randomly appearing on the screen, causing the snake
to grow longer. If the snake collides with itself or the walls,
the game ends. This project emphasizes clean code
structure, modularity, and reusability using C++ classes and
OOP design.
Objective:
The objective of this project is to develop a console-based Snake
Game using C++ by applying Object-Oriented Programming
(OOP) principles. The aim is to create a fully interactive and
modular game system that:

• Demonstrates real-time game logic using classes.

• Implements object behavior such as movement, collision, and


score tracking.

• Uses OOP features such as inheritance, encapsulation, and


modular design.

• Stores and retrieves high scores using file handling.

This project not only focuses on building a playable game but also
showcases how object-oriented programming makes large and
complex programs easier to manage and extend.
Components Required:
Software Tools:
• Language: C++
• Compiler: Dev C++
• Platform: Windows Console
Libraries Used:
• <iostream>: For standard input/output operations.
• <conio.h>: For non-blocking keyboard input (_kbhit(),
_getch()).
• <windows.h>: For console cursor control and sleep/delay
functions.
• <ctime>: For random number generation.
• <fstream>: For reading/writing high score to a file.
OOP Concept’s Applied
• Class and Object:
The game entities (Snake, Fruit) are modeled as objects with
properties and methods.

• Inheritance:
Both Snake and Fruit inherit from the Position base class to
reuse coordinate handling.

• Encapsulation:
Each class controls its own data and behavior, making the
code organized and manageable.

• Abstraction:
Complex tasks like movement, input handling, and collision
detection are hidden inside cleanly named methods.

• Modularity:
Game functions (drawGame(), updateGame(), etc.) are
separated for clarity and easy debugging or future upgrades.
Executable Code
#include <iostream> // For input and output (cout)
#include <conio.h>// For _kbhit() and _getch() -
keyboard input
#include <windows.h>// For Sleep() and cursor control
#include <ctime>// For random number seeding
#include <fstream>// For reading/writing high score

using namespace std;

// Constants for game area


const int W = 40;
const int H = 20;

enum Direction { STOP = 0, LEFT, RIGHT, UP, DOWN };

// Base class for all objects with (x, y) coordinates


class Position {
public:
int x, y;
Position(int x = 0, int y = 0) : x(x), y(y) {}
};

// Snake class
class Snake : public Position {
public:
int tailX[100], tailY[100], length;
Direction dir;

Snake(int x = W / 2, int y = H / 2) : Position(x,


y), length(0), dir(STOP) {}

void move() {
for (int i = length; i > 0; i--) {
tailX[i] = tailX[i - 1];
tailY[i] = tailY[i - 1];
}
tailX[0] = x;
tailY[0] = y;

switch (dir) {
case LEFT: x--; break;
case RIGHT: x++; break;
case UP: y--; break;
case DOWN: y++; break;
}
}

bool isSelfCollide() {
for (int i = 0; i < length; i++)
if (tailX[i] == x && tailY[i] == y)
return true;
return false;
}

void setDirection(Direction d) {
dir = d;
}
};

// Fruit class
class Fruit : public Position {
public:
Fruit() { generate(); }

void generate() {
x = rand() % W;
y = rand() % H;
}
};
// Moves the console cursor to top-left to avoid
flickering
void clearScreen() {
COORD pos = {0, 0};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_H
ANDLE), pos);
}

// Draws game frame and all objects


void drawGame(Snake& snake, Fruit& fruit, int score,
int highScore) {
clearScreen();

// Top border
for (int i = 0; i < W + 2; i++) cout << "#";
cout << "\n";

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


for (int j = 0; j < W; j++) {
if (j == 0) cout << "#";

if (i == snake.y && j == snake.x)


cout << "\033[1;32mO\033[0m"; // Snake
head in green
else if (i == fruit.y && j == fruit.x)
cout << "\033[1;31mF\033[0m"; // Fruit
in red
else {
bool tailPrinted = false;
for (int k = 0; k < [Link]; k++)
{
if ([Link][k] == j &&
[Link][k] == i) {
cout << "\033[1;32mo\033[0m";
// Tail in green
tailPrinted = true;
break;
}
}
if (!tailPrinted) cout << " ";
}

if (j == W - 1) cout << "#";


}
cout << "\n";
}

// Bottom border
for (int i = 0; i < W + 2; i++) cout << "#";
cout << "\n";

cout << "Score: " << score << " High Score: " <<
highScore << "\n";
cout << "Controls: W = up, A = left, S = down, D =
right, X = exit\n";
}

// Reads user input and updates snake direction


void getInput(Snake& snake) {
if (_kbhit()) {
switch (_getch()) {
case 'a': [Link](LEFT); break;
case 'd': [Link](RIGHT);
break;
case 'w': [Link](UP); break;
case 's': [Link](DOWN); break;
case 'x': exit(0);
}
}
}

// Updates game logic (movement, collision, score)


void updateGame(Snake& snake, Fruit& fruit, int&
score, bool& gameOver) {
[Link]();

// Screen wrapping
if (snake.x >= W) snake.x = 0; else if (snake.x <
0) snake.x = W - 1;
if (snake.y >= H) snake.y = 0; else if (snake.y <
0) snake.y = H - 1;

// Fruit collision
if (snake.x == fruit.x && snake.y == fruit.y) {
score += 10;
[Link]();
[Link]++;
}

// Self-collision
if ([Link]()) {
gameOver = true;
}
}

// File functions for reading/writing high score


int readHighScore() {
ifstream file("[Link]");
int highScore = 0;
if (file) file >> highScore;
return highScore;
}

void writeHighScore(int score) {


ofstream file("[Link]");
file << score;
}

// Main game function


int main() {
srand(time(0));
Snake snake;
Fruit fruit;
int score = 0;
bool gameOver = false;
int highScore = readHighScore();

while (!gameOver) {
drawGame(snake, fruit, score, highScore);
getInput(snake);
updateGame(snake, fruit, score, gameOver);
Sleep(100);
}

cout << "\n\033[1;31mGame Over!\033[0m\n";

if (score > highScore) {


cout << "New High Score: " << score << "
??\n";
writeHighScore(score);
} else {
cout << "Your Score: " << score << "\n";
}

return 0;
}
Output
Discussion and Conclusion:
This project provided hands-on experience in applying object-
oriented programming in C++. By using classes and inheritance,
the game structure became more modular and easier to manage.
Tail movement, collision detection, and score tracking were
effectively handled within their respective classes.

The addition of file handling for high score tracking added a


realistic feature, making the game more complete. Real-time input
and screen updates were smoothly handled using console
functions.

In conclusion, the project was successful in achieving its goal:


creating a playable snake game while reinforcing key OOP
concepts. The code is easy to extend and serves as a solid
foundation for future improvements like adding obstacles, levels,
or GUI support.

You might also like