diff --git a/README.md b/README.md new file mode 100644 index 0000000..0b6e52b --- /dev/null +++ b/README.md @@ -0,0 +1,90 @@ +# 🐍 Snake Game (C++ Console Edition) + +A colorful and modern **Snake Game** built entirely in **C++** for the terminal. +This version includes a **menu system, persistent leaderboard, scoring with time tracking, smooth controls, and a retro ASCII-art UI** that makes the classic snake experience both fun and polished. + +--- + +## 🎮 Features + +- 🏠 **Main Menu:** Start a new game, view the leaderboard, or exit. +- 👤 **Player Names:** Each player enters their name before starting, and their performance is tracked. +- đŸŽ¯ **Scoring System:** + - +10 points for each fruit collected + - Timer shows how long you survived + - Score combined with time for leaderboard ranking +- 🏆 **Leaderboard:** Sorted by **score** (higher is better), with **time** used as a tiebreaker. +- 🐍 **Snake Mechanics:** Grow longer each time you eat fruit, but avoid running into your own tail! +- 🔄 **Wrap-Around Walls:** When hitting borders, snake reappears on the opposite side. +- ⏱ **Time Tracking:** Total game duration is displayed alongside your score. +- 🎨 **Colorful Console Graphics:** Snake, fruits, borders, and leaderboard are all highlighted with ANSI colors. +- 💾 **Persistent Save:** Player data is stored in `leaderboard.txt` so you can keep competing across sessions. +- ⚡ **Fast and Simple UI:** Runs directly in terminal — no extra dependencies. + +--- + +## 📷 Screenshots + +### 🏠 Main Menu +![Menu](./image/Menu.png) + +--- + +### 🏆 Leaderboard +![Leaderboard](./image/leaderboard.png) + +--- + +### 🎮 In-Game +![Gameplay](./image/Game.png) + +--- + +## âš™ī¸ Setup & Run + +### ✅ Requirements +- A C++ compiler (e.g., g++, MSVC) +- Windows OS (project uses `conio.h` and `windows.h`) +- Console with UTF-8 and ANSI color support + +### đŸ“Ļ Build & Run + +#### On Windows: +```bash +g++ -o snake snake.cpp -std=c++11 +snake.exe +``` + +#### On Linux/macOS: +> âš ī¸ This version relies on Windows-specific libraries. For Linux/macOS, small adjustments are required (replace `conio.h` and `windows.h` with platform-specific functions). + +--- + +## đŸ•šī¸ Controls + +- `W` or **Up Arrow** → Move Up +- `S` or **Down Arrow** → Move Down +- `A` or **Left Arrow** → Move Left +- `D` or **Right Arrow** → Move Right +- `ESC` → End the game immediately + +--- + +## 📁 Project Files + +- `snake.cpp` → Main source code +- `leaderboard.txt` → Stores player leaderboard data + + +--- + +## 👤 Creator + +> **Name:** _[Meraj Derafshi]_ +> **Contact/Portfolio:** _[https://github.com/MerajDerafshi]_ + +--- + +## 📜 License + +This project is open-source. Feel free to use, modify, or expand it for learning or fun. Attribution is appreciated. diff --git a/image/Game.png b/image/Game.png new file mode 100644 index 0000000..b1c608c Binary files /dev/null and b/image/Game.png differ diff --git a/image/Menu.png b/image/Menu.png new file mode 100644 index 0000000..3f6a059 Binary files /dev/null and b/image/Menu.png differ diff --git a/image/leaderboard.png b/image/leaderboard.png new file mode 100644 index 0000000..9f3e048 Binary files /dev/null and b/image/leaderboard.png differ diff --git a/leaderboard.txt b/leaderboard.txt new file mode 100644 index 0000000..05767dc --- /dev/null +++ b/leaderboard.txt @@ -0,0 +1,4 @@ +Sam 370 139 +Mehrad 370 141 +navid 200 80 +Meraj 120 40 diff --git a/snake.cpp b/snake.cpp new file mode 100644 index 0000000..668291e --- /dev/null +++ b/snake.cpp @@ -0,0 +1,445 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; +using namespace chrono; + +#define PURPLE "\033[35m" +#define AMETHYSTINE "\033[1;35m" +#define TURQUOISE "\033[1;36m" +#define COBALTBLUE "\033[36m" +#define GRAY "\033[1;90m" +#define RED "\033[1;31m" +#define BLUE "\033[1;34m" +#define YELLOW "\033[1;33m" +#define GREEN "\033[1;92m" +#define LIGHT_GREEN "\033[38;5;118m" +#define SILVER "\033[1;97m" +#define BRONZE "\033[0;33m" +#define RESET "\033[0m" + +// --- Game Variables --- +bool gameOver; +const int width = 40; +const int height = 20; // Adjusted height for better screen fit with menu/leaderboard +int x, y, fruitX, fruitY, score; +int tailX[100], tailY[100]; +int ntail; +int timer; // Variable to store elapsed time in seconds +enum eDirection { STOP = 0, LEFT, RIGHT, UP, DOWN }; +eDirection dir; + +// --- Leaderboard Structure & Globals --- +struct Player { + string name; + int score = 0; + int time = 0; +}; + +string playerName; +Player players[100]; +int NumOfPlayers = 0; + +// --- Function Prototypes --- +// Utility +void clearScreen(); +void pauseForMilliseconds(int milliseconds); +void gotoxy(int x, int y); +void showConsoleCursor(bool showFlag); + +// Menu and Game Flow +int showMenu(); +void getPlayerName(); +void mainGame(); + +// Leaderboard +void leaderboard(); +void sortLeaderboard(); +void loadData(); +void saveData(string name, int score, int time); +void saveInfo(); + +// Original Snake Game Functions +void setup(); +void draw(); +void input(); +void logic(); + + +// --- Main Control Flow --- + +int main() { + #ifdef _WIN32 + SetConsoleOutputCP(CP_UTF8); + #endif + + while (true) { + int choice = showMenu(); + + switch (choice) { + case 0: + mainGame(); + break; + + case 1: + leaderboard(); + cout << GRAY << "\nPress Enter to return to the menu..." << RESET; + getch(); + break; + + case 2: + cout << RED << "\nExiting game. Goodbye!\n" << RESET; + pauseForMilliseconds(1500); + return 0; + } + } + return 0; +} + + +// --- Snake Game Logic (Wrapped) --- + +void mainGame() { + getPlayerName(); + setup(); + int tickCounter = 0; + while (!gameOver) { + draw(); + input(); + logic(); + Sleep(100); // Game speed + + tickCounter++; + if (tickCounter == 10) { // 10 * 100ms = 1 second + timer++; + tickCounter = 0; + } + } + // After game over + saveData(playerName, score, timer); + cout << RED << "GAME OVER!" << RESET << endl; + cout << YELLOW << "Press Enter to return to the menu..." << RESET; + getch(); +} + +// --- Menu & Player Input --- + +void getPlayerName() { + clearScreen(); + cout << "\033[1;37;46m" << "\nEnter your name: " << RESET << " "; + cin >> playerName; +} + +int showMenu() { + + showConsoleCursor(false); + clearScreen(); + cout << "\n\n"; + cout << GREEN << R"( _ + ___ _ __ __ _| | _____ +/ __| '_ \ / _` | |/ / _ \ +\__ \ | | | (_| | < __/ +|___/_| |_|\__,_|_|\_\___|)" << RESET << "\n\n"; + + + string menuItems[] = { "New Game", "Leaderboard", "Exit" }; + int selectedOption = 0; + char key; + + while (true) { + for (int i = 0; i < 3; i++) { + int y_pos = 8 + i * 2; + string textColor = (i == selectedOption) ? GREEN : AMETHYSTINE; + + gotoxy(6, y_pos); + if(selectedOption == i) cout << textColor << "> " << menuItems[i] << " <" << RESET; + else cout << textColor << " " << menuItems[i] << " " << RESET; + } + + key = getch(); + switch (toupper(key)) { + case 'W': + case 72: // Up arrow + selectedOption = (selectedOption > 0) ? selectedOption - 1 : 2; + break; + case 'S': + case 80: // Down arrow + selectedOption = (selectedOption < 2) ? selectedOption + 1 : 0; + break; + case 13: // Enter + showConsoleCursor(true); + return selectedOption; + } + } +} + +// --- Leaderboard Functions --- + +void leaderboard() { + clearScreen(); + loadData(); + sortLeaderboard(); + + cout << TURQUOISE << " _ _ _ _ \n"; + cout << "| | ___ __ _ __| | ___ _ __| |__ ___ __ _ _ __ __| |\n"; + cout << "| |/ _ \\/ _` |/ _` |/ _ \\ '__| '_ \\ / _ \\ / _` | '__/ _` |\n" << RESET; + cout << AMETHYSTINE << "| | __/ (_| | (_| | __/ | | |_) | (_) | (_| | | | (_| |\n"; + cout << "|_|\\___|\\__,_|\\__,_|\\___|_| |_.__/ \\___/ \\__,_|_| \\__,_|\n" << "\n" << RESET; + pauseForMilliseconds(1000); + + + cout << SILVER << setw(20) << left << "Name" + << setw(15) << "Score" + << setw(10) << "Time (s)" << RESET << "\n"; + cout << PURPLE << string(45, '_') << RESET << "\n\n"; + + // Print each player's data + for (int i = 0; i < NumOfPlayers; i++) { + string color; + if (i == 0) color = YELLOW; + else if (i == 1) color = GRAY; + else if (i == 2) color = BRONZE; + else color = RESET; + + cout << color << setw(20) << left << players[i].name + << setw(15) << players[i].score + << setw(10) << players[i].time << RESET << "\n"; + } +} + +void loadData() { + ifstream file("leaderboard.txt"); + if (file.is_open()) { + NumOfPlayers = 0; + while (NumOfPlayers < 100 && file >> players[NumOfPlayers].name >> players[NumOfPlayers].score >> players[NumOfPlayers].time) { + NumOfPlayers++; + } + } + file.close(); +} + +void sortLeaderboard() { + // Sorts players with a two-tiered priority: Score, then Time. + for (int i = 0; i < NumOfPlayers - 1; i++) { + for (int j = i + 1; j < NumOfPlayers; j++) { + bool shouldSwap = false; + + // Priority 1: Score (higher is better) + if (players[j].score > players[i].score) { + shouldSwap = true; + } + // Priority 2: Time (lower is better, used for ties in score) + else if (players[j].score == players[i].score) { + if (players[j].time < players[i].time) { + shouldSwap = true; + } + } + + if (shouldSwap) { + Player temp = players[i]; + players[i] = players[j]; + players[j] = temp; + } + } + } +} + +void saveInfo() { + ofstream file("snake_leaderboard.txt", ios::trunc); + if (file.is_open()) { + for (int i = 0; i < NumOfPlayers; i++) { + file << players[i].name << " " << players[i].score << " " << players[i].time << "\n"; + } + } + file.close(); +} + +void saveData(string name, int score, int time) { + loadData(); + + bool playerFound = false; + for (int i = 0; i < NumOfPlayers; i++) { + if (players[i].name == name) { + playerFound = true; + // Update record only if the new score is higher, + // or if scores are equal and the new time is lower. + if (score > players[i].score || (score == players[i].score && time < players[i].time)) { + players[i].score = score; + players[i].time = time; + } + break; + } + } + + if (!playerFound && NumOfPlayers < 100) { + players[NumOfPlayers].name = name; + players[NumOfPlayers].score = score; + players[NumOfPlayers].time = time; + NumOfPlayers++; + } + + saveInfo(); +} + + +// --- Original Snake Functions (Unchanged Core Logic) --- + +void setup() { + gameOver = false; + dir = STOP; + x = width / 2; + y = height / 2; + fruitX = rand() % width; + fruitY = rand() % height; + score = 0; + ntail = 0; // Start with 0 tail length + timer = 0; // Initialize timer +} + +void draw() { + SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), {0,0}); + cout << AMETHYSTINE << "┌"; + for(int i = 1; i < width + 1; i++) cout << "─"; + cout << "┐\n" << RESET; + for(int i = 0; i < height; i++) { + for(int j = 0; j < width; j++ ) { + if(j == 0) cout << AMETHYSTINE << "│" << RESET; + if(i == y && j == x) cout << BLUE << "O" << RESET; // Snake Head + else if(i == fruitY && j == fruitX) cout << RED << "F" << RESET; // Fruit + else { + bool print = false; + for (int k = 0; k < ntail; k++) { + if (tailX[k] == j && tailY[k] == i) { + cout << TURQUOISE << "o" << RESET; // Snake Tail + print = true; + } + } + if(!print) cout << " "; + } + if(j == width - 1) cout << AMETHYSTINE << "│" << RESET; + } + cout << "\n"; + } + cout << AMETHYSTINE << "└"; + for(int i = 1; i < width + 1; i++) cout << "─"; + cout << "┘\n" << RESET; + cout << GREEN << "Score: " << score << RESET << "\n"; + cout << YELLOW << "Time: " << timer << "s" << RESET << "\n"; +} + +void input() { + if(kbhit()) { + char userInput = getch(); + switch(toupper(userInput)) { + case 'A': + case 75: // Left Arrow + if (dir != RIGHT) dir = LEFT; + break; + case 'D': + case 77: // Right Arrow + if (dir != LEFT) dir = RIGHT; + break; + case 'W': + case 72: // Up Arrow + if (dir != DOWN) dir = UP; + break; + case 'S': + case 80: // Down Arrow + if (dir != UP) dir = DOWN; + break; + case 27: // ESC key + gameOver = true; + break; + } + } +} + +void logic() { + int prevX = tailX[0]; + int prevY = tailY[0]; + int prev2X, prev2Y; + tailX[0] = x; + tailY[0] = y; + for(int i = 1; i < ntail; i++) { + prev2X = tailX[i]; + prev2Y = tailY[i]; + tailX[i] = prevX; + tailY[i] = prevY; + prevX = prev2X; + prevY = prev2Y; + } + + switch(dir){ + case LEFT: + x--; + break; + case RIGHT: + x++; + break; + case UP: + y--; + break; + case DOWN: + y++; + break; + default: + break; + } + + // Wall collision (wrap around) + if(x >= width) x = 0; + else if(x < 0) x = width - 1; + if(y >= height) y = 0; + else if(y < 0) y = height - 1; + + // Tail collision + for(int i = 0; i < ntail; i++) + if(tailX[i] == x && tailY[i] == y) + gameOver = true; + + // Fruit collision + if(x == fruitX && y == fruitY) { + score += 10; + fruitX = rand() % width; + fruitY = rand() % height; + ntail++; + } +} + +// --- Utility Functions --- + +void clearScreen() { + #ifdef _WIN32 + system("cls"); + #else + system("clear"); + #endif +} + +void pauseForMilliseconds(int milliseconds) { + this_thread::sleep_for(chrono::milliseconds(milliseconds)); +} + +void gotoxy(int x, int y) { + #ifdef _WIN32 + COORD coord = { (SHORT)x, (SHORT)y }; + SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); + #endif +} + +void showConsoleCursor(bool showFlag) { + #ifdef _WIN32 + HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); + CONSOLE_CURSOR_INFO cursorInfo; + GetConsoleCursorInfo(out, &cursorInfo); + cursorInfo.bVisible = showFlag; + SetConsoleCursorInfo(out, &cursorInfo); + #endif +} \ No newline at end of file