Files
Snake-Game/snake.cpp
T

445 lines
12 KiB
C++

#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <chrono>
#include <thread>
#include <iomanip>
#include <conio.h>
#include <windows.h>
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
}