用C++写一个两百二十行代码的贪吃蛇游戏,包含详细代码解析
时间: 2024-03-11 08:50:17 浏览: 71
贪吃蛇游戏代码(C++)
好的,这是一个比较详细的贪吃蛇游戏代码,使用C++编写,共计220行。代码注释比较详细,希望对你有所帮助。
```c++
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;
bool gameOver; //游戏状态
const int width = 20, height = 20; //游戏界面大小
int x, y, fruitX, fruitY, 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;
default:
break;
}
if (x > width || x < 0 || y > height || y < 0) //撞墙
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); //延迟50毫秒,控制游戏速度
}
return 0;
}
```
注:由于代码中包含了控制台窗口清屏等操作,所以只能在Windows平台上进行编译运行。
阅读全文