西工大计算科大作业课题b
为大家提供一个思路吧!
贪吃蛇游戏代码大纲
#include <iostream>
#include <conio.h>
#include <vector>
#include <ctime>
#include <cstdlib>
#include <windows.h>
using namespace std;
// 定义常量
const int kWidth = 20;
const int kHeight = 10;
// 定义方向
enum Direction {
UP,
DOWN,
LEFT,
RIGHT
};
// 定义食物结构体
struct Food {
int x, y;
};
// 定义蛇结构体
struct SnakeSegment {
int x, y;
};
class SnakeGame {
private:
vector<SnakeSegment> snake; // 蛇的身体
Food food; // 食物
Direction direction; // 蛇的方向
bool gameOver; // 游戏结束标志
public:
SnakeGame() : direction(RIGHT), gameOver(false) {
// 初始化蛇
snake.push_back({kWidth / 2, kHeight / 2});
snake.push_back({kWidth / 2 - 1, kHeight / 2});
snake.push_back({kWidth / 2 - 2, kHeight / 2});
// 初始化食物
generateFood();
}
// 生成食物
void generateFood() {
food.x = rand() % kWidth;
food.y = rand() % kHeight;
}
// 显示游戏画面
void render() {
system("cls");
// 显示蛇
for (const auto& segment : snake) {
cout << "*";
}
cout << endl;
// 显示食物和地图
for (int i = 0; i < kHeight; ++i) {
for (int j = 0; j < kWidth; ++j) {
if (i == food.y && j == food.x) {
cout << "@"; // 食物
} else if (i == snake[0].y && j == snake[0].x) {
cout << "O"; // 蛇头
} else {
bool isBodySegment = false;
for (size_t k = 1; k < snake.size(); ++k) {
if (i == snake[k].y && j == snake[k].x) {
cout << "*"; // 蛇身体
isBodySegment = true;
}
}
if (!isBodySegment) {
cout << " ";
}
}
}
cout << endl;
}
}
// 处理用户输入
void handleInput() {
if (_kbhit()) {
char key = _getch();
switch (key) {
case 'w':
direction = UP;
break;
case 's':
direction = DOWN;
break;
case 'a':
direction = LEFT;
break;
case 'd':
direction = RIGHT;
break;
case 'x':
gameOver = true;
break;
default:
break;
}
}
}
// 移动蛇
void move() {
SnakeSegment newHead = snake[0];
// 根据方向移动蛇头
switch (direction) {
case UP:
newHead.y--;
break;
case DOWN:
newHead.y++;
break;
case LEFT:
newHead.x--;
break;
case RIGHT:
newHead.x++;
break;
default:
break;
}
// 将新的蛇头插入到蛇的起始位置
snake.insert(snake.begin(), newHead);
// 检查是否吃到食物
if (newHead.x == food.x && newHead.y == food.y) {
generateFood();
} else {
// 移除蛇尾
snake.pop_back();
}
// 检查碰撞
checkCollision();
}
// 检查碰撞
void checkCollision() {
// 检查是否撞墙
if (snake[0].x < 0 || snake[0].x >= kWidth || snake[0].y < 0 || snake[0].y >= kHeight) {
gameOver = true;
}
// 检查是否咬到自己
for (size_t i = 1; i < snake.size(); ++i) {
if (snake[i].x == snake[0].x && snake[i].y == snake[0].y) {
gameOver = true;
}
}
}
// 运行游戏
void run() {
while (!gameOver) {
render();
handleInput();
move();
Sleep(100); // 控制游戏速度
}
// 游戏结束
cout << "Game Over! Your score: " << snake.size() - 3 << endl;
}
};
int main() {
srand(static_cast<unsigned>(time(nullptr)));
SnakeGame game;
game.run();
return 0;
}
这个简单的贪吃蛇游戏使用控制台进行显示,通过W
、A
、S
、D
键来控制蛇的移动方向,按X
键退出游戏。游戏在每个循环中进行渲染、用户输入处理和蛇的移动,通过Sleep
函数来控制游戏的速度。请注意,这只是一个基本的大纲,你可以根据需要扩展和改进游戏。
如有建议,可关注并私信我呀