#include<bits/stdc++.h>
#include<windows.h>
#include<conio.h>
using namespace std;
const int n = 20;
int die, len = 3, head_x, head_y, d[4][2] = {0, -1, 0, 1, -1, 0, 1, 0}, snake[n * n][2], food[2];
void gotoxy(int x, int y){
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void replace(int x, int y, string s){
gotoxy(x, y);
cout << s;
}
int main(){
srand(time(0));
int dir = 3;
char c;
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++) cout << " ";
cout << "|" << endl;
}
for (int i = 0; i < n * 2; i++) cout << "-";
cout << "+";
for (int i = 0; i < len; i++) snake[i][0] = len - i - 1;
food[0] = rand() % n, food[1] = rand() % n;
for (int i = 0; i < len; i++){
gotoxy(snake[i][0] * 2, snake[i][1]);
cout << "@";
}
while (true){
if (_kbhit()){
c = _getch();
if (c == 'w' && dir != 1) dir = 0;
if (c == 's' && dir != 0) dir = 1;
if (c == 'a' && dir != 3) dir = 2;
if (c == 'd' && dir != 2) dir = 3;
}
replace(food[0] * 2, food[1], "# ");
replace(snake[len - 1][0] * 2, snake[len - 1][1], " ");
head_x = snake[0][0], head_y = snake[0][1];
if (head_x + d[dir][0] == food[0] && head_y + d[dir][1] == food[1]){
len = len + 1;
food[0] = rand() % n, food[1] = rand() % n;
}
for (int i = len - 1; i > 0; i--) snake[i][0] = snake[i - 1][0], snake[i][1] = snake[i - 1][1];
head_x = snake[0][0] = head_x + d[dir][0], head_y = snake[0][1] = head_y + d[dir][1];
if (head_x < 0 || head_x > n - 1 || head_y < 0 || head_y > n - 1) die = 1;
for (int i = 1; i < len && !die; i++) if (head_x == snake[i][0] && head_y == snake[i][1]) die = 1;
if (die) break;
replace(head_x * 2, head_y, "@ ");
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO cci;
GetConsoleCursorInfo(hOut, &cci);
cci.bVisible = 0;
SetConsoleCursorInfo(hOut, &cci);
Sleep(200);
}
gotoxy(0, n);
return 0;
}