C++#include <iostream>
#include <conio.h>
#include <windows.h>
#include <vector>
#include <ctime>
#include <cstdlib>
using namespace std;
// 游戏常量
const int WIDTH = 20;
const int HEIGHT = 20;
const int SPEED = 150; // 毫秒
// 方向枚举
enum Direction { STOP = 0, UP, DOWN, LEFT, RIGHT };
// 游戏类
class Game {
private:
bool gameOver;
int x, y; // 蛇头位置
int foodX, foodY; // 食物位置
int score;
Direction dir;
vector<int> tailX; // 蛇尾X坐标
vector<int> tailY; // 蛇尾Y坐标
int tailLength; // 蛇尾长度
public:
Game() {
gameOver = false;
dir = STOP;
x = WIDTH / 2;
y = HEIGHT / 2;
score = 0;
tailLength = 0;
srand(time(0));
spawnFood();
}
// 生成食物
void spawnFood() {
foodX = rand() % WIDTH;
foodY = rand() % HEIGHT;
}
// 绘制游戏界面
void draw() {
system("cls"); // 清屏
// 绘制上边界
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 << "#";
bool isTail = false;
// 先检查蛇身
for (int k = 0; k < tailLength; k++) {
if (tailX[k] == j && tailY[k] == i) {
cout << "o";
isTail = true;
break;
}
}
// 如果不是蛇身,检查其他元素
if (!isTail) {
if (i == y && j == x)
cout << "O"; // 蛇头
else if (i == foodY && j == foodX)
cout << "F"; // 食物
else
cout << " "; // 空地
}
// 绘制右边界
if (j == WIDTH - 1) cout << "#";
}
cout << endl;
}
// 绘制下边界
for (int i = 0; i < WIDTH + 2; i++)
cout << "#";
cout << endl;
// 显示分数
cout << "分数: " << score << endl;
}
// 处理输入
void input() {
if (_kbhit()) {
switch (_getch()) {
case 'w': dir = UP; break;
case 's': dir = DOWN; break;
case 'a': dir = LEFT; break;
case 'd': dir = RIGHT; break;
case 'x': gameOver = true; break;
}
}
}
// 更新游戏状态
void update() {
// 保存原来的蛇头位置
int prevX = x;
int prevY = y;
// 更新蛇尾位置(从尾部向前移动)
if (tailLength > 0) {
// 移动蛇尾(从后向前更新位置)
for (int i = tailLength - 1; i > 0; i--) {
tailX[i] = tailX[i-1];
tailY[i] = tailY[i-1];
}
// 第一节蛇尾移动到原蛇头位置
tailX[0] = prevX;
tailY[0] = prevY;
}
// 更新蛇头位置
switch (dir) {
case UP: y--; break;
case DOWN: y++; break;
case LEFT: x--; break;
case RIGHT: x++; break;
}
// 检查是否撞墙
if (x < 0 || x >= WIDTH || y < 0 || y >= HEIGHT)
gameOver = true;
// 检查是否吃到食物
if (x == foodX && y == foodY) {
score += 10;
spawnFood();
tailLength++;
// 增加蛇尾空间
tailX.push_back(0);
tailY.push_back(0);
}
// 检查是否撞到自己
for (int i = 0; i < tailLength; i++) {
if (x == tailX[i] && y == tailY[i])
gameOver = true;
}
}
// 运行游戏
void run() {
while (!gameOver) {
draw();
input();
update();
Sleep(SPEED); // 控制游戏速度
}
// 游戏结束显示
system("cls");
cout << "===================" << endl;
cout << " 游戏结束! " << endl;
cout << " 最终分数: " << score << endl;
cout << "===================" << endl;
cout << "按任意键退出..." << endl;
_getch();
}
};
int main() {
Game game;
game.run();
return 0;
}