贪吃蛇c++代码

以下是一个简单的贪吃蛇游戏的C++代码示例。

cpp
#include <iostream> #include <conio.h> #include <windows.h> using namespace std; bool gameOver; const int width = 20; const int height = 10; int x, y; // 蛇头的坐标 int fruitX, fruitY; // 水果的坐标 int score; int tailX[100], tailY[100]; // 蛇的尾巴坐标 int nTail; enum eDirecton { STOP = 0, LEFT, RIGHT, UP, DOWN }; eDirecton dir; void Setup() { gameOver = false; dir = STOP; x = width / 2; y = height / 2; fruitX = rand() % width; fruitY = rand() % height; score = 0; } 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 << "#"; // 左边界 if (i == y && j == x) cout << "O"; // 蛇头 else if (i == fruitY && j == fruitX) cout << "F"; // 水果 else { bool printTail = false; for (int k = 0; k < nTail; k++) { if (tailX[k] == j && tailY[k] == i) { cout << "o"; // 蛇尾 printTail = true; } } if (!printTail) cout << " "; } if (j == width - 1) cout << "#"; // 右边界 } cout << endl; } for (int i = 0; i < width + 2; i++) cout << "#"; cout << endl; cout << "Score:" << score << endl; } void Input() { if (_kbhit()) { switch (_getch()) { case 'a': dir = LEFT; break; case 'd': dir = RIGHT; break; case 'w': dir = UP; break; case 's': dir = DOWN; break; case 'x': gameOver = true; break; } } } void Algorithm() { 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 - 1; else if (x >= width) x = 0; if (y < 0) y = height - 1; else if (y >= height) y = 0; 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() { Setup(); while (!gameOver) { Draw(); Input(); Algorithm(); Sleep(10); // 控制游戏速度 } return 0; }

这个代码实现了一个基本的贪吃蛇游戏,通过控制台进行显示和输入。此代码在Windows环境下使用了 <conio.h>Sleep() 函数,如果在其他平台上运行,可能需要进行一些调整。此外,

增加速度控制:
Setup 函数中添加一个速度变量,以及在 Sleep 函数中使用该变量来控制游戏速度。你可以通过增加或减少速度值来调整游戏的难度。

cpp
int speed = 100; // 设置速度 // 在主循环中修改 Sleep 函数 Sleep(speed);

显示最高分:
在游戏结束后,你可以记录和显示最高分。定义一个变量来存储最高分,并在游戏结束时更新和显示它。

cpp
int highScore = 0; // 在主循环中游戏结束后添加
cpp
// 定义一个二维数组来表示地图 char map[height][width]; // 在 Setup 函数中初始化地图 for (int i = 0; i < height; i++) for (int j = 0; j < width; j++) map[i][j] = ' '; // 在 Draw 函数中显示障碍物 map[obstacleY][obstacleX] = 'X'; // 在主循环中添加 Draw 函数的调用 Draw();