写一段可以在DEVC++上跑的贪吃蛇代码
时间: 2023-06-27 15:04:15 浏览: 157
以下是一个简单的贪吃蛇代码,可以在DEVC++上运行。代码注释较详细,希望能帮助到你。
```c++
#include <iostream>
#include <conio.h> //用于获取键盘输入
#include <windows.h> //用于调整控制台窗口大小和光标位置
using namespace std;
//定义游戏界面大小
const int width = 20;
const int height = 20;
//定义蛇和食物的坐标
int snakeX, snakeY, foodX, foodY;
//定义蛇的长度和分数
int snakeLength = 1;
int score = 0;
//定义蛇的移动方向
enum Direction { STOP = 0, LEFT, RIGHT, UP, DOWN };
Direction dir;
//定义蛇的身体坐标数组
int tailX[100], tailY[100];
int nTail = 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 == snakeY && j == snakeX)
cout << "O"; //绘制蛇头
else if (i == foodY && j == foodX)
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;
cout << "Use arrow keys to move the snake. Press X to quit." << endl;
}
//定义初始化游戏的函数
void Setup()
{
//初始化蛇的位置和方向
snakeX = width / 2;
snakeY = height / 2;
dir = STOP;
//随机生成食物的位置
foodX = rand() % width;
foodY = rand() % height;
//初始化分数和身体长度
score = 0;
snakeLength = 1;
}
//定义蛇移动的函数
void Move()
{
//更新蛇的身体坐标数组
int prevX = tailX[0];
int prevY = tailY[0];
int prev2X, prev2Y;
tailX[0] = snakeX;
tailY[0] = snakeY;
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:
snakeX--;
break;
case RIGHT:
snakeX++;
break;
case UP:
snakeY--;
break;
case DOWN:
snakeY++;
break;
}
//判断是否吃到食物
if (snakeX == foodX && snakeY == foodY)
{
score += 10;
snakeLength++;
nTail++;
foodX = rand() % width;
foodY = rand() % height;
}
//判断是否撞墙或撞到自己的身体
if (snakeX < 0 || snakeX >= width || snakeY < 0 || snakeY >= height)
{
cout << "Game Over!" << endl;
Sleep(2000); //暂停2秒
exit(0);
}
for (int i = 0; i < nTail; i++)
{
if (tailX[i] == snakeX && tailY[i] == snakeY)
{
cout << "Game Over!" << endl;
Sleep(2000); //暂停2秒
exit(0);
}
}
}
//定义获取键盘输入的函数
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':
cout << "Game Over!" << endl;
Sleep(2000); //暂停2秒
exit(0);
break;
}
}
}
//主函数
int main()
{
Setup(); //初始化游戏
while (true)
{
Draw(); //绘制游戏界面
Input(); //获取键盘输入
Move(); //移动蛇
Sleep(100); //暂停100毫秒,控制蛇的移动速度
}
return 0;
}
```
阅读全文