贪吃蛇(转载)
2025-12-20 13:18:39
发布于:浙江
#include <iostream>
#include <windows.h>
#include <conio.h>
#include <cstdlib>
#include <ctime>
using namespace std;
// 游戏区域大小
const int WIDTH = 20;
const int HEIGHT = 20;
// 蛇的方向
enum Direction {
STOP = 0, LEFT, RIGHT, UP, DOWN
};
// 游戏变量
int x, y; // 蛇头位置
int fruitX, fruitY; // 食物位置
int score;
int tailX[100], tailY[100]; // 蛇身
int nTail; // 蛇身长度
Direction dir;
bool gameOver;
HANDLE hConsole; // 控制台句柄
// 初始化游戏
void Setup() {
gameOver = false;
dir = STOP;
x = WIDTH / 2;
y = HEIGHT / 2;
fruitX = rand() % WIDTH;
fruitY = rand() % HEIGHT;
score = 0;
nTail = 0;
// 获取控制台句柄并隐藏光标
hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO cursor_info = {1, 0}; // 第二个参数为0表示隐藏光标
SetConsoleCursorInfo(hConsole, &cursor_info);
}
// 绘制游戏界面
void Draw() {
COORD coord = {0, 0};
SetConsoleCursorPosition(hConsole, coord); // 将光标移动到左上角
// 上边框
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) {
SetConsoleTextAttribute(hConsole, 0x02); // 绿色蛇头
cout << "O"; // 蛇头
SetConsoleTextAttribute(hConsole, 0x07); // 恢复默认颜色
}
else if (i == fruitY && j == fruitX) {
SetConsoleTextAttribute(hConsole, 0x06); // 黄色食物
cout << "F"; // 食物
SetConsoleTextAttribute(hConsole, 0x07); // 恢复默认颜色
}
else {
bool print = false;
for (int k = 0; k < nTail; k++) {
if (tailX[k] == j && tailY[k] == i) {
SetConsoleTextAttribute(hConsole, 0x02); // 绿色蛇身
cout << "o"; // 蛇身
SetConsoleTextAttribute(hConsole, 0x07); // 恢复默认颜色
print = true;
}
}
if (!print)
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 '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':
gameOver = true;
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)
gameOver = true;
// 撞自己检测
for (int i = 0; i < nTail; i++) {
if (tailX[i] == x && tailY[i] == y)
gameOver = true;
}
// 吃食物
if (x == fruitX && y == fruitY) {
score += 10;
fruitX = rand() % WIDTH;
fruitY = rand() % HEIGHT;
nTail++;
}
}
int main() {
srand(time(NULL)); // 初始化随机数种子
Setup();
while (!gameOver) {
Draw();
Input();
Logic();
Sleep(200); // 控制游戏速度,增加延迟使游戏变慢
}
return 0;
}
这里空空如也









有帮助,赞一个