用c++写一个贪吃蛇的软件
时间: 2024-01-06 11:03:56 浏览: 22
好的,下面是一个简单的贪吃蛇游戏的C++代码示例,希望能帮到你:
```
#include <iostream>
#include <conio.h>
#include <Windows.h>
using namespace std;
const int width = 20; // 地图宽度
const int 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() {
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':
dir = STOP;
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) {
cout << "Game Over!" << endl;
exit(0);
}
if (x == fruitX && y == fruitY) {
score += 10;
fruitX = rand() % width;
fruitY = rand() % height;
nTail++;
}
// 判断是否咬到自己
for (int i = 0; i < nTail; i++) {
if (tailX[i] == x && tailY[i] == y) {
cout << "Game Over!" << endl;
exit(0);
}
}
}
int main() {
Setup();
while (true) {
Draw();
Input();
Logic();
Sleep(100); // 控制帧率
}
return 0;
}
```
这个示例中,我们使用了Windows.h库中的`Sleep()`函数来控制帧率,使游戏画面更加流畅。同时,我们使用了`_kbhit()`和`_getch()`函数来检测键盘输入,以实现控制蛇的方向。