用c++写一个贪吃蛇的游戏
时间: 2023-11-27 18:02:51 浏览: 25
好的,以下是一个简单的贪吃蛇游戏的 C++ 程序。程序使用了 Windows API 的一些函数,因此只能在 Windows 操作系统下编译运行。
```c++
#include <iostream>
#include <windows.h>
#include <conio.h>
#include <time.h>
using namespace std;
const int width = 20; // 地图宽度
const int height = 20; // 地图高度
const int snakeMaxLength = 100; // 蛇的最大长度
int snakeX[snakeMaxLength], snakeY[snakeMaxLength]; // 蛇的坐标
int foodX, foodY; // 食物的坐标
int snakeLength = 3; // 蛇的长度
int direction = 1; // 蛇的方向
bool gameOver = false; // 游戏是否结束
void initSnake() {
// 初始化蛇的坐标
snakeX[0] = width / 2;
snakeY[0] = height / 2;
for (int i = 1; i < snakeLength; i++) {
snakeX[i] = snakeX[i-1] - 1;
snakeY[i] = snakeY[i-1];
}
}
void generateFood() {
// 随机生成食物的坐标
srand(time(NULL));
foodX = rand() % width;
foodY = rand() % height;
}
void drawMap() {
// 绘制地图和蛇和食物
system("cls"); // 清屏
for (int i = 0; i < width+2; i++) {
cout << "#";
}
cout << endl;
for (int i = 0; i < height; i++) {
cout << "#";
for (int j = 0; j < width; j++) {
bool snakeBody = false;
if (i == foodY && j == foodX) {
cout << "F";
} else {
for (int k = 0; k < snakeLength; k++) {
if (i == snakeY[k] && j == snakeX[k]) {
cout << "O";
snakeBody = true;
break;
}
}
if (!snakeBody) {
cout << " ";
}
}
}
cout << "#" << endl;
}
for (int i = 0; i < width+2; i++) {
cout << "#";
}
cout << endl;
}
void handleInput() {
// 处理用户的输入
if (_kbhit()) {
char ch = _getch();
switch (ch) {
case 'w':
if (direction != 2) {
direction = 0;
}
break;
case 'd':
if (direction != 3) {
direction = 1;
}
break;
case 's':
if (direction != 0) {
direction = 2;
}
break;
case 'a':
if (direction != 1) {
direction = 3;
}
break;
case 'q':
gameOver = true;
break;
}
}
}
void updateSnake() {
// 更新蛇的坐标
for (int i = snakeLength-1; i > 0; i--) {
snakeX[i] = snakeX[i-1];
snakeY[i] = snakeY[i-1];
}
switch (direction) {
case 0:
snakeY[0]--;
break;
case 1:
snakeX[0]++;
break;
case 2:
snakeY[0]++;
break;
case 3:
snakeX[0]--;
break;
}
}
bool checkCollision() {
// 检查蛇是否与边界或自身碰撞
if (snakeX[0] < 0 || snakeX[0] >= width || snakeY[0] < 0 || snakeY[0] >= height) {
return true;
}
for (int i = 1; i < snakeLength; i++) {
if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]) {
return true;
}
}
return false;
}
bool checkFood() {
// 检查蛇是否吃到了食物
if (snakeX[0] == foodX && snakeY[0] == foodY) {
snakeLength++;
if (snakeLength >= snakeMaxLength) {
return true;
}
generateFood();
}
return false;
}
int main() {
initSnake();
generateFood();
while (!gameOver) {
drawMap();
handleInput();
updateSnake();
if (checkCollision()) {
gameOver = true;
}
if (checkFood()) {
cout << "You win!" << endl;
gameOver = true;
}
Sleep(100); // 控制游戏速度
}
cout << "Game over!" << endl;
return 0;
}
```
程序实现了基本的贪吃蛇游戏功能,但是还有很多可以改进的地方,比如增加难度、优化代码等。