From acb96cb7b07ec0474b55451eb41430d82cd5913d Mon Sep 17 00:00:00 2001 From: MerajDerafshi Date: Tue, 23 Sep 2025 05:27:48 +0330 Subject: [PATCH] #include --- snake.cpp | 377 ++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 335 insertions(+), 42 deletions(-) diff --git a/snake.cpp b/snake.cpp index a9845c7..6703872 100644 --- a/snake.cpp +++ b/snake.cpp @@ -1,13 +1,34 @@ -#include #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 = 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; @@ -15,6 +36,261 @@ 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; @@ -23,39 +299,39 @@ void setup() { 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 << "┌"; + cout << AMETHYSTINE << "┌"; for(int i = 1; i < width + 1; i++) cout << "─"; - cout << "┐\n"; + cout << "┐\n" << RESET; for(int i = 0; i < height; i++) { for(int j = 0; j < width; j++ ) { - if(j == 0) cout << "│"; - if(i == y && j == x) cout << "O"; - else if(i == fruitY && j == fruitX) cout << "F"; + 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 << "@"; + cout << TURQUOISE << "o" << RESET; // Snake Tail print = true; } } if(!print) cout << " "; } - if(j == width - 1) cout << "│"; + if(j == width - 1) cout << AMETHYSTINE << "│" << RESET; } cout << "\n"; } - cout << "└"; + cout << AMETHYSTINE << "└"; for(int i = 1; i < width + 1; i++) cout << "─"; - cout << "┘\n"; - cout << "score:" << score << "\n"; - cout << "Time: " << timer << "s\n"; // Display timer - + cout << "┘\n" << RESET; + cout << GREEN << "Score: " << score << RESET << "\n"; + cout << YELLOW << "Time: " << timer << "s" << RESET << "\n"; } void input() { @@ -63,30 +339,29 @@ void input() { char userInput = getch(); switch(toupper(userInput)) { case 'A': - case 75: - dir = LEFT; + case 75: // Left Arrow + if (dir != RIGHT) dir = LEFT; break; case 'D': - case 77: - dir = RIGHT; + case 77: // Right Arrow + if (dir != LEFT) dir = RIGHT; break; case 'W': - case 72: - dir = UP; + case 72: // Up Arrow + if (dir != DOWN) dir = UP; break; case 'S': - case 80: - dir = DOWN; + case 80: // Down Arrow + if (dir != UP) dir = DOWN; break; - case 27: + case 27: // ESC key + gameOver = true; break; - } } } void logic() { - int prevX = tailX[0]; int prevY = tailY[0]; int prev2X, prev2Y; @@ -114,39 +389,57 @@ void logic() { 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++; } - } -int main() { - system("cls"); - setup(); - int tickCounter = 0; - while(!gameOver){ - draw(); - input(); - logic(); - Sleep(100); +// --- Utility Functions --- - tickCounter++; - if (tickCounter == 10){ - timer++; - tickCounter = 0; - } - } - return 0; +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