贪吃蛇c++的小游戏
2025-05-06 21:01:14
发布于:浙江
#include <iostream>
#include <conio.h>
#include <windows.h>
#include <vector>
using namespace std;
// 定义游戏区域大小
const int width = 20;
const int height = 20;
// 蛇的结构体
struct Snake {
int x, y;
};
// 食物的结构体
struct Food {
int x, y;
};
// 蛇的方向
enum eDirection { STOP = 0, LEFT, RIGHT, UP, DOWN };
eDirection dir;
// 蛇的身体
vector<Snake> snake;
// 食物
Food food;
// 分数
int score;
// 设置光标位置
void gotoxy(int x, int y) {
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
// 隐藏光标
void hideCursor() {
HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO info;
info.dwSize = 100;
info.bVisible = FALSE;
SetConsoleCursorInfo(consoleHandle, &info);
}
// 初始化游戏
void Setup() {
hideCursor();
dir = STOP;
score = 0;
snake.clear();
snake.push_back({ width / 2, height / 2 });
food.x = rand() % width;
food.y = rand() % height;
}
// 绘制游戏界面
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 == snake[0].y && j == snake[0].x)
cout << "O";
else if (i == food.y && j == food.x)
cout << "F";
else {
bool print = false;
for (int k = 1; k < snake.size(); k++) {
if (snake[k].x == j && snake[k].y == 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':
if (dir != RIGHT)
dir = LEFT;
break;
case 'd':
if (dir != LEFT)
dir = RIGHT;
break;
case 'w':
if (dir != DOWN)
dir = UP;
break;
case 's':
if (dir != UP)
dir = DOWN;
break;
case 'x':
exit(0);
break;
}
}
}
// 游戏逻辑
void Logic() {
for (int i = snake.size() - 1; i > 0; i--) {
snake[i] = snake[i - 1];
}
switch (dir) {
case LEFT:
snake[0].x--;
break;
case RIGHT:
snake[0].x++;
break;
case UP:
snake[0].y--;
break;
case DOWN:
snake[0].y++;
break;
default:
break;
}
// 检查是否吃到食物
if (snake[0].x == food.x && snake[0].y == food.y) {
score += 10;
snake.push_back({ snake[snake.size() - 1].x, snake[snake.size() - 1].y });
food.x = rand() % width;
food.y = rand() % height;
}
// 检查是否撞到边界
if (snake[0].x < 0 || snake[0].x >= width || snake[0].y < 0 || snake[0].y >= height) {
cout << "Game Over!" << endl;
exit(0);
}
// 检查是否撞到自己
for (int i = 1; i < snake.size(); i++) {
if (snake[0].x == snake[i].x && snake[0].y == snake[i].y) {
cout << "Game Over!" << endl;
exit(0);
}
}
}
int main() {
Setup();
while (true) {
Draw();
Input();
Logic();
Sleep(100);
}
return 0;
}
全部评论 1
可以点个赞吗?
2025-05-06 来自 浙江
1
有帮助,赞一个