#include <iostream>
#include <cstdlib>
#include <ctime>
#include <unistd.h>
using namespace std;
const int width = 20;
const int height = 20;
const int maxTail = 100;
int x, y;
int fruitX, fruitY;
int score;
int tailX[maxTail], tailY[maxTail];
int nTail;
enum Dir { STOP = 0, LEFT, RIGHT, UP, DOWN };
Dir dir;
// 初始化游戏
void Setup()
{
dir = STOP;
x = width / 2;
y = height / 2;
srand((unsigned)time(NULL));
fruitX = rand() % width;
fruitY = rand() % height;
score = 0;
nTail = 0;
}
// 跨平台清屏
void ClearScreen()
{
#ifdef _WIN32
system("cls");
#else
system("clear");
#endif
}
// 绘制界面
void Draw()
{
ClearScreen();
for (int i = 0; i < width + 2; ++i)
cout << "#";
cout << endl;
for (int i = 0; i < height; ++i)
{
for (int j = 0; j < width; ++j)
{
if (j == 0) cout << "#";
if (i == y && j == x)
cout << "O";
else if (i == fruitY && j == fruitX)
cout << "F";
else
{
bool print = false;
for (int k = 0; k < nTail; ++k)
{
if (tailX[k] == j && tailY[k] == i)
{
cout << "o";
print = true;
}
}
if (!print) cout << " ";
}
if (j == width - 1) cout << "#";
}
cout << endl;
}
for (int i = 0; i < width + 2; ++i)
cout << "#";
cout << "\n分数: " << score << endl;
cout << "WASD移动,请勿反向掉头\n";
}
// 键盘简易控制 + 防反向
void Input()
{
char key;
// Linux/Mac/通用标准判断
#if defined(__APPLE__) || defined(__linux__)
// 极简兼容:提示按方向对应键
#else
// Windows备用
#endif
if (cin.peek() != EOF)
{
cin >> key;
switch(key)
{
case 'a': case 'A':
if(dir != RIGHT) dir = LEFT;
break;
case 'd': case 'D':
if(dir != LEFT) dir = RIGHT;
break;
case 'w': case 'W':
if(dir != DOWN) dir = UP;
break;
case 's': case 'S':
if(dir != UP) dir = DOWN;
break;
case 'x': case 'X':
exit(0);
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;
}
// 撞墙结束
if(x < 0 || x >= width || y < 0 || y >= height)
{
cout << "游戏结束:撞到墙壁!最终分数:" << score << endl;
sleep(3);
exit(0);
}
// 撞到自己
for(int i = 0; i < nTail; ++i)
{
if(tailX[i] == x && tailY[i] == y)
{
cout << "游戏结束:撞到自身!最终分数:" << score << endl;
sleep(3);
exit(0);
}
}
// 吃到食物 + 限制最大长度防数组越界
if(x == fruitX && y == fruitY)
{
score += 10;
fruitX = rand() % width;
fruitY = rand() % height;
if(nTail < maxTail) nTail++;
}
}
int main()
{
Setup();
while(true)
{
Draw();
Input();
Logic();
usleep(120000); // 延时兼容多平台
}
return 0;
}