写一份贪吃蛇代码(要求使用c ++)
时间: 2024-03-14 16:44:00 浏览: 29
好的,下面是一份简单的贪吃蛇代码,使用C++语言实现,仅供参考:
```c++
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;
bool gameOver; // 游戏结束标志
const int width = 20; // 游戏地图宽度
const int height = 20; // 游戏地图高度
int x, y; // 蛇头的坐标
int fruitX, fruitY; // 食物的坐标
int score; // 得分
int tailX[100], tailY[100]; // 蛇尾的坐标数组
int nTail; // 蛇尾的长度
enum eDirection { STOP = 0, LEFT, RIGHT, UP, DOWN }; // 方向枚举类型
eDirection 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 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 << 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 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;
}
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()
{
Setup();
while (!gameOver)
{
Draw();
Input();
Logic();
Sleep(50); // 控制游戏速度
}
return 0;
}
```
这份代码实现了一个简单的控制台贪吃蛇游戏,具有基本的移动、吃食物、撞墙和撞蛇尾等功能。但是它还有许多不足,比如没有加入难度和等级、没有记录最高分、没有添加音效等等,需要进一步完善。