C++贪吃蛇
时间: 2023-07-11 21:20:17 浏览: 44
以下是一个简单的C++贪吃蛇游戏示例:
游戏规则:
1. 程序初始化一个10x10的游戏区域,蛇初始长度为3,出生位置在游戏区域中心。
2. 蛇头可以通过键盘控制上下左右移动,蛇身会随着蛇头的移动而跟随移动。
3. 当蛇头碰到游戏区域边缘或蛇身时,游戏结束。
4. 食物随机生成在游戏区域内,当蛇头碰到食物时,蛇身长度增加1。
代码示例:
```
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <conio.h>
using namespace std;
const int WIDTH = 10;
const int HEIGHT = 10;
const int MAX_LENGTH = 100;
struct Snake
{
int x[MAX_LENGTH];
int y[MAX_LENGTH];
int length;
};
struct Food
{
int x;
int y;
};
void initGame(Snake& snake, Food& food)
{
// 初始化蛇
snake.length = 3;
snake.x[0] = WIDTH / 2;
snake.y[0] = HEIGHT / 2;
snake.x[1] = WIDTH / 2;
snake.y[1] = HEIGHT / 2 + 1;
snake.x[2] = WIDTH / 2;
snake.y[2] = HEIGHT / 2 + 2;
// 初始化食物
srand(time(NULL));
food.x = rand() % WIDTH;
food.y = rand() % HEIGHT;
}
void drawMap(Snake& snake, Food& food)
{
system("cls"); // 清屏
// 绘制游戏区域
cout << "+";
for (int i = 0; i < WIDTH; i++)
{
cout << "-";
}
cout << "+" << endl;
for (int i = 0; i < HEIGHT; i++)
{
cout << "|";
for (int j = 0; j < WIDTH; j++)
{
bool isSnake = false;
for (int k = 0; k < snake.length; k++)
{
if (i == snake.y[k] && j == snake.x[k])
{
cout << "*";
isSnake = true;
break;
}
}
if (!isSnake)
{
if (i == food.y && j == food.x)
{
cout << "@";
}
else
{
cout << " ";
}
}
}
cout << "|" << endl;
}
cout << "+";
for (int i = 0; i < WIDTH; i++)
{
cout << "-";
}
cout << "+" << endl;
}
void move(Snake& snake, Food& food, char direction)
{
// 记录蛇尾位置
int tailX = snake.x[snake.length - 1];
int tailY = snake.y[snake.length - 1];
// 移动蛇身
for (int i = snake.length - 1; i > 0; i--)
{
snake.x[i] = snake.x[i - 1];
snake.y[i] = snake.y[i - 1];
}
// 移动蛇头
switch (direction)
{
case 'w':
snake.y[0]--;
break;
case 's':
snake.y[0]++;
break;
case 'a':
snake.x[0]--;
break;
case 'd':
snake.x[0]++;
break;
}
// 判断蛇头是否碰到游戏区域边缘
if (snake.x[0] < 0 || snake.x[0] >= WIDTH || snake.y[0] < 0 || snake.y[0] >= HEIGHT)
{
cout << "游戏结束!" << endl;
exit(0);
}
// 判断蛇头是否碰到蛇身
for (int i = 1; i < snake.length; i++)
{
if (snake.x[i] == snake.x[0] && snake.y[i] == snake.y[0])
{
cout << "游戏结束!" << endl;
exit(0);
}
}
// 判断蛇头是否碰到食物
if (snake.x[0] == food.x && snake.y[0] == food.y)
{
// 蛇身长度增加1
snake.length++;
snake.x[snake.length - 1] = tailX;
snake.y[snake.length - 1] = tailY;
// 重新生成食物
food.x = rand() % WIDTH;
food.y = rand() % HEIGHT;
}
}
int main()
{
Snake snake;
Food food;
char direction = 'd'; // 蛇头初始方向为右侧
initGame(snake, food);
while (true)
{
drawMap(snake, food);
move(snake, food, direction);
// 判断玩家输入的方向
if (_kbhit())
{
char input = _getch();
switch (input)
{
case 'w':
case 's':
case 'a':
case 'd':
direction = input;
break;
}
}
// 控制游戏速度
Sleep(100);
}
return 0;
}
```
这是一个简单的贪吃蛇游戏,通过学习和实践C++语言,可以编写出更加复杂、高级的游戏。