#include <iostream>
#include <conio.h>
using namespace std;
// 定义贪吃蛇节点结构体
struct Node {
int x;
int y;
};
const int width = 20; // 地图宽度
const int height = 20; // 地图高度
int score = 0; // 记录得分
bool gameOver = false; // 记录游戏是否结束
int foodX, foodY; // 食物的坐标
int sleepTime = 100; // 控制游戏速度的睡眠时间
char snakeHead = 'O'; // 蛇头的字符
char snakeBody = 'o'; // 蛇身的字符
Node snake[100]; // 定义贪吃蛇节点数组
int snakeSize = 1; // 记录贪吃蛇长度
void initMap() {
// 初始化地图
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (i == 0 || i == height - 1 || j == 0 || j == width - 1) {
cout << '#';
} else {
cout << ' ';
}
}
cout << endl;
}
}
void initSnake() {
// 初始化贪吃蛇
snake[0].x = 5;
snake[0].y = 5;
cout << snakeHead;
}
void generateFood() {
// 随机生成食物
int x = rand() % (height - 2) + 1;
int y = rand() % (width - 2) + 1;
foodX = x;
foodY = y;
gotoxy(foodY, foodX);
cout << '*';
}
void moveSnake() {
// 移动贪吃蛇
for (int i = snakeSize - 1; i > 0; i--) {
snake[i].x = snake[i - 1].x;
snake[i].y = snake[i - 1].y;
}
if (_kbhit()) {
// 如果用户按下了键盘,则根据键盘上的方向键,调整贪吃蛇的移动方向
switch (_getch()) {
case 'w':
snake[0].x--;
break;
case 'a':
snake[0].y--;
break;
case 's':
snake[0].x++;
break;
case 'd':
snake[0].y++;
break;
default:
break;
}
}
// 判断贪吃蛇是否吃到了食物
if (snake[0].x == foodX && snake[0].y == foodY) {
score += 10;
snakeSize++;
generateFood();
}
// 判断贪吃蛇是否撞到自己或撞到边界
if (snake[0].x == 0 || snake[0].x == height - 1 || snake[0].y == 0 || snake[0].y == width - 1) {
gameOver = true;
}
for (int i = 1; i < snakeSize; i++) {
if (snake[0].x == snake[i].x && snake[0].y == snake[i].y) {
gameOver = true;
break;
}
}
}
void showScore() {
// 显示得分
gotoxy(width + 2, 3);
cout << "Score: " << score;
}
void gameOverDisplay() {
// 游戏结束时的显示
system("cls");
cout << "Game Over!" << endl;
cout << "Your Score: " << score << endl;
}
int main() {
srand(time(NULL));
initMap();
initSnake();
generateFood();
while (!gameOver)
c++贪吃蛇代码(带注释)
最新推荐文章于 2024-09-17 22:32:53 发布