#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
#include <clocale>
#include <conio.h>
#include <windows.h>
using namespace std;
const int w = 20;
const int h = 20;
const int size222 = w * h;
int size2[size222]; // 0 - пусто, -1 - стена, -100 - еда, >0 - змейка
int d; // сложность 1-3
int dir = 2; // текущее направление: 1 вверх, 2 вправо, 3 вниз, 4 влево
int nextDir = 2; // направление, выбранное игроком
int headX, headY; // координаты головы
int len = 3; // длина змейки
int score = 0;
bool gameOver = false;
char q3(int q5) { // функция отрисовки клетки
if (q5 > 0) return (q5 == len) ? 'O' : 'o'; // голова / тело
switch (q5) {
case -1: return '#'; // стена
case -100: return '*'; // еда
}
return ' ';
}
void q2() { // вывод поля
COORD pos = {0, 0};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos); // вместо cls, без мерцания
string out;
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
out += q3(size2[j + i * w]);
}
out += '\n';
}
out += "Счёт: " + to_string(score) + " \n";
cout << out;
}
void q4() { // генерация еды
int v, v1;
do {
v = rand() % (w - 2) + 1;
v1 = rand() % (h - 2) + 1;
} while (size2[v + v1 * w] != 0); // еда не появляется на змейке
size2[v + v1 * w] = -100;
}
void q() { // создаёт карту
headX = w / 2;
headY = h / 2;
size2[headX + headY * w] = len;
for (int i = 0; i < w; i++) {
size2[i] = -1;
size2[i + (h - 1) * w] = -1;
}
for (int j = 0; j < h; j++) {
size2[j * w] = -1;
size2[(w - 1) + j * w] = -1;
}
q4();
}
void update() { // один шаг змейки
dir = nextDir;
int nx = headX, ny = headY;
switch (dir) {
case 1: ny--; break;
case 2: nx++; break;
case 3: ny++; break;
case 4: nx--; break;
}
int cell = size2[nx + ny * w];
if (cell == -1 || cell > 0) { // стена или сама змейка
gameOver = true;
return;
}
bool ate = (cell == -100);
if (ate) {
len++;
score++;
} else {
for (int i = 0; i < size222; i++) { // хвост "съедается"
if (size2[i] > 0) size2[i]--;
}
}
headX = nx;
headY = ny;
size2[headX + headY * w] = len;
if (ate) q4();
}
void q10() { // главный цикл: управление и движение
int delay = (d == 1) ? 300 : (d == 2) ? 200 : 100;
system("cls");
while (!gameOver) {
while (_kbhit()) {
char key = _getch();
switch (key) {
case 'w': case 'W':
if (dir != 3) nextDir = 1;
break;
case 'd': case 'D':
if (dir != 4) nextDir = 2;
break;
case 's': case 'S':
if (dir != 1) nextDir = 3;
break;
case 'a': case 'A':
if (dir != 2) nextDir = 4;
break;
}
}
update();
q2();
Sleep(delay);
}
cout << "Game Over!" << endl;
cin.ignore();
cin.get();
}
int main() {
setlocale(0, "");
srand(time(NULL));
cout << "Введите уровень сложности:" << endl;
cout << "1-Легкий" << endl;
cout << "2-Средний" << endl;
cout << "3-Сложный" << endl;
while (!(cin >> d) || d < 1 || d > 3) {
cin.clear();
cin.ignore(1000, '\n');
cout << "Введите число от 1 до 3: ";
}
q(); // создание карты
q10(); // игра
return 0;
}