#include <iostream>
#include <conio.h>
#include <windows.h>
#include <vector>
using namespace std;
// 定义游戏区域大小
const int width = 20;
const int height = 20;
// 蛇的结构体
struct Snake {
int x, y;
};
// 食物的结构体
struct Food {
int x, y;
};
// 蛇的方向
enum eDirection { STOP = 0, LEFT, RIGHT, UP, DOWN };
eDirection dir;
// 蛇的身体
vector<Snake> snake;
// 食物
Food food;
// 分数
int score;
// 设置光标位置
void gotoxy(int x, int y) {
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
// 隐藏光标
void hideCursor() {
HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO info;
info.dwSize = 100;
info.bVisible = FALSE;
SetConsoleCursorInfo(consoleHandle, &info);
}
// 初始化游戏
void Setup() {
hideCursor();
dir = STOP;
score = 0;
snake.clear();
snake.push_back({ width / 2, height / 2 });
food.x = rand() % width;
food.y = rand() % height;
}
// 绘制游戏界面
void Draw() {
system("cls");
for (int i = 0; i < width + 2; i++)
cout << "#";
cout << endl;
}
// 处理输入
void Input() {
if (_kbhit()) {
switch (_getch()) {
case 'a':
if (dir != RIGHT)
dir = LEFT;
break;
case 'd':
if (dir != LEFT)
dir = RIGHT;
break;
case 'w':
if (dir != DOWN)
dir = UP;
break;
case 's':
if (dir != UP)
dir = DOWN;
break;
case 'x':
exit(0);
break;
}
}
}
// 游戏逻辑
void Logic() {
for (int i = snake.size() - 1; i > 0; i--) {
snake[i] = snake[i - 1];
}
switch (dir) {
case LEFT:
snake[0].x--;
break;
case RIGHT:
snake[0].x++;
break;
case UP:
snake[0].y--;
break;
case DOWN:
snake[0].y++;
break;
default:
break;
}
}
int main() {
Setup();
while (true) {
Draw();
Input();
Logic();
Sleep(100);
}
return 0;
}