#include <iostream>
#include <windows.h>
#include <cstdlib>
#include <ctime>
#include <conio.h>
using namespace std;
const int WIDTH = 80;
const int HEIGHT = 20;
struct Snake {
int x;
int y;
Snake* next;
};
Snake* snake;
int foodX, foodY;
int score = 0;
int dir = 77;
void initGame() {
snake = new Snake;
snake->x = WIDTH / 2;
snake->y = HEIGHT / 2;
snake->next = NULL;
srand(static_cast<unsigned int>(time(NULL)));
foodX = rand() % (WIDTH - 2) + 1;
foodY = rand() % (HEIGHT - 2) + 1;
}
void drawScene() {
system("cls");
for (int i = 0; i < HEIGHT; ++i) {
for (int j = 0; j < WIDTH; ++j) {
if (i == 0 || i == HEIGHT - 1 || j == 0 || j == WIDTH - 1) {
cout << "#";
}
else {
bool isSnake = false;
Snake* current = snake;
while (current!= NULL) {
if (current->x == j && current->y == i) {
cout << "O";
isSnake = true;
break;
}
current = current->next;
}
if (!isSnake) {
if (j == foodX && i == foodY) {
cout << "*";
}
else {
cout << " ";
}
}
}
}
cout << endl;
}
cout << "Score: " << score << endl;
}
void moveSnake() {
Snake* newHead = new Snake;
switch (dir) {
case 72:
newHead->x = snake->x;
newHead->y = snake->y - 1;
break;
case 80:
newHead->x = snake->x;
newHead->y = snake->y + 1;
break;
case 75:
newHead->x = snake->x - 1;
newHead->y = snake->y;
break;
case 77:
newHead->x = snake->x + 1;
newHead->y = snake->y;
break;
}
newHead->next = snake;
snake = newHead;
if (snake->x == foodX && snake->y == foodY) {
score++;
srand(static_cast<unsigned int>(time(NULL)));
foodX = rand() % (WIDTH - 2) + 1;
foodY = rand() % (HEIGHT - 2) + 1;
}
else {
Snake* current = snake;
Snake* prev = NULL;
while (current->next!= NULL) {
prev = current;
current = current->next;
}
delete current;
prev->next = NULL;
}
}
bool isGameOver() {
if (snake->x == 0 || snake->x == WIDTH - 1 || snake->y == 0 || snake->y == HEIGHT - 1) {
return true;
}
Snake* current = snake->next;
while (current!= NULL) {
if (current->x == snake->x && current->y == snake->y) {
return true;
}
current = current->next;
}
return false;
}
int main() {
initGame();
while (true) {
if (_kbhit()) {
char key = _getch();
if ((key == 'w' || key == 72) && dir!= 80) dir = 72;
if ((key == 's' || key == 80) && dir!= 72) dir = 80;
if ((key == 'a' || key == 75) && dir!= 77) dir = 75;
if ((key == 'b' || key == 77) && dir!= 75) dir = 77;
}
drawScene();
moveSnake();
if (isGameOver()) {
system("cls");
cout << "Game Over! Your score: " << score << endl;
break;
}
Sleep(100);
}
return 0;
}