注意事项
要添加编译选项 -std=c++11
跑酷游戏
#include <iostream>
#include <vector>
#include <conio.h>
#include <windows.h>
#include <ctime>
#include <cstdlib>
#include <algorithm>
#include <sstream>
using namespace std;
// 隐藏控制台光标
void hideCursor() {
HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO cursorInfo;
GetConsoleCursorInfo(consoleHandle, &cursorInfo);
cursorInfo.bVisible = FALSE; // 设置光标不可见
SetConsoleCursorInfo(consoleHandle, &cursorInfo);
}
// 显示控制台光标
void showCursor() {
HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO cursorInfo;
GetConsoleCursorInfo(consoleHandle, &cursorInfo);
cursorInfo.bVisible = TRUE; // 设置光标可见
SetConsoleCursorInfo(consoleHandle, &cursorInfo);
}
// 设置控制台缓冲区大小
void setConsoleBufferSize(int width, int height) {
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
COORD bufferSize = {width, height};
SetConsoleScreenBufferSize(hConsole, bufferSize);
}
// 设置控制台窗口大小
void setConsoleWindowSize(int width, int height) {
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SMALL_RECT windowSize = {0, 0, width - 1, height - 1};
SetConsoleWindowInfo(hConsole, TRUE, &windowSize);
}
// 移动光标到指定位置
void setCursorPosition(int x, int y) {
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
COORD coord = {x, y};
SetConsoleCursorPosition(hConsole, coord);
}
// 游戏常量
const int SCREEN_WIDTH = 80; // 屏幕宽度
const int SCREEN_HEIGHT = 20; // 屏幕高度
const int GROUND_Y = 16; // 地面Y坐标
const int GRAVITY = 1; // 重力加速度
const int JUMP_POWER = -6; // 跳跃力度
const int INITIAL_SPEED = 2; // 初始速度
// 枚举类型定义
enum ObstacleType { ROCK, CACTUS, PIT };
enum PowerUpType { SPEED_BOOST, SHIELD, SLOW_DOWN, DOUBLE_JUMP, HEAL };
enum GameState { PLAYING, PAUSED, GAME_OVER };
// 玩家类
class Player {
private:
int x, y; // 位置坐标
int velocityY; // Y方向速度
bool isJumping; // 是否正在跳跃
bool canDoubleJump; // 是否可以二段跳
int health; // 生命值
int maxHealth; // 最大生命值
bool hasShield; // 是否有护盾
int shieldDuration; // 护盾持续时间
bool speedBoosted; // 是否有加速效果
int speedBoostDuration; // 加速持续时间
public:
Player() : x(10), y(GROUND_Y), velocityY(0), isJumping(false),
canDoubleJump(false), health(3), maxHealth(3),
hasShield(false), shieldDuration(0),
speedBoosted(false), speedBoostDuration(0) {}
// 获取坐标
int getX() const { return x; }
int getY() const { return y; }
int getHealth() const { return health; }
bool hasShieldActive() const { return hasShield; }
bool isSpeedBoosted() const { return speedBoosted; }
// 跳跃
void jump() {
if (!isJumping) { // 第一段跳
velocityY = JUMP_POWER;
isJumping = true;
canDoubleJump = true;
} else if (canDoubleJump) { // 第二段跳
velocityY = JUMP_POWER + 2; // 第二段跳力度稍小
canDoubleJump = false;
}
}
// 受伤
void takeDamage() {
if (hasShield) {
hasShield = false;
shieldDuration = 0;
Beep(800, 100); // 护盾破裂音效
return;
}
health--;
Beep(400, 200); // 受伤音效
}
// 治疗
void heal() {
health = min(health + 1, maxHealth);
Beep(1000, 100); // 治疗音效
}
// 激活护盾
void activateShield(int duration) {
hasShield = true;
shieldDuration = duration;
Beep(700, 100);
Beep(900, 100); // 护盾激活音效
}
// 激活加速
void activateSpeedBoost(int duration) {
speedBoosted = true;
speedBoostDuration = duration;
Beep(800, 50);
Beep(1200, 100); // 加速激活音效
}
// 允许二段跳
void enableDoubleJump() {
canDoubleJump = true;
Beep(600, 50);
Beep(800, 100); // 二段跳激活音效
}
// 更新玩家状态(处理重力和跳跃)
void update() {
// 应用重力
velocityY += GRAVITY;
y += velocityY;
// 确保玩家不会穿过地面
if (y >= GROUND_Y) {
y = GROUND_Y;
velocityY = 0;
isJumping = false;
canDoubleJump = false;
}
// 更新状态效果
if (shieldDuration > 0) {
shieldDuration--;
if (shieldDuration == 0) {
hasShield = false;
}
}
if (speedBoostDuration > 0) {
speedBoostDuration--;
if (speedBoostDuration == 0) {
speedBoosted = false;
}
}
}
// 绘制玩家
char getSprite() const {
if (hasShield) {
return 'O'; // 有护盾时的玩家
} else if (isJumping) {
return '^'; // 跳跃中的玩家
}
return 'P'; // 普通状态的玩家
}
// 检查是否存活
bool isAlive() const {
return health > 0;
}
};
// 障碍物类
class Obstacle {
private:
int x, y; // 位置坐标
ObstacleType type; // 障碍物类型
int width; // 宽度
int height; // 高度
public:
Obstacle(int startX, ObstacleType t) : x(startX), type(t) {
// 根据障碍物类型设置属性
switch (type) {
case ROCK:
y = GROUND_Y;
width = 2;
height = 1;
break;
case CACTUS:
y = GROUND_Y - 1;
width = 1;
height = 2;
break;
case PIT:
y = GROUND_Y;
width = 3;
height = 1;
break;
}
}
// 获取属性
int getX() const { return x; }
int getY() const { return y; }
int getWidth() const { return width; }
int getHeight() const { return height; }
ObstacleType getType() const { return type; }
// 更新障碍物位置(向左移动)
void update(int speed) {
x -= speed;
}
// 检查是否超出屏幕
bool isOffScreen() const {
return x + width < 0;
}
// 绘制障碍物
char getSprite(int localX, int localY) const {
switch (type) {
case ROCK:
return 'O';
case CACTUS:
return localY == 0 ? '|' : '/';
case PIT:
return '_';
default:
return '?';
}
}
// 碰撞检测
bool collidesWith(const Player& player) const {
// 简单的矩形碰撞检测
int playerBottom = player.getY();
int playerTop = player.getY() - 1; // 玩家高度约为2个单位
int obstacleLeft = x;
int obstacleRight = x + width - 1;
int obstacleTop = y - height + 1;
int obstacleBottom = y;
return !(player.getX() > obstacleRight ||
player.getX() < obstacleLeft ||
playerTop > obstacleBottom ||
playerBottom < obstacleTop);
}
};
// 道具类
class PowerUp {
private:
int x, y; // 位置坐标
PowerUpType type; // 道具类型
int duration; // 效果持续时间(帧)
public:
PowerUp(int startX, PowerUpType t) : x(startX), y(GROUND_Y - 1), type(t) {
// 根据道具类型设置持续时间
switch (type) {
case SPEED_BOOST: duration = 120; break;
case SHIELD: duration = 180; break;
case SLOW_DOWN: duration = 150; break;
case DOUBLE_JUMP: duration = 0; break; // 一次性效果
case HEAL: duration = 0; break; // 一次性效果
}
}
// 获取属性
int getX() const { return x; }
int getY() const { return y; }
PowerUpType getType() const { return type; }
int getDuration() const { return duration; }
// 更新道具位置
void update(int speed) {
x -= speed;
}
// 检查是否超出屏幕
bool isOffScreen() const {
return x < 0;
}
// 绘制道具
char getSprite() const {
switch (type) {
case SPEED_BOOST: return 'S';
case SHIELD: return 'H';
case SLOW_DOWN: return 'L';
case DOUBLE_JUMP: return 'J';
case HEAL: return '+';
default: return '?';
}
}
// 碰撞检测
bool collidesWith(const Player& player) const {
return abs(x - player.getX()) < 2 && abs(y - player.getY()) < 2;
}
};
// 背景元素类
class BackgroundElement {
private:
int x, y;
char sprite;
int speed;
public:
BackgroundElement(int startX) : x(startX) {
// 随机生成背景元素
y = rand() % (GROUND_Y - 5) + 1;
speed = rand() % 2 + 1; // 1或2的速度
// 随机选择背景元素
const char* sprites = "/*.|";
sprite = sprites[rand() % 4];
}
void update() {
x -= speed;
}
bool isOffScreen() const {
return x < 0;
}
int getX() const { return x; }
int getY() const { return y; }
char getSprite() const { return sprite; }
};
// 游戏类
class Game {
private:
Player player;
vector<Obstacle> obstacles;
vector<PowerUp> powerUps;
vector<BackgroundElement> background;
int score;
int highScore;
int level;
int gameSpeed;
int obstacleSpawnTimer;
int powerUpSpawnTimer;
int backgroundSpawnTimer;
GameState state;
bool slowDownActive;
int slowDownDuration;
HANDLE hConsole; // 控制台句柄
CHAR_INFO* buffer; // 双缓冲缓冲区
COORD bufferSize; // 缓冲区大小
SMALL_RECT writeRegion;// 写入区域
public:
Game() : score(0), highScore(0), level(1), gameSpeed(INITIAL_SPEED),
obstacleSpawnTimer(0), powerUpSpawnTimer(0), backgroundSpawnTimer(0),
state(PLAYING), slowDownActive(false), slowDownDuration(0) {
// 初始化双缓冲
hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
bufferSize.X = SCREEN_WIDTH;
bufferSize.Y = SCREEN_HEIGHT + 6; // 游戏区域 + 信息区域
writeRegion = {0, 0, bufferSize.X - 1, bufferSize.Y - 1};
buffer = new CHAR_INFO[bufferSize.X * bufferSize.Y];
}
~Game() {
delete[] buffer; // 释放缓冲区内存
}
// 初始化游戏
void init() {
srand(time(0));
score = 0;
level = 1;
gameSpeed = INITIAL_SPEED;
state = PLAYING;
slowDownActive = false;
slowDownDuration = 0;
obstacles.clear();
powerUps.clear();
background.clear();
player = Player();
// 初始化缓冲区
for (int i = 0; i < bufferSize.X * bufferSize.Y; i++) {
buffer[i].Char.AsciiChar = ' ';
buffer[i].Attributes = 7; // 白色文本
}
}
// 处理输入
void handleInput() {
if (_kbhit()) {
char key = _getch();
if (key == ' ' || key == 'w' || key == 'W') { // 空格或W键跳跃
if (state == PLAYING) {
player.jump();
} else if (state == GAME_OVER) {
init(); // 游戏结束后按跳跃键重新开始
}
}
if (key == 'p' || key == 'P') { // P键暂停/继续
if (state == PLAYING) {
state = PAUSED;
} else if (state == PAUSED) {
state = PLAYING;
}
}
if (key == 'q' || key == 'Q') { // Q键退出游戏
showCursor(); // 退出前显示光标
exit(0);
}
}
}
// 获取当前游戏速度(考虑各种效果)
int getCurrentSpeed() const {
if (state != PLAYING) return 0;
int currentSpeed = gameSpeed;
if (slowDownActive) {
currentSpeed = max(1, currentSpeed / 2);
}
if (player.isSpeedBoosted()) {
currentSpeed = min(currentSpeed * 2, 10);
}
return currentSpeed;
}
// 更新游戏状态
void update() {
if (state != PLAYING) return;
// 更新玩家
player.update();
// 更新背景元素
backgroundSpawnTimer++;
if (backgroundSpawnTimer > 10) {
background.emplace_back(SCREEN_WIDTH - 1);
backgroundSpawnTimer = 0;
}
for (auto& elem : background) {
elem.update();
}
background.erase(remove_if(background.begin(), background.end(),
[](const BackgroundElement& elem) { return elem.isOffScreen(); }),
background.end());
// 更新减速效果
if (slowDownActive) {
slowDownDuration--;
if (slowDownDuration == 0) {
slowDownActive = false;
}
}
// 生成障碍物(随等级提高而增加频率和难度)
int currentSpeed = getCurrentSpeed();
obstacleSpawnTimer++;
int spawnRate = max(30, 120 - (level * 10)); // 随等级提高,生成频率增加
if (obstacleSpawnTimer > spawnRate) {
// 随机选择障碍物类型
int randType = rand() % 10;
ObstacleType type;
if (randType < 5) type = ROCK;
else if (randType < 8) type = CACTUS;
else type = PIT;
obstacles.emplace_back(SCREEN_WIDTH - 1, type);
obstacleSpawnTimer = 0;
}
// 更新障碍物
for (auto& obstacle : obstacles) {
obstacle.update(currentSpeed);
}
// 移除超出屏幕的障碍物
obstacles.erase(remove_if(obstacles.begin(), obstacles.end(),
[](const Obstacle& obs) { return obs.isOffScreen(); }),
obstacles.end());
// 生成道具
powerUpSpawnTimer++;
if (powerUpSpawnTimer > 200) { // 道具生成频率
int randType = rand() % 10;
PowerUpType type;
if (randType < 2) type = SPEED_BOOST;
else if (randType < 4) type = SHIELD;
else if (randType < 6) type = SLOW_DOWN;
else if (randType < 8) type = DOUBLE_JUMP;
else type = HEAL;
powerUps.emplace_back(SCREEN_WIDTH - 1, type);
powerUpSpawnTimer = 0;
}
// 更新道具
for (auto& powerUp : powerUps) {
powerUp.update(currentSpeed);
}
// 移除超出屏幕的道具
powerUps.erase(remove_if(powerUps.begin(), powerUps.end(),
[](const PowerUp& pu) { return pu.isOffScreen(); }),
powerUps.end());
// 检测道具碰撞
for (auto it = powerUps.begin(); it != powerUps.end();) {
if (it->collidesWith(player)) {
// 应用道具效果
switch (it->getType()) {
case SPEED_BOOST:
player.activateSpeedBoost(it->getDuration());
break;
case SHIELD:
player.activateShield(it->getDuration());
break;
case SLOW_DOWN:
slowDownActive = true;
slowDownDuration = it->getDuration();
break;
case DOUBLE_JUMP:
player.enableDoubleJump();
break;
case HEAL:
player.heal();
break;
}
it = powerUps.erase(it);
} else {
++it;
}
}
// 检测障碍物碰撞
for (auto it = obstacles.begin(); it != obstacles.end();) {
if (it->collidesWith(player)) {
player.takeDamage();
it = obstacles.erase(it);
// 检查玩家是否死亡
if (!player.isAlive()) {
state = GAME_OVER;
highScore = max(highScore, score);
break;
}
} else {
++it;
}
}
// 增加分数
score++;
// 升级逻辑
int newLevel = (score / 500) + 1;
if (newLevel > level) {
level = newLevel;
gameSpeed = min(INITIAL_SPEED + (level - 1), 8); // 最大速度限制
Beep(500, 100);
Beep(1000, 200); // 升级音效
}
}
// 绘制游戏到缓冲区
void drawToBuffer() {
// 清空缓冲区
for (int i = 0; i < bufferSize.X * bufferSize.Y; i++) {
buffer[i].Char.AsciiChar = ' ';
buffer[i].Attributes = 7; // 白色文本
}
// 绘制天空和背景
for (int y = 0; y < SCREEN_HEIGHT; y++) {
for (int x = 0; x < SCREEN_WIDTH; x++) {
bool drawn = false;
// 绘制背景元素
if (!drawn) {
for (const auto& elem : background) {
if (x == elem.getX() && y == elem.getY()) {
buffer[y * bufferSize.X + x].Char.AsciiChar = elem.getSprite();
buffer[y * bufferSize.X + x].Attributes = 8; // 灰色
drawn = true;
break;
}
}
}
// 绘制玩家
if (!drawn && x == player.getX() && y == player.getY()) {
buffer[y * bufferSize.X + x].Char.AsciiChar = player.getSprite();
buffer[y * bufferSize.X + x].Attributes = 10; // 绿色
drawn = true;
}
// 绘制玩家上方(用于二段跳显示)
if (!drawn && x == player.getX() && y == player.getY() - 1 && player.getSprite() == '^') {
buffer[y * bufferSize.X + x].Char.AsciiChar = 'P';
buffer[y * bufferSize.X + x].Attributes = 10; // 绿色
drawn = true;
}
// 绘制道具
if (!drawn) {
for (const auto& powerUp : powerUps) {
if (x == powerUp.getX() && y == powerUp.getY()) {
buffer[y * bufferSize.X + x].Char.AsciiChar = powerUp.getSprite();
buffer[y * bufferSize.X + x].Attributes = 14; // 黄色
drawn = true;
break;
}
}
}
// 绘制障碍物
if (!drawn) {
for (const auto& obstacle : obstacles) {
for (int ox = 0; ox < obstacle.getWidth(); ox++) {
for (int oy = 0; oy < obstacle.getHeight(); oy++) {
if (x == obstacle.getX() + ox && y == obstacle.getY() - oy) {
buffer[y * bufferSize.X + x].Char.AsciiChar = obstacle.getSprite(ox, oy);
buffer[y * bufferSize.X + x].Attributes = 12; // 红色
drawn = true;
break;
}
}
if (drawn) break;
}
}
}
// 绘制地面和天空
if (!drawn) {
if (y == GROUND_Y) {
buffer[y * bufferSize.X + x].Char.AsciiChar = '-';
buffer[y * bufferSize.X + x].Attributes = 2; // 绿色
} else {
buffer[y * bufferSize.X + x].Char.AsciiChar = ' ';
}
}
}
}
// 显示游戏信息(在屏幕下方)
int infoY = SCREEN_HEIGHT;
stringstream ss;
ss << "分数: " << score << " 最高分: " << highScore;
string scoreStr = ss.str();
for (int i = 0; i < scoreStr.size() && i < SCREEN_WIDTH; i++) {
buffer[infoY * bufferSize.X + i].Char.AsciiChar = scoreStr[i];
buffer[infoY * bufferSize.X + i].Attributes = 11; // 青色
}
infoY++;
ss.str("");
ss << "等级: " << level << " 速度: " << getCurrentSpeed();
string levelStr = ss.str();
for (int i = 0; i < levelStr.size() && i < SCREEN_WIDTH; i++) {
buffer[infoY * bufferSize.X + i].Char.AsciiChar = levelStr[i];
buffer[infoY * bufferSize.X + i].Attributes = 11; // 青色
}
infoY++;
ss.str("");
ss << "生命值: ";
for (int i = 0; i < player.getHealth(); i++) {
ss << "?";
}
string healthStr = ss.str();
for (int i = 0; i < healthStr.size() && i < SCREEN_WIDTH; i++) {
buffer[infoY * bufferSize.X + i].Char.AsciiChar = healthStr[i];
buffer[infoY * bufferSize.X + i].Attributes = 12; // 红色
}
infoY++;
ss.str("");
if (player.hasShieldActive()) ss << "护盾激活! ";
if (player.isSpeedBoosted()) ss << "速度提升! ";
if (slowDownActive) ss << "世界减速! ";
string statusStr = ss.str();
for (int i = 0; i < statusStr.size() && i < SCREEN_WIDTH; i++) {
buffer[infoY * bufferSize.X + i].Char.AsciiChar = statusStr[i];
buffer[infoY * bufferSize.X + i].Attributes = 14; // 黄色
}
infoY++;
ss.str("");
ss << "按空格/W跳跃,P暂停,Q退出";
if (state == PAUSED) {
ss << " | 游戏暂停 - 按P继续";
} else if (state == GAME_OVER) {
ss << " | 游戏结束 - 按空格重新开始";
}
string helpStr = ss.str();
for (int i = 0; i < helpStr.size() && i < SCREEN_WIDTH; i++) {
buffer[infoY * bufferSize.X + i].Char.AsciiChar = helpStr[i];
buffer[infoY * bufferSize.X + i].Attributes = 7; // 白色
}
}
// 将缓冲区内容显示到屏幕
void drawToScreen() {
WriteConsoleOutputA(hConsole, buffer, bufferSize, {0, 0}, &writeRegion);
}
// 绘制游戏(双缓冲版本)
void draw() {
drawToBuffer(); // 先绘制到内存缓冲区
drawToScreen(); // 再一次性显示到屏幕
}
// 游戏主循环
void run() {
init();
hideCursor(); // 游戏开始时隐藏光标
setConsoleBufferSize(SCREEN_WIDTH, SCREEN_HEIGHT + 6);
setConsoleWindowSize(SCREEN_WIDTH, SCREEN_HEIGHT + 6);
while (true) {
handleInput();
update();
draw();
Sleep(50); // 控制游戏帧率
}
}
};
int main() {
// 设置控制台标题
SetConsoleTitleA("跑酷游戏");
// 初始化控制台
setConsoleBufferSize(SCREEN_WIDTH, SCREEN_HEIGHT + 6);
setConsoleWindowSize(SCREEN_WIDTH, SCREEN_HEIGHT + 6);
cout << "欢迎来到高级跑酷游戏!" << endl;
cout << "游戏特色:" << endl;
cout << "- 多种障碍物(岩石、仙人掌、陷阱)" << endl;
cout << "- 各种道具(加速、护盾、减速、二段跳、治疗)" << endl;
cout << "- 生命值系统,不再一碰就死" << endl;
cout << "- 等级提升,难度逐渐增加" << endl;
cout << endl;
cout << "操作说明:" << endl;
cout << "- 空格或W键: 跳跃(可二段跳)" << endl;
cout << "- P键: 暂停/继续游戏" << endl;
cout << "- Q键: 退出游戏" << endl;
cout << endl;
cout << "按任意键开始游戏..." << endl;
_getch(); // 等待用户按键
// 清屏并开始游戏
system("cls");
Game game;
game.run();
showCursor(); // 程序正常结束时显示光标
return 0;
}
文字游戏
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <cstdlib>
#include <ctime>
#include <windows.h>
#include <algorithm>
#include <fstream>
#include <sstream>
using namespace std;
// 前向声明
class Item;
class Character;
class Location;
class Quest;
// 物品类
class Item {
private:
string name;
string description;
bool isUsable;
bool isQuestItem;
int attackBonus; // 攻击加成
int defenseBonus; // 防御加成
int healAmount; // 治疗量
public:
Item(string n, string d, bool usable, bool questItem,
int atk = 0, int def = 0, int heal = 0)
: name(n), description(d), isUsable(usable), isQuestItem(questItem),
attackBonus(atk), defenseBonus(def), healAmount(heal) {}
string getName() const { return name; }
string getDescription() const { return description; }
bool getIsUsable() const { return isUsable; }
bool getIsQuestItem() const { return isQuestItem; }
int getAttackBonus() const { return attackBonus; }
int getDefenseBonus() const { return defenseBonus; }
int getHealAmount() const { return healAmount; }
// 使用物品
bool use(Character& player);
// 物品序列化(用于存档)
string serialize() const {
return name + "|" + description + "|" + to_string(isUsable) + "|" + to_string(isQuestItem) +
"|" + to_string(attackBonus) + "|" + to_string(defenseBonus) + "|" + to_string(healAmount);
}
// 物品反序列化(用于读档)
static Item* deserialize(const string& data) {
vector<string> parts;
stringstream ss(data);
string part;
while (getline(ss, part, '|')) {
parts.push_back(part);
}
if (parts.size() != 7) return nullptr;
return new Item(
parts[0],
parts[1],
parts[2] == "1",
parts[3] == "1",
stoi(parts[4]),
stoi(parts[5]),
stoi(parts[6])
);
}
};
// 任务类
class Quest {
private:
string name;
string description;
bool isCompleted;
Item* rewardItem;
int rewardGold;
string completionCondition; // 完成条件描述
public:
Quest(string n, string d, string condition, Item* reward = nullptr, int gold = 0)
: name(n), description(d), isCompleted(false),
rewardItem(reward), rewardGold(gold), completionCondition(condition) {}
string getName() const { return name; }
string getDescription() const { return description; }
bool getIsCompleted() const { return isCompleted; }
string getCompletionCondition() const { return completionCondition; }
Item* getRewardItem() const { return rewardItem; }
int getRewardGold() const { return rewardGold; }
void complete(Character& player);
bool checkCompletion(Character& player);
// 设置任务完成状态(用于读档)
void setCompleted(bool completed) { isCompleted = completed; }
// 任务序列化(用于存档)
string serialize() const {
string rewardName = rewardItem ? rewardItem->getName() : "null";
return name + "|" + description + "|" + to_string(isCompleted) + "|" + rewardName +
"|" + to_string(rewardGold) + "|" + completionCondition;
}
// 任务反序列化(用于读档)
static Quest* deserialize(const string& data, const vector<Item*>& allItems) {
vector<string> parts;
stringstream ss(data);
string part;
while (getline(ss, part, '|')) {
parts.push_back(part);
}
if (parts.size() != 6) return nullptr;
Item* rewardItem = nullptr;
if (parts[3] != "null") {
for (auto item : allItems) {
if (item->getName() == parts[3]) {
rewardItem = item;
break;
}
}
}
Quest* quest = new Quest(
parts[0],
parts[1],
parts[5],
rewardItem,
stoi(parts[4])
);
quest->setCompleted(parts[2] == "1");
return quest;
}
};
// 角色类
class Character {
private:
string name;
int health;
int maxHealth;
int strength; // 影响攻击力
int agility; // 影响命中率和闪避
int intelligence; // 影响对话选项和魔法
int gold;
vector<Item*> inventory;
vector<Quest*> quests;
map<string, bool> flags; // 用于跟踪剧情状态
Item* equippedWeapon;
Item* equippedArmor;
public:
Character(string n) : name(n), health(100), maxHealth(100),
strength(5), agility(5), intelligence(5),
gold(0), equippedWeapon(nullptr), equippedArmor(nullptr) {}
// 带参数的构造函数,用于创建敌人
Character(string n, int hp, int str, int agi, int intel, int g)
: name(n), health(hp), maxHealth(hp),
strength(str), agility(agi), intelligence(intel),
gold(g), equippedWeapon(nullptr), equippedArmor(nullptr) {}
// 属性获取
string getName() const { return name; }
int getHealth() const { return health; }
int getMaxHealth() const { return maxHealth; }
int getStrength() const { return strength; }
int getAgility() const { return agility; }
int getIntelligence() const { return intelligence; }
int getGold() const { return gold; }
Item* getEquippedWeapon() const { return equippedWeapon; }
Item* getEquippedArmor() const { return equippedArmor; }
// 获取背包物品
vector<Item*>& getInventory() { return inventory; }
const vector<Item*>& getInventory() const { return inventory; }
// 获取任务列表
vector<Quest*>& getQuests() { return quests; }
const vector<Quest*>& getQuests() const { return quests; }
// 获取剧情标记
map<string, bool>& getFlags() { return flags; }
const map<string, bool>& getFlags() const { return flags; }
// 计算实际战斗属性
int getAttack() const {
int atk = strength;
if (equippedWeapon) atk += equippedWeapon->getAttackBonus();
return atk;
}
int getDefense() const {
int def = (agility / 2);
if (equippedArmor) def += equippedArmor->getDefenseBonus();
return def;
}
// 属性修改
void takeDamage(int damage) {
health = max(0, health - damage);
cout << name << "受到了" << damage << "点伤害!" << endl;
}
void heal(int amount) {
health = min(maxHealth, health + amount);
cout << name << "恢复了" << amount << "点生命值!" << endl;
}
void addGold(int amount) {
gold += amount;
cout << name << "获得了" << amount << "枚金币!" << endl;
}
bool spendGold(int amount) {
if (gold >= amount) {
gold -= amount;
cout << name << "花费了" << amount << "枚金币。" << endl;
return true;
}
cout << "金币不足!" << endl;
return false;
}
void increaseStat(string stat, int amount) {
if (stat == "strength") strength += amount;
else if (stat == "agility") agility += amount;
else if (stat == "intelligence") intelligence += amount;
else if (stat == "maxHealth") {
maxHealth += amount;
health = maxHealth;
}
cout << name << "的" << stat << "提升了!" << endl;
}
// 物品管理
void addItem(Item* item) {
inventory.push_back(item);
cout << "获得了:" << item->getName() << endl;
}
bool hasItem(string itemName) const {
for (const auto& item : inventory) {
if (item->getName() == itemName) return true;
}
return false;
}
Item* getItem(string itemName) {
for (auto& item : inventory) {
if (item->getName() == itemName) return item;
}
return nullptr;
}
bool removeItem(string itemName) {
for (auto it = inventory.begin(); it != inventory.end(); ++it) {
if ((*it)->getName() == itemName) {
inventory.erase(it);
return true;
}
}
return false;
}
void equipWeapon(Item* item) {
if (item->getAttackBonus() > 0) {
equippedWeapon = item;
cout << "装备了" << item->getName() << endl;
} else {
cout << "这不是武器!" << endl;
}
}
void equipArmor(Item* item) {
if (item->getDefenseBonus() > 0) {
equippedArmor = item;
cout << "装备了" << item->getName() << endl;
} else {
cout << "这不是防具!" << endl;
}
}
// 任务管理
void addQuest(Quest* quest) {
quests.push_back(quest);
cout << "接受了任务:" << quest->getName() << endl;
cout << "任务描述:" << quest->getDescription() << endl;
cout << "目标:" << quest->getCompletionCondition() << endl;
}
vector<Quest*> getActiveQuests() const {
vector<Quest*> active;
for (const auto& quest : quests) {
if (!quest->getIsCompleted()) active.push_back(quest);
}
return active;
}
// 剧情标记
void setFlag(string flag, bool value = true) {
flags[flag] = value;
}
bool hasFlag(string flag) const {
auto it = flags.find(flag);
return (it != flags.end() && it->second);
}
// 显示角色状态
void showStatus() const {
cout << "\n【" << name << "的状态】" << endl;
cout << "生命值:" << health << "/" << maxHealth << endl;
cout << "力量:" << strength << " (影响攻击力)" << endl;
cout << "敏捷:" << agility << " (影响命中和闪避)" << endl;
cout << "智力:" << intelligence << " (影响对话和魔法)" << endl;
cout << "金币:" << gold << endl;
cout << "装备:";
if (equippedWeapon) cout << "武器 - " << equippedWeapon->getName() << " ";
else cout << "无武器 ";
if (equippedArmor) cout << "防具 - " << equippedArmor->getName() << endl;
else cout << "无防具" << endl;
}
// 显示背包
void showInventory() const {
if (inventory.empty()) {
cout << "背包是空的。" << endl;
return;
}
cout << "\n【背包】" << endl;
for (size_t i = 0; i < inventory.size(); ++i) {
cout << i+1 << ". " << inventory[i]->getName() << " - "
<< inventory[i]->getDescription() << endl;
}
}
// 显示任务
void showQuests() const {
vector<Quest*> activeQuests = getActiveQuests();
if (activeQuests.empty()) {
cout << "没有正在进行的任务。" << endl;
return;
}
cout << "\n【当前任务】" << endl;
for (size_t i = 0; i < activeQuests.size(); ++i) {
cout << i+1 << ". " << activeQuests[i]->getName() << endl;
cout << " " << activeQuests[i]->getDescription() << endl;
cout << " 目标:" << activeQuests[i]->getCompletionCondition() << endl;
}
}
bool isAlive() const { return health > 0; }
// 设置装备(用于读档)
void setEquippedWeapon(Item* weapon) { equippedWeapon = weapon; }
void setEquippedArmor(Item* armor) { equippedArmor = armor; }
// 设置基础属性(用于读档)
void setHealth(int hp) { health = hp; }
void setMaxHealth(int maxHp) { maxHealth = maxHp; }
void setStrength(int str) { strength = str; }
void setAgility(int agi) { agility = agi; }
void setIntelligence(int intel) { intelligence = intel; }
void setGold(int g) { gold = g; }
// 清空背包和任务(读档前初始化)
void clearInventory() { inventory.clear(); }
void clearQuests() { quests.clear(); }
void clearFlags() { flags.clear(); }
// 角色序列化(用于存档)
string serialize() const {
// 1. 基础属性
string base = name + "|" + to_string(health) + "|" + to_string(maxHealth) + "|" +
to_string(strength) + "|" + to_string(agility) + "|" + to_string(intelligence) + "|" + to_string(gold);
// 2. 装备
string weapon = equippedWeapon ? equippedWeapon->getName() : "null";
string armor = equippedArmor ? equippedArmor->getName() : "null";
string equip = weapon + "|" + armor;
// 3. 背包物品
string inventoryData = to_string(inventory.size());
for (auto item : inventory) {
inventoryData += "|" + item->serialize();
}
// 4. 任务
string questData = to_string(quests.size());
for (auto quest : quests) {
questData += "|" + quest->serialize();
}
// 5. 剧情标记
string flagData = to_string(flags.size());
for (auto& pair : flags) {
flagData += "|" + pair.first + "|" + to_string(pair.second);
}
// 拼接所有部分
return base + "##" + equip + "##" + inventoryData + "##" + questData + "##" + flagData;
}
// 角色反序列化(用于读档)
bool deserialize(const string& data, const vector<Item*>& allItems) {
// 分割模块
vector<string> modules;
stringstream ss(data);
string module;
while (getline(ss, module, '#')) {
if (!module.empty()) {
modules.push_back(module);
}
}
if (modules.size() != 5) return false;
// 1. 解析基础属性
vector<string> baseParts;
stringstream baseSS(modules[0]);
while (getline(baseSS, module, '|')) {
baseParts.push_back(module);
}
if (baseParts.size() != 7) return false;
setHealth(stoi(baseParts[1]));
setMaxHealth(stoi(baseParts[2]));
setStrength(stoi(baseParts[3]));
setAgility(stoi(baseParts[4]));
setIntelligence(stoi(baseParts[5]));
setGold(stoi(baseParts[6]));
// 2. 解析装备
vector<string> equipParts;
stringstream equipSS(modules[1]);
while (getline(equipSS, module, '|')) {
equipParts.push_back(module);
}
if (equipParts.size() != 2) return false;
// 匹配武器
Item* weapon = nullptr;
if (equipParts[0] != "null") {
for (auto item : allItems) {
if (item->getName() == equipParts[0]) {
weapon = item;
break;
}
}
}
setEquippedWeapon(weapon);
// 匹配防具
Item* armor = nullptr;
if (equipParts[1] != "null") {
for (auto item : allItems) {
if (item->getName() == equipParts[1]) {
armor = item;
break;
}
}
}
setEquippedArmor(armor);
// 3. 解析背包
clearInventory();
vector<string> inventoryParts;
stringstream invSS(modules[2]);
while (getline(invSS, module, '|')) {
inventoryParts.push_back(module);
}
if (inventoryParts.empty()) return false;
int invSize = stoi(inventoryParts[0]);
for (int i = 0; i < invSize; ++i) {
if (i + 1 >= (int)inventoryParts.size()) break;
Item* item = Item::deserialize(inventoryParts[i + 1]);
if (item) {
inventory.push_back(item);
}
}
// 4. 解析任务
clearQuests();
vector<string> questParts;
stringstream questSS(modules[3]);
while (getline(questSS, module, '|')) {
questParts.push_back(module);
}
if (questParts.empty()) return false;
int questSize = stoi(questParts[0]);
for (int i = 0; i < questSize; ++i) {
if (i + 1 >= (int)questParts.size()) break;
Quest* quest = Quest::deserialize(questParts[i + 1], allItems);
if (quest) {
quests.push_back(quest);
}
}
// 5. 解析剧情标记
clearFlags();
vector<string> flagParts;
stringstream flagSS(modules[4]);
while (getline(flagSS, module, '|')) {
flagParts.push_back(module);
}
if (flagParts.empty()) return false;
int flagSize = stoi(flagParts[0]);
for (int i = 0; i < flagSize; ++i) {
if (i * 2 + 1 >= (int)flagParts.size()) break;
string flagName = flagParts[i * 2 + 1];
bool flagValue = flagParts[i * 2 + 2] == "1";
flags[flagName] = flagValue;
}
return true;
}
};
// NPC类
class NPC {
private:
string name;
string description;
vector<string> dialogs; // 基础对话
map<string, string> conditionalDialogs; // 条件对话(基于玩家状态)
map<string, Item*> tradeItems; // 可交易物品
Quest* questToGive; // 可给予的任务
public:
NPC(string n, string d, Quest* quest = nullptr)
: name(n), description(d), questToGive(quest) {}
void addDialog(string dialog) { dialogs.push_back(dialog); }
void addConditionalDialog(string flag, string dialog) {
conditionalDialogs[flag] = dialog;
}
void addTradeItem(Item* item, int price) {
tradeItems[item->getName()] = item;
}
string getName() const { return name; }
string getDescription() const { return description; }
// 与NPC对话
void talkTo(Character& player);
// 与NPC交易
void tradeWith(Character& player);
};
// 位置类
class Location {
private:
string name;
string description;
map<string, Location*> exits; // 出口 (方向 -> 位置)
vector<NPC*> npcs;
vector<Item*> items; // 可拾取物品
vector<string> events; // 随机事件
map<string, string> conditionalDescriptions; // 条件描述
string locationId; // 用于存档的唯一标识
public:
Location(string id, string n, string d) : locationId(id), name(n), description(d) {}
void addExit(string direction, Location* location) {
exits[direction] = location;
}
void addNPC(NPC* npc) { npcs.push_back(npc); }
void addItem(Item* item) { items.push_back(item); }
void addEvent(string event) { events.push_back(event); }
void addConditionalDescription(string flag, string desc) {
conditionalDescriptions[flag] = desc;
}
string getName() const { return name; }
string getDescription(Character& player) const;
string getLocationId() const { return locationId; }
// 获取NPC列表
vector<NPC*>& getNPCs() { return npcs; }
const vector<NPC*>& getNPCs() const { return npcs; }
// 获取物品列表
vector<Item*>& getItems() { return items; }
const vector<Item*>& getItems() const { return items; }
// 移除物品
bool removeItem(string itemName) {
for (auto it = items.begin(); it != items.end(); ++it) {
if ((*it)->getName() == itemName) {
items.erase(it);
return true;
}
}
return false;
}
// 显示位置信息
void display(Character& player);
// 探索位置
void explore(Character& player);
// 移动到其他位置
Location* move(string direction) {
auto it = exits.find(direction);
if (it != exits.end()) {
return it->second;
}
return nullptr;
}
// 序列化位置(仅保存ID用于存档)
string serialize() const {
return locationId;
}
};
// 战斗系统
namespace Combat {
bool fight(Character& player, Character& enemy);
}
// 游戏类
class Game {
private:
Character* player;
Location* currentLocation;
vector<Item*> allItems;
vector<Quest*> allQuests;
vector<Location*> allLocations; // 所有位置,用于读档时查找
bool gameOver;
string ending; // 结局类型
public:
Game(string playerName) : gameOver(false), ending("") {
initializeWorld();
player = new Character(playerName);
// 初始物品
player->addItem(getItem("铁剑"));
player->equipWeapon(player->getItem("铁剑"));
}
~Game() {
delete player;
for (auto item : allItems) delete item;
for (auto quest : allQuests) delete quest;
for (auto loc : allLocations) delete loc;
}
void initializeWorld();
Item* getItem(string name) {
for (auto item : allItems) {
if (item->getName() == name) return item;
}
return nullptr;
}
// 查找位置(用于读档)
Location* getLocationById(string id) {
for (auto loc : allLocations) {
if (loc->getLocationId() == id) return loc;
}
return nullptr;
}
void play();
void checkEndingConditions();
void showEnding();
// 新增:保存游戏
bool saveGame(string filename) {
ofstream file(filename);
if (!file.is_open()) {
cout << "无法打开存档文件进行写入!" << endl;
return false;
}
// 1. 保存当前位置
file << currentLocation->serialize() << endl;
// 2. 保存玩家数据
file << player->serialize() << endl;
file.close();
cout << "游戏已成功保存到 " << filename << endl;
return true;
}
// 新增:读取游戏
bool loadGame(string filename) {
ifstream file(filename);
if (!file.is_open()) {
cout << "无法打开存档文件进行读取!" << endl;
return false;
}
// 1. 读取当前位置
string locationId;
getline(file, locationId);
Location* newLocation = getLocationById(locationId);
if (!newLocation) {
cout << "无法找到对应的位置数据!" << endl;
return false;
}
currentLocation = newLocation;
// 2. 读取玩家数据
string playerData;
getline(file, playerData);
if (!player->deserialize(playerData, allItems)) {
cout << "玩家数据解析失败!" << endl;
return false;
}
file.close();
cout << "游戏已成功从 " << filename << " 加载" << endl;
return true;
}
};
// Item类方法实现
bool Item::use(Character& player) {
if (!isUsable) {
cout << "这个物品不能使用。" << endl;
return false;
}
if (healAmount > 0) {
player.heal(healAmount);
return true;
}
cout << "使用了" << name << ",但什么也没发生。" << endl;
return false;
}
// Quest类方法实现
void Quest::complete(Character& player) {
if (isCompleted) return;
isCompleted = true;
cout << "任务完成:" << name << "!" << endl;
if (rewardItem) {
player.addItem(rewardItem);
cout << "获得任务奖励:" << rewardItem->getName() << endl;
}
if (rewardGold > 0) {
player.addGold(rewardGold);
cout << "获得任务奖励:" << rewardGold << "金币" << endl;
}
}
bool Quest::checkCompletion(Character& player) {
if (completionCondition == "找到古老的卷轴" &&
player.hasItem("古老的卷轴")) {
return true;
}
if (completionCondition == "消灭森林中的狼人" &&
player.hasFlag("killed_werewolf")) {
return true;
}
if (completionCondition == "帮助村民修理桥梁" &&
player.hasItem("木材") && player.hasFlag("talked_to_blacksmith")) {
return true;
}
return false;
}
// NPC类方法实现
void NPC::talkTo(Character& player) {
cout << "\n[" << name << "]: ";
// 检查是否有条件对话
for (const auto& dialog : conditionalDialogs) {
if (player.hasFlag(dialog.first)) {
cout << dialog.second << endl;
// 如果有任务可以给予且玩家还没接受
if (questToGive) {
bool hasQuest = false;
for (const auto& q : player.getActiveQuests()) {
if (q->getName() == questToGive->getName()) {
hasQuest = true;
break;
}
}
if (!hasQuest) {
cout << "我有一个任务要交给你,你愿意接受吗?(1-接受, 2-拒绝)" << endl;
int choice;
cin >> choice;
if (choice == 1) {
player.addQuest(questToGive);
}
}
}
return;
}
}
// 没有条件对话则使用随机基础对话
if (!dialogs.empty()) {
int idx = rand() % dialogs.size();
cout << dialogs[idx] << endl;
// 提供任务
if (questToGive) {
bool hasQuest = false;
for (const auto& q : player.getActiveQuests()) {
if (q->getName() == questToGive->getName()) {
hasQuest = true;
break;
}
}
if (!hasQuest) {
cout << "我有一个任务要交给你,你愿意接受吗?(1-接受, 2-拒绝)" << endl;
int choice;
cin >> choice;
if (choice == 1) {
player.addQuest(questToGive);
}
}
}
} else {
cout << "你好,旅行者。" << endl;
}
}
void NPC::tradeWith(Character& player) {
if (tradeItems.empty()) {
cout << name << "没有东西可以交易。" << endl;
return;
}
cout << "\n[" << name << "的商店]" << endl;
cout << "1. 返回" << endl;
vector<Item*> items;
for (const auto& item : tradeItems) {
items.push_back(item.second);
}
for (size_t i = 0; i < items.size(); ++i) {
int price = 10 * (i + 1);
cout << i+2 << ". " << items[i]->getName() << " - " << price << "金币" << endl;
cout << " " << items[i]->getDescription() << endl;
}
cout << "请选择要购买的物品:";
int choice;
cin >> choice;
if (choice == 1) return;
choice -= 2;
if (choice >= 0 && choice < (int)items.size()) {
int price = 10 * (choice + 1);
if (player.spendGold(price)) {
player.addItem(items[choice]);
}
} else {
cout << "无效的选择。" << endl;
}
}
// Location类方法实现
string Location::getDescription(Character& player) const {
for (const auto& cond : conditionalDescriptions) {
if (player.hasFlag(cond.first)) {
return cond.second;
}
}
return description;
}
void Location::display(Character& player) {
cout << "\n=====================================" << endl;
cout << "【" << name << "】" << endl;
cout << "=====================================" << endl;
cout << getDescription(player) << endl;
// 显示出口
cout << "\n出口:";
for (const auto& exit : exits) {
cout << exit.first << " ";
}
cout << endl;
// 显示NPC
if (!npcs.empty()) {
cout << "你看到了:";
for (const auto& npc : npcs) {
cout << npc->getName() << " ";
}
cout << endl;
}
// 显示可拾取物品
if (!items.empty()) {
cout << "地上有:";
for (const auto& item : items) {
cout << item->getName() << " ";
}
cout << endl;
}
}
void Location::explore(Character& player) {
// 随机事件
if (!events.empty() && rand() % 5 == 0) { // 20%概率触发随机事件
int idx = rand() % events.size();
cout << "\n【突发事件】" << endl;
cout << events[idx] << endl;
// 处理事件
if (events[idx] == "你发现了一个隐藏的宝箱!") {
cout << "你获得了10枚金币和一瓶治疗药水!" << endl;
player.addGold(10);
player.addItem(new Item("治疗药水", "恢复20点生命值", true, false, 0, 0, 20));
player.setFlag("found_chest");
} else if (events[idx] == "一只饥饿的狼向你扑来!") {
Character wolf("饥饿的狼", 30, 8, 4, 3, 0);
wolf.addItem(new Item("狼皮", "一张厚实的狼皮", false, false));
if (Combat::fight(player, wolf)) {
player.addItem(new Item("狼皮", "一张厚实的狼皮", false, false));
player.addGold(5);
cout << "你获得了狼皮和5枚金币!" << endl;
}
} else if (events[idx] == "你找到了一些草药。") {
cout << "你制作了一瓶治疗药水!" << endl;
player.addItem(new Item("治疗药水", "恢复20点生命值", true, false, 0, 0, 20));
} else if (events[idx] == "你遇到了一只凶猛的狼人!") {
Character werewolf("狼人", 50, 10, 6, 2, 15);
if (Combat::fight(player, werewolf)) {
player.addGold(15);
player.setFlag("killed_werewolf");
cout << "你成功杀死了狼人!" << endl;
}
}
Sleep(2000);
}
}
// 战斗系统实现
namespace Combat {
bool fight(Character& player, Character& enemy) {
cout << "\n=== 战斗开始: " << player.getName() << " VS " << enemy.getName() << " ===" << endl;
while (player.isAlive() && enemy.isAlive()) {
// 玩家回合
cout << "\n你的回合!" << endl;
cout << "1. 攻击" << endl;
cout << "2. 使用物品" << endl;
cout << "3. 尝试逃跑" << endl;
cout << "选择行动:";
int choice;
cin >> choice;
if (choice == 1) {
// 攻击
int hitChance = 70 + (player.getAgility() - enemy.getAgility()) * 2;
hitChance = max(30, min(95, hitChance));
if (rand() % 100 < hitChance) {
int damage = max(1, player.getAttack() - (enemy.getDefense() / 2));
enemy.takeDamage(damage);
cout << "你对" << enemy.getName() << "造成了" << damage << "点伤害!" << endl;
} else {
cout << "你的攻击落空了!" << endl;
}
} else if (choice == 2) {
// 使用物品
player.showInventory();
cout << "选择要使用的物品 (0取消):";
int itemChoice;
cin >> itemChoice;
if (itemChoice > 0 && itemChoice <= (int)player.getInventory().size()) {
vector<Item*> inventory = player.getInventory();
Item* selectedItem = inventory[itemChoice - 1];
if (selectedItem->getIsUsable()) {
selectedItem->use(player);
// 如果是消耗品,使用后移除
if (selectedItem->getHealAmount() > 0) {
player.removeItem(selectedItem->getName());
}
} else {
cout << "这个物品不能使用!" << endl;
}
}
} else if (choice == 3) {
// 尝试逃跑
int escapeChance = 50 + (player.getAgility() - enemy.getAgility()) * 5;
escapeChance = max(20, min(80, escapeChance));
if (rand() % 100 < escapeChance) {
cout << "你成功逃脱了!" << endl;
return false;
} else {
cout << "逃跑失败!" << endl;
}
}
if (!enemy.isAlive()) break;
// 敌人回合
cout << "\n" << enemy.getName() << "的回合!" << endl;
int hitChance = 60 + (enemy.getAgility() - player.getAgility()) * 2;
hitChance = max(20, min(90, hitChance));
if (rand() % 100 < hitChance) {
int damage = max(1, enemy.getAttack() - (player.getDefense() / 2));
player.takeDamage(damage);
cout << enemy.getName() << "对你造成了" << damage << "点伤害!" << endl;
} else {
cout << enemy.getName() << "的攻击落空了!" << endl;
}
if (!player.isAlive()) break;
// 显示状态
cout << "\n战斗状态:" << endl;
cout << player.getName() << " HP: " << player.getHealth() << "/" << player.getMaxHealth() << endl;
cout << enemy.getName() << " HP: " << enemy.getHealth() << endl;
Sleep(1000);
}
if (player.isAlive()) {
cout << "\n你战胜了" << enemy.getName() << "!" << endl;
return true;
} else {
cout << "\n你被" << enemy.getName() << "击败了!" << endl;
return false;
}
}
}
// Game类方法实现
void Game::initializeWorld() {
// 创建物品
allItems.push_back(new Item("铁剑", "一把普通的铁剑", false, false, 5));
allItems.push_back(new Item("钢甲", "一件坚固的钢甲", false, false, 0, 5));
allItems.push_back(new Item("治疗药水", "恢复20点生命值", true, false, 0, 0, 20));
allItems.push_back(new Item("强效治疗药水", "恢复50点生命值", true, false, 0, 0, 50));
allItems.push_back(new Item("古老的卷轴", "记载着秘密的古老卷轴", false, true));
allItems.push_back(new Item("木材", "用于建造的木材", false, false));
allItems.push_back(new Item("金钥匙", "一把金色的钥匙,似乎能打开某个特殊的门", false, true));
// 创建任务
allQuests.push_back(new Quest(
"寻找古老卷轴",
"村长需要你找到一卷古老的卷轴,据说藏在森林深处。",
"找到古老的卷轴",
getItem("钢甲"), 50
));
allQuests.push_back(new Quest(
"消灭狼人",
"铁匠的儿子被狼人抓走了,他请求你消灭那只狼人。",
"消灭森林中的狼人",
getItem("强效治疗药水"), 100
));
allQuests.push_back(new Quest(
"修理桥梁",
"村子通往外界的桥梁坏了,需要木材来修理。",
"帮助村民修理桥梁",
nullptr, 30
));
// 创建位置(带唯一ID用于存档)
Location* village = new Location(
"village",
"宁静村",
"一个宁静的小村庄,村民们过着平静的生活。村口有一个公告板,上面贴着一些任务。"
);
Location* forest = new Location(
"forest",
"黑森林",
"一片茂密的森林,树木高大,阳光很难穿透。林中传来奇怪的叫声。"
);
Location* cave = new Location(
"cave",
"神秘洞穴",
"一个黑暗的洞穴,墙壁上有奇怪的符号。深处似乎有微光。"
);
Location* river = new Location(
"river",
"河流",
"一条湍急的河流,河上有一座破旧的木桥。"
);
Location* mountain = new Location(
"mountain",
"迷雾山脉",
"高耸入云的山脉,常年被迷雾笼罩。山顶似乎有什么东西在闪光。"
);
// 存储所有位置
allLocations.push_back(village);
allLocations.push_back(forest);
allLocations.push_back(cave);
allLocations.push_back(river);
allLocations.push_back(mountain);
// 设置出口
village->addExit("东", forest);
village->addExit("南", river);
forest->addExit("西", village);
forest->addExit("北", cave);
cave->addExit("南", forest);
river->addExit("北", village);
river->addExit("东", mountain);
mountain->addExit("西", river);
// 添加随机事件
village->addEvent("村长召集村民开会,讨论最近的怪事。");
village->addEvent("一个商人经过村庄,出售一些奇特的商品。");
forest->addEvent("你发现了一个隐藏的宝箱!");
forest->addEvent("一只饥饿的狼向你扑来!");
forest->addEvent("你遇到了一只凶猛的狼人!");
cave->addEvent("你在洞穴墙壁上发现了古老的壁画。");
cave->addEvent("洞穴开始震动,一些石头掉了下来!");
river->addEvent("你看到河里有一条巨大的鱼跃出水面。");
river->addEvent("一阵强风吹过,差点把你吹到河里!");
mountain->addEvent("你找到了一些稀有矿石,可以用来制作强力装备。");
mountain->addEvent("山顶的风雪很大,你必须小心前进!");
// 创建NPC
NPC* villageChief = new NPC("村长", "一位白发苍苍的老人,看起来很有智慧。", allQuests[0]);
villageChief->addDialog("欢迎来到宁静村,旅行者。");
villageChief->addDialog("最近森林里不太平,有奇怪的声音传来。");
villageChief->addConditionalDialog("found_scroll", "谢谢你找到卷轴!这对村子很重要。");
NPC* blacksmith = new NPC("铁匠", "一个身材魁梧的男人,手臂上满是肌肉。", allQuests[1]);
blacksmith->addDialog("需要修理武器或防具吗?");
blacksmith->addDialog("我的儿子被森林里的狼人抓走了...");
blacksmith->addConditionalDialog("killed_werewolf", "谢谢你救了我的儿子!我欠你一份人情。");
blacksmith->addTradeItem(getItem("铁剑"), 20);
blacksmith->addTradeItem(getItem("钢甲"), 50);
NPC* farmer = new NPC("农夫", "一个勤劳的农夫,正在田地里干活。", allQuests[2]);
farmer->addDialog("今年的收成不错,希望能卖个好价钱。");
farmer->addDialog("河上的桥坏了,没法去镇上赶集了。");
farmer->addConditionalDialog("bridge_repaired", "谢谢你帮忙修好桥!现在方便多了。");
// 添加NPC到位置
village->addNPC(villageChief);
village->addNPC(blacksmith);
village->addNPC(farmer);
forest->addNPC(new NPC("猎人", "一个经验丰富的猎人,正在森林里打猎。"));
cave->addNPC(new NPC("隐士", "一个住在洞穴里的隐士,似乎知道很多秘密。"));
// 添加物品到位置
forest->addItem(getItem("古老的卷轴"));
forest->addItem(getItem("木材"));
cave->addItem(getItem("金钥匙"));
mountain->addItem(getItem("强效治疗药水"));
// 设置初始位置
currentLocation = village;
}
void Game::checkEndingConditions() {
// 多种结局条件
if (player->hasFlag("found_artifact") && player->hasFlag("saved_village")) {
ending = "good";
gameOver = true;
} else if (player->hasFlag("found_artifact") && !player->hasFlag("saved_village")) {
ending = "selfish";
gameOver = true;
} else if (!player->isAlive()) {
ending = "death";
gameOver = true;
} else if (player->hasFlag("joined_bandits")) {
ending = "bandit";
gameOver = true;
}
}
void Game::showEnding() {
cout << "\n=====================================" << endl;
cout << "【游戏结束】" << endl;
cout << "=====================================" << endl;
if (ending == "good") {
cout << "你找到了传说中的神器,并成功拯救了村庄!" << endl;
cout << "村民们为你举行了盛大的庆祝仪式,你成为了村庄的英雄。" << endl;
cout << "多年后,人们仍然在讲述你的英勇事迹..." << endl;
} else if (ending == "selfish") {
cout << "你找到了传说中的神器,但却无视了村庄的危机。" << endl;
cout << "你带着神器离开了,从此再也没有人见过你。" << endl;
cout << "有人说你成为了强大的巫师,也有人说神器的力量吞噬了你..." << endl;
} else if (ending == "death") {
cout << "你的冒险之旅在这里结束了。" << endl;
cout << "虽然未能完成所有目标,但你的勇气将被铭记。" << endl;
} else if (ending == "bandit") {
cout << "你加入了强盗团伙,成为了他们的首领。" << endl;
cout << "你带领团伙掠夺周边的村庄,变得越来越富有,但也越来越孤独。" << endl;
cout << "最终,你被一支皇家军队剿灭,结束了罪恶的一生..." << endl;
}
cout << "\n你的最终得分:" << (player->getGold() + player->getStrength() * 10 +
player->getAgility() * 10 + player->getIntelligence() * 10) << endl;
cout << "感谢游玩!" << endl;
}
void Game::play() {
cout << "欢迎来到《神秘大陆冒险记》!" << endl;
cout << "在这个世界中,你可以探索各个地点,接受任务,与NPC交流,与怪物战斗。" << endl;
cout << "你的选择将决定故事的结局..." << endl;
Sleep(2000);
while (!gameOver) {
currentLocation->display(*player);
currentLocation->explore(*player);
// 检查任务完成情况
for (auto quest : player->getActiveQuests()) {
if (!quest->getIsCompleted() && quest->checkCompletion(*player)) {
quest->complete(*player);
}
}
// 显示可用操作(新增存档/读档选项)
cout << "\n请选择操作:" << endl;
cout << "1. 移动" << endl;
cout << "2. 与NPC交谈" << endl;
cout << "3. 拾取物品" << endl;
cout << "4. 查看状态" << endl;
cout << "5. 查看背包" << endl;
cout << "6. 查看任务" << endl;
cout << "7. 保存游戏" << endl;
cout << "8. 读取存档" << endl;
cout << "9. 退出游戏" << endl;
cout << "选择:";
int choice;
cin >> choice;
if (choice == 1) {
// 移动
cout << "请输入要前往的方向:";
string direction;
cin >> direction;
Location* newLocation = currentLocation->move(direction);
if (newLocation) {
currentLocation = newLocation;
cout << "你向" << direction << "方向移动。" << endl;
Sleep(1000);
} else {
cout << "不能向那个方向移动!" << endl;
}
} else if (choice == 2) {
// 与NPC交谈
if (currentLocation->getNPCs().empty()) {
cout << "这里没有可以交谈的人。" << endl;
continue;
}
cout << "请选择要交谈的NPC:" << endl;
vector<NPC*> npcs = currentLocation->getNPCs();
for (size_t i = 0; i < npcs.size(); ++i) {
cout << i+1 << ". " << npcs[i]->getName() << endl;
}
cout << npcs.size()+1 << ". 取消" << endl;
cout << "选择:";
int npcChoice;
cin >> npcChoice;
if (npcChoice >= 1 && npcChoice <= (int)npcs.size()) {
npcs[npcChoice-1]->talkTo(*player);
// 特殊对话后标记
if (npcs[npcChoice-1]->getName() == "铁匠") {
player->setFlag("talked_to_blacksmith");
}
// 询问是否交易
cout << "要与" << npcs[npcChoice-1]->getName() << "交易吗?(1-是, 2-否):";
int tradeChoice;
cin >> tradeChoice;
if (tradeChoice == 1) {
npcs[npcChoice-1]->tradeWith(*player);
}
}
} else if (choice == 3) {
// 拾取物品
if (currentLocation->getItems().empty()) {
cout << "这里没有可以拾取的物品。" << endl;
continue;
}
cout << "请选择要拾取的物品:" << endl;
vector<Item*> items = currentLocation->getItems();
for (size_t i = 0; i < items.size(); ++i) {
cout << i+1 << ". " << items[i]->getName() << endl;
}
cout << items.size()+1 << ". 取消" << endl;
cout << "选择:";
int itemChoice;
cin >> itemChoice;
if (itemChoice >= 1 && itemChoice <= (int)items.size()) {
player->addItem(items[itemChoice-1]);
currentLocation->removeItem(items[itemChoice-1]->getName());
// 特殊物品拾取后标记
if (items[itemChoice-1]->getName() == "古老的卷轴") {
player->setFlag("found_scroll");
}
if (items[itemChoice-1]->getName() == "金钥匙") {
player->setFlag("has_golden_key");
}
}
} else if (choice == 4) {
// 查看状态
player->showStatus();
} else if (choice == 5) {
// 查看背包
player->showInventory();
// 可以使用或装备物品
cout << "要使用或装备物品吗?(1-是, 2-否):";
int useChoice;
cin >> useChoice;
if (useChoice == 1 && !player->getInventory().empty()) {
cout << "选择要操作的物品:";
int itemIdx;
cin >> itemIdx;
if (itemIdx >= 1 && itemIdx <= (int)player->getInventory().size()) {
Item* item = player->getInventory()[itemIdx-1];
cout << "1. 使用 2. 装备 3. 取消:";
int action;
cin >> action;
if (action == 1) {
if (item->use(*player)) {
// 消耗品使用后移除
if (item->getHealAmount() > 0) {
player->removeItem(item->getName());
}
}
} else if (action == 2) {
if (item->getAttackBonus() > 0) {
player->equipWeapon(item);
} else if (item->getDefenseBonus() > 0) {
player->equipArmor(item);
} else {
cout << "这件物品不能装备。" << endl;
}
}
}
}
} else if (choice == 6) {
// 查看任务
player->showQuests();
} else if (choice == 7) {
// 保存游戏
string filename;
cout << "请输入存档文件名:";
cin >> filename;
saveGame(filename);
} else if (choice == 8) {
// 读取存档
string filename;
cout << "请输入要读取的存档文件名:";
cin >> filename;
loadGame(filename);
} else if (choice == 9) {
// 退出游戏
cout << "确定要退出游戏吗?(1-是, 2-否):";
int exitChoice;
cin >> exitChoice;
if (exitChoice == 1) {
gameOver = true;
}
} else {
cout << "无效的选择。" << endl;
}
// 检查结局条件
checkEndingConditions();
// 暂停一下,让玩家看清内容
if (!gameOver) {
cout << "\n按回车键继续...";
cin.ignore();
cin.get();
}
}
showEnding();
}
// 主函数
int main() {
srand(time(0));
string playerName;
cout << "欢迎来到《神秘大陆冒险记》!" << endl;
cout << "请输入你的名字:";
cin >> playerName;
Game game(playerName);
game.play();
return 0;
}
迷宫游戏
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
#include <random>
#include <ctime>
#include <conio.h>
#include <windows.h>
#include <iomanip>
#include <map>
#include <string>
#include <sstream>
#include <cstring>
#include <fstream>
#include <algorithm>
#include <chrono>
using namespace std;
// 定义缺失的Windows API常量
#ifndef FOREGROUND_WHITE
#define FOREGROUND_WHITE (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE)
#endif
// 颜色定义
enum Color {
BLACK = 0, BLUE = 1, GREEN = 2, CYAN = 3,
RED = 4, MAGENTA = 5, BROWN = 6, LIGHTGRAY = 7,
DARKGRAY = 8, LIGHTBLUE = 9, LIGHTGREEN = 10, LIGHTCYAN = 11,
LIGHTRED = 12, LIGHTMAGENTA = 13, YELLOW = 14, WHITE = 15
};
// 双缓冲相关全局变量
HANDLE hConsoleOutput;
HANDLE hConsoleInput;
CONSOLE_SCREEN_BUFFER_INFO csbi;
SMALL_RECT windowRect;
CHAR_INFO* buffer;
COORD bufferSize;
// 初始化双缓冲环境
void initDoubleBuffering() {
hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
hConsoleInput = GetStdHandle(STD_INPUT_HANDLE);
GetConsoleScreenBufferInfo(hConsoleOutput, &csbi);
// 设置固定窗口大小以避免闪烁
windowRect.Left = 0;
windowRect.Top = 0;
windowRect.Right = 100; // 宽度
windowRect.Bottom = 40; // 高度
SetConsoleWindowInfo(hConsoleOutput, TRUE, &windowRect);
bufferSize.X = windowRect.Right + 1;
bufferSize.Y = windowRect.Bottom + 1;
// 分配离屏缓冲内存
buffer = new CHAR_INFO[bufferSize.X * bufferSize.Y];
memset(buffer, 0, sizeof(CHAR_INFO) * bufferSize.X * bufferSize.Y);
}
// 释放双缓冲资源
void cleanupDoubleBuffering() {
delete[] buffer;
}
// 绘制字符到离屏缓冲
void drawChar(int x, int y, char ch, WORD color) {
if (x >= 0 && x < bufferSize.X && y >= 0 && y < bufferSize.Y) {
int index = y * bufferSize.X + x;
buffer[index].Char.AsciiChar = ch;
buffer[index].Attributes = color;
}
}
// 绘制字符串到离屏缓冲
void drawString(int x, int y, const string& str, WORD color) {
for (size_t i = 0; i < str.size(); ++i) {
drawChar(x + i, y, str[i], color);
}
}
// 将离屏缓冲内容一次性绘制到屏幕
void swapBuffers() {
COORD destOrigin = {0, 0};
WriteConsoleOutputA(hConsoleOutput, buffer, bufferSize, destOrigin, &windowRect);
}
// 清空离屏缓冲
void clearBuffer() {
for (int i = 0; i < bufferSize.X * bufferSize.Y; ++i) {
buffer[i].Char.AsciiChar = ' ';
buffer[i].Attributes = FOREGROUND_WHITE;
}
}
// 获取颜色属性值
WORD getColorAttribute(int textColor, int bgColor) {
return (bgColor << 4) | textColor;
}
// 隐藏光标
void hideCursor() {
CONSOLE_CURSOR_INFO cursor_info = {1, 0};
SetConsoleCursorInfo(hConsoleOutput, &cursor_info);
}
// 迷宫元素
enum Cell {
WALL = 0, PATH = 1, START = 2, END = 3,
OBSTACLE = 5, TREASURE = 6, TRAP = 7,
HEAL = 8, KEY = 9, DOOR = 10, SHOP = 11
};
// 方向
enum Direction {
UP, DOWN, LEFT, RIGHT, NONE
};
// 道具类型
enum ItemType {
HEALTH_POTION, STRENGTH_POTION, SPEED_POTION,
ARMOR, SWORD, SHIELD, MAP, KEY_ITEM
};
// 敌人类型
enum EnemyType {
SLIME, SKELETON, GOBLIN, BOSS
};
struct Point {
int x, y;
Point(int x = 0, int y = 0) : x(x), y(y) {}
bool operator==(const Point& other) const {
return x == other.x && y == other.y;
}
bool operator!=(const Point& other) const {
return !(*this == other);
}
// 用于存档
void save(ofstream& file) const {
file << x << " " << y << " ";
}
// 用于读档
void load(ifstream& file) {
file >> x >> y;
}
};
struct Item {
ItemType type;
string name;
string description;
int value; // 效果值或价格
char symbol;
Color color;
Item(ItemType t, const string& n, const string& d, int v, char s, Color c)
: type(t), name(n), description(d), value(v), symbol(s), color(c) {}
// 用于存档
void save(ofstream& file) const {
file << type << " " << value << " ";
}
// 用于读档
void load(ifstream& file) {
int t;
file >> t >> value;
type = (ItemType)t;
// 根据类型恢复其他属性
switch (type) {
case HEALTH_POTION:
name = "生命药水";
description = "恢复50点生命值";
symbol = 'H';
color = LIGHTRED;
break;
case STRENGTH_POTION:
name = "力量药水";
description = "暂时增加5点力量";
symbol = 'S';
color = YELLOW;
break;
case SPEED_POTION:
name = "速度药水";
description = "暂时增加3点速度";
symbol = 'P';
color = LIGHTBLUE;
break;
case ARMOR:
name = "铁甲";
description = "增加3点防御";
symbol = 'A';
color = LIGHTGRAY;
break;
case SWORD:
name = "铁剑";
description = "增加5点力量";
symbol = 'W';
color = BROWN;
break;
case SHIELD:
name = "盾牌";
description = "增加5点防御";
symbol = 'D';
color = LIGHTCYAN;
break;
case MAP:
name = "地图";
description = "显示整个迷宫";
symbol = 'M';
color = GREEN;
break;
case KEY_ITEM:
name = "钥匙";
description = "打开门";
symbol = 'K';
color = YELLOW;
break;
}
}
};
struct Enemy {
EnemyType type;
string name;
int health;
int maxHealth;
int damage;
int defense;
int speed;
int expReward;
int goldReward;
char symbol;
Color color;
Point position;
Enemy(EnemyType t, const string& n, int h, int dmg, int def, int spd,
int exp, int gold, char s, Color c, const Point& pos)
: type(t), name(n), health(h), maxHealth(h), damage(dmg), defense(def),
speed(spd), expReward(exp), goldReward(gold), symbol(s), color(c), position(pos) {}
bool isAlive() const { return health > 0; }
void takeDamage(int dmg) {
int actualDmg = max(1, dmg - defense);
health = max(0, health - actualDmg);
}
// 用于存档
void save(ofstream& file) const {
file << type << " " << health << " " << maxHealth << " "
<< damage << " " << defense << " " << speed << " "
<< expReward << " " << goldReward << " ";
position.save(file);
}
// 用于读档
void load(ifstream& file) {
int t;
file >> t >> health >> maxHealth >> damage >> defense >> speed
>> expReward >> goldReward;
type = (EnemyType)t;
position.load(file);
// 根据类型恢复其他属性
switch (type) {
case SLIME:
name = "史莱姆";
symbol = 's';
color = GREEN;
break;
case SKELETON:
name = "骷髅兵";
symbol = 'k';
color = LIGHTGRAY;
break;
case GOBLIN:
name = "哥布林";
symbol = 'g';
color = LIGHTGREEN;
break;
case BOSS:
name = "迷宫守卫";
symbol = 'B';
color = RED;
break;
}
}
};
struct Player {
Point position;
int health;
int maxHealth;
int strength;
int defense;
int speed;
int level;
int exp;
int expToNextLevel;
int gold;
int keys;
map<ItemType, int> items;
bool hasMap;
Player(const Point& pos)
: position(pos), health(100), maxHealth(100), strength(5), defense(2),
speed(3), level(1), exp(0), expToNextLevel(100), gold(0), keys(0), hasMap(false) {}
void levelUp() {
level++;
maxHealth += 20;
health = maxHealth;
strength += 2;
defense += 1;
speed += 1;
exp -= expToNextLevel;
expToNextLevel = (int)(expToNextLevel * 1.5);
}
void addExp(int amount) {
exp += amount;
while (exp >= expToNextLevel) {
levelUp();
}
}
void useItem(ItemType type) {
if (items[type] <= 0) return;
items[type]--;
switch (type) {
case HEALTH_POTION:
health = min(maxHealth, health + 50);
break;
case STRENGTH_POTION:
strength += 5;
break;
case SPEED_POTION:
speed += 3;
break;
case ARMOR:
defense += 3;
break;
case SWORD:
strength += 5;
break;
case SHIELD:
defense += 5;
break;
case MAP:
hasMap = true;
break;
case KEY_ITEM:
keys++;
break;
}
}
// 用于存档
void save(ofstream& file) const {
position.save(file);
file << health << " " << maxHealth << " " << strength << " "
<< defense << " " << speed << " " << level << " "
<< exp << " " << expToNextLevel << " " << gold << " "
<< keys << " " << (hasMap ? 1 : 0) << " " << items.size() << " ";
for (const auto& pair : items) {
file << pair.first << " " << pair.second << " ";
}
}
// 用于读档
void load(ifstream& file) {
position.load(file);
file >> health >> maxHealth >> strength >> defense >> speed >> level
>> exp >> expToNextLevel >> gold >> keys;
int hasMapInt;
file >> hasMapInt;
hasMap = hasMapInt == 1;
int itemCount;
file >> itemCount;
items.clear();
for (int i = 0; i < itemCount; i++) {
int type, count;
file >> type >> count;
items[(ItemType)type] = count;
}
}
};
struct Quest {
string name;
string description;
bool completed;
int expReward;
int goldReward;
Item* itemReward;
Quest(const string& n, const string& d, int exp, int gold, Item* item = nullptr)
: name(n), description(d), completed(false), expReward(exp), goldReward(gold), itemReward(item) {}
// 用于存档
void save(ofstream& file) const {
file << completed << " ";
// 其他属性可以从初始化中恢复,不需要保存
}
// 用于读档
void load(ifstream& file) {
file >> completed;
}
};
class MazeAdventure {
private:
vector<vector<int>> maze;
vector<Enemy> enemies;
vector<Item> itemsList;
vector<Quest> quests;
Player player;
Point start;
Point end;
int width, height;
int floor; // 当前楼层
bool gameOver;
bool floorCompleted;
time_t startTime;
mt19937 rng;
vector<Item> shopItems;
// 存档文件版本号,用于兼容性检查 - 改为静态常量
static const int SAVE_VERSION;
public:
MazeAdventure(int w = 31, int h = 17) : width(w), height(h), floor(1),
gameOver(false), floorCompleted(false),
player(Point(1, 1)) {
if (width % 2 == 0) width++;
if (height % 2 == 0) height++;
rng.seed(time(nullptr));
initializeItems();
initializeQuests();
generateFloor();
startTime = time(nullptr);
}
void initializeItems() {
itemsList.emplace_back(HEALTH_POTION, "生命药水", "恢复50点生命值", 50, 'H', LIGHTRED);
itemsList.emplace_back(STRENGTH_POTION, "力量药水", "暂时增加5点力量", 5, 'S', YELLOW);
itemsList.emplace_back(SPEED_POTION, "速度药水", "暂时增加3点速度", 5, 'P', LIGHTBLUE);
itemsList.emplace_back(ARMOR, "铁甲", "增加3点防御", 3, 'A', LIGHTGRAY);
itemsList.emplace_back(SWORD, "铁剑", "增加5点力量", 5, 'W', BROWN);
itemsList.emplace_back(SHIELD, "盾牌", "增加5点防御", 5, 'D', LIGHTCYAN);
itemsList.emplace_back(MAP, "地图", "显示整个迷宫", 1, 'M', GREEN);
itemsList.emplace_back(KEY_ITEM, "钥匙", "打开门", 1, 'K', YELLOW);
shopItems.emplace_back(HEALTH_POTION, "生命药水", "恢复50点生命值", 50, 'H', LIGHTRED);
shopItems.emplace_back(STRENGTH_POTION, "力量药水", "暂时增加5点力量", 75, 'S', YELLOW);
shopItems.emplace_back(SPEED_POTION, "速度药水", "暂时增加3点速度", 60, 'P', LIGHTBLUE);
shopItems.emplace_back(KEY_ITEM, "钥匙", "打开门", 100, 'K', YELLOW);
}
void initializeQuests() {
quests.emplace_back("收集宝藏", "收集5个宝藏", 100, 50);
quests.emplace_back("消灭敌人", "击败3个敌人", 150, 75);
quests.emplace_back("找到钥匙", "找到1把钥匙", 50, 25, &itemsList[6]);
}
void generateFloor() {
enemies.clear();
maze.assign(height, vector<int>(width, WALL));
uniform_int_distribution<int> distX(1, (width - 1) / 2);
uniform_int_distribution<int> distY(1, (height - 1) / 2);
uniform_int_distribution<int> distDir(0, 3);
start.x = distX(rng) * 2 - 1;
start.y = distY(rng) * 2 - 1;
maze[start.y][start.x] = START;
player.position = start;
stack<Point> s;
s.push(start);
int dx[] = {2, -2, 0, 0};
int dy[] = {0, 0, 2, -2};
while (!s.empty()) {
Point current = s.top();
s.pop();
vector<int> dirs = {0, 1, 2, 3};
for (int i = 0; i < 4; ++i) {
swap(dirs[i], dirs[distDir(rng)]);
}
for (int dir : dirs) {
int nx = current.x + dx[dir];
int ny = current.y + dy[dir];
if (nx > 0 && nx < width && ny > 0 && ny < height && maze[ny][nx] == WALL) {
maze[ny][nx] = PATH;
maze[current.y + dy[dir]/2][current.x + dx[dir]/2] = PATH;
s.push(current);
s.push(Point(nx, ny));
}
}
}
do {
end.x = distX(rng) * 2 - 1;
end.y = distY(rng) * 2 - 1;
} while ((end.x == start.x && end.y == start.y) || maze[end.y][end.x] != PATH);
maze[end.y][end.x] = END;
addFloorFeatures();
addEnemies();
addShop();
floorCompleted = false;
}
void addShop() {
uniform_int_distribution<int> distX(1, width - 2);
uniform_int_distribution<int> distY(1, height - 2);
int x, y;
do {
x = distX(rng);
y = distY(rng);
} while (maze[y][x] != PATH || (x == start.x && y == start.y) || (x == end.x && y == end.y));
maze[y][x] = SHOP;
}
void addFloorFeatures() {
uniform_int_distribution<int> distX(1, width - 2);
uniform_int_distribution<int> distY(1, height - 2);
uniform_int_distribution<int> distType(0, 100);
int featureCount = floor * 10 + 10;
int doorCount = floor + 1;
for (int i = 0; i < doorCount; ++i) {
int x, y;
do {
x = distX(rng);
y = distY(rng);
} while (maze[y][x] != PATH || (x == start.x && y == start.y) || (x == end.x && y == end.y));
maze[y][x] = DOOR;
do {
x = distX(rng);
y = distY(rng);
} while (maze[y][x] != PATH || (x == start.x && y == start.y) || (x == end.x && y == end.y));
maze[y][x] = KEY;
}
for (int i = 0; i < featureCount; ++i) {
int x, y;
do {
x = distX(rng);
y = distY(rng);
} while (maze[y][x] != PATH || (x == start.x && y == start.y) || (x == end.x && y == end.y));
int rand = distType(rng);
if (rand < 30) {
maze[y][x] = TREASURE;
} else if (rand < 45) {
maze[y][x] = TRAP;
} else if (rand < 60) {
maze[y][x] = HEAL;
} else if (rand < 70) {
maze[y][x] = OBSTACLE;
}
}
}
void addEnemies() {
uniform_int_distribution<int> distX(1, width - 2);
uniform_int_distribution<int> distY(1, height - 2);
uniform_int_distribution<int> distEnemy(0, 99);
int enemyCount = floor * 3 + 2;
addBossEnemy();
for (int i = 0; i < enemyCount; ++i) {
int x, y;
do {
x = distX(rng);
y = distY(rng);
} while (maze[y][x] != PATH || (x == start.x && y == start.y) || (x == end.x && y == end.y));
int rand = distEnemy(rng);
if (rand < 40) {
enemies.emplace_back(SLIME, "史莱姆", 20 + floor * 5, 5 + floor * 2,
1 + floor, 2, 10 + floor * 5, 5 + floor * 2,
's', GREEN, Point(x, y));
} else if (rand < 70) {
enemies.emplace_back(SKELETON, "骷髅兵", 30 + floor * 7, 8 + floor * 3,
2 + floor * 2, 3, 15 + floor * 7, 8 + floor * 3,
'k', LIGHTGRAY, Point(x, y));
} else {
enemies.emplace_back(GOBLIN, "哥布林", 25 + floor * 6, 6 + floor * 2,
1 + floor, 4, 12 + floor * 6, 6 + floor * 2,
'g', LIGHTGREEN, Point(x, y));
}
}
}
void addBossEnemy() {
uniform_int_distribution<int> distX(1, width - 2);
uniform_int_distribution<int> distY(1, height - 2);
int x, y;
do {
x = distX(rng);
y = distY(rng);
} while (maze[y][x] != PATH || (x == start.x && y == start.y) || (x == end.x && y == end.y));
enemies.emplace_back(BOSS, "迷宫守卫", 100 + floor * 30, 15 + floor * 5,
5 + floor * 3, 2, 100 + floor * 50, 50 + floor * 20,
'B', RED, Point(x, y));
}
// 使用双缓冲绘制,消除闪烁
void display() {
// 清空离屏缓冲
clearBuffer();
// 绘制标题和信息
WORD yellowBlack = getColorAttribute(YELLOW, BLACK);
WORD whiteBlack = getColorAttribute(WHITE, BLACK);
drawString(0, 0, "===== 迷宫探险 | 第 " + to_string(floor) + " 层 =====", yellowBlack);
drawString(0, 1, "等级: " + to_string(player.level) + " | 经验: " + to_string(player.exp) + "/" + to_string(player.expToNextLevel), whiteBlack);
drawString(0, 2, "生命: " + to_string(player.health) + "/" + to_string(player.maxHealth) + " | 力量: " + to_string(player.strength), whiteBlack);
drawString(0, 3, "防御: " + to_string(player.defense) + " | 速度: " + to_string(player.speed), whiteBlack);
drawString(0, 4, "金币: " + to_string(player.gold) + " | 钥匙: " + to_string(player.keys), whiteBlack);
drawString(0, 5, "时间: " + to_string((int)(difftime(time(nullptr), startTime))) + "秒", whiteBlack);
drawString(0, 6, "快捷键: S-保存 L-加载 I-物品 ESC-菜单", whiteBlack);
drawString(0, 7, "=========================================", whiteBlack);
// 显示小地图(如果有地图)
if (player.hasMap) {
WORD cyanBlack = getColorAttribute(CYAN, BLACK);
drawString(0, 8, "小地图: ", cyanBlack);
for (int y = 0; y < 5; y++) {
for (int x = 0; x < 10; x++) {
int mx = start.x - 5 + x;
int my = start.y - 2 + y;
char c = ' ';
if (mx >= 0 && mx < width && my >= 0 && my < height) {
if (maze[my][mx] == WALL) c = '#';
else if (mx == end.x && my == end.y) c = 'E';
else if (mx == start.x && my == start.y) c = 'S';
else if (mx == player.position.x && my == player.position.y) c = 'P';
}
drawChar(5 + x, 8, c, cyanBlack);
}
}
drawString(0, 9, "=========================================", cyanBlack);
}
// 绘制迷宫
int mazeStartY = player.hasMap ? 10 : 8;
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
bool isEnemy = false;
// 检查是否有敌人
for (const auto& enemy : enemies) {
if (enemy.position.x == x && enemy.position.y == y && enemy.isAlive()) {
drawChar(x * 2, mazeStartY + y, enemy.symbol, getColorAttribute(enemy.color, BLACK));
drawChar(x * 2 + 1, mazeStartY + y, ' ', getColorAttribute(enemy.color, BLACK));
isEnemy = true;
break;
}
}
if (isEnemy) continue;
if (x == player.position.x && y == player.position.y) {
// 玩家:白字红底
drawChar(x * 2, mazeStartY + y, 'P', getColorAttribute(WHITE, RED));
drawChar(x * 2 + 1, mazeStartY + y, ' ', getColorAttribute(WHITE, RED));
} else {
switch (maze[y][x]) {
case WALL:
// 使用单字符替代多字符常量
drawChar(x * 2, mazeStartY + y, '#', getColorAttribute(DARKGRAY, BLACK));
drawChar(x * 2 + 1, mazeStartY + y, '#', getColorAttribute(DARKGRAY, BLACK));
break;
case PATH:
drawChar(x * 2, mazeStartY + y, ' ', getColorAttribute(LIGHTGRAY, BLACK));
drawChar(x * 2 + 1, mazeStartY + y, ' ', getColorAttribute(LIGHTGRAY, BLACK));
break;
case START:
drawChar(x * 2, mazeStartY + y, 'S', getColorAttribute(GREEN, BLACK));
drawChar(x * 2 + 1, mazeStartY + y, ' ', getColorAttribute(GREEN, BLACK));
break;
case END:
drawChar(x * 2, mazeStartY + y, 'E', getColorAttribute(LIGHTGREEN, BLACK));
drawChar(x * 2 + 1, mazeStartY + y, ' ', getColorAttribute(LIGHTGREEN, BLACK));
break;
case OBSTACLE:
drawChar(x * 2, mazeStartY + y, '?', getColorAttribute(RED, BLACK));
drawChar(x * 2 + 1, mazeStartY + y, ' ', getColorAttribute(RED, BLACK));
break;
case TREASURE:
drawChar(x * 2, mazeStartY + y, '$', getColorAttribute(YELLOW, BLACK));
drawChar(x * 2 + 1, mazeStartY + y, ' ', getColorAttribute(YELLOW, BLACK));
break;
case TRAP:
drawChar(x * 2, mazeStartY + y, '?', getColorAttribute(MAGENTA, BLACK));
drawChar(x * 2 + 1, mazeStartY + y, ' ', getColorAttribute(MAGENTA, BLACK));
break;
case HEAL:
drawChar(x * 2, mazeStartY + y, '+', getColorAttribute(LIGHTRED, BLACK));
drawChar(x * 2 + 1, mazeStartY + y, ' ', getColorAttribute(LIGHTRED, BLACK));
break;
case KEY:
drawChar(x * 2, mazeStartY + y, 'K', getColorAttribute(YELLOW, BLACK));
drawChar(x * 2 + 1, mazeStartY + y, ' ', getColorAttribute(YELLOW, BLACK));
break;
case DOOR:
drawChar(x * 2, mazeStartY + y, 'D', getColorAttribute(BROWN, BLACK));
drawChar(x * 2 + 1, mazeStartY + y, ' ', getColorAttribute(BROWN, BLACK));
break;
case SHOP:
drawChar(x * 2, mazeStartY + y, 'O', getColorAttribute(LIGHTBLUE, BLACK));
drawChar(x * 2 + 1, mazeStartY + y, ' ', getColorAttribute(LIGHTBLUE, BLACK));
break;
default:
drawChar(x * 2, mazeStartY + y, ' ', whiteBlack);
drawChar(x * 2 + 1, mazeStartY + y, ' ', whiteBlack);
}
}
}
}
// 显示任务
int infoStartY = mazeStartY + height + 1;
WORD cyanBlack = getColorAttribute(CYAN, BLACK);
drawString(0, infoStartY, "任务:", cyanBlack);
for (size_t i = 0; i < quests.size(); ++i) {
string status = quests[i].completed ? "[完成] " : "[进行] ";
drawString(0, infoStartY + 1 + i, status + quests[i].name, cyanBlack);
}
// 显示物品
int itemStartY = infoStartY + 1 + quests.size() + 1;
WORD greenBlack = getColorAttribute(GREEN, BLACK);
drawString(0, itemStartY, "物品:", greenBlack);
int itemCount = 0;
for (const auto& item : itemsList) {
if (player.items[item.type] > 0) {
string itemStr = string(1, item.symbol) + " " + item.name + " x" + to_string(player.items[item.type]);
drawString(0, itemStartY + 1 + itemCount, itemStr, greenBlack);
itemCount++;
}
}
// 操作提示
drawString(0, itemStartY + 1 + itemCount + 1, "方向键移动,I使用物品,Q退出游戏", whiteBlack);
// 一次性将缓冲内容绘制到屏幕
swapBuffers();
}
bool movePlayer(Direction dir) {
int dx = 0, dy = 0;
switch (dir) {
case UP: dy = -1; break;
case DOWN: dy = 1; break;
case LEFT: dx = -1; break;
case RIGHT: dx = 1; break;
default: return false;
}
int newX = player.position.x + dx;
int newY = player.position.y + dy;
if (newX < 0 || newX >= width || newY < 0 || newY >= height) {
return false;
}
if (maze[newY][newX] == DOOR) {
if (player.keys <= 0) return false;
player.keys--;
maze[newY][newX] = PATH;
}
if (maze[newY][newX] == WALL || maze[newY][newX] == OBSTACLE) {
return false;
}
if (maze[newY][newX] == SHOP) {
enterShop();
return false;
}
if (maze[newY][newX] == TREASURE) {
player.gold += 10 * floor;
player.addExp(5 * floor);
maze[newY][newX] = PATH;
for (auto& quest : quests) {
if (quest.name == "收集宝藏" && player.gold >= 50 * floor) {
quest.completed = true;
completeQuest(quest);
}
}
} else if (maze[newY][newX] == TRAP) {
int damage = 10 + floor * 5;
player.health = max(0, player.health - damage);
maze[newY][newX] = PATH;
if (player.health <= 0) {
gameOver = true;
}
} else if (maze[newY][newX] == HEAL) {
player.health = min(player.maxHealth, player.health + 30 + floor * 10);
maze[newY][newX] = PATH;
} else if (maze[newY][newX] == KEY) {
player.keys++;
maze[newY][newX] = PATH;
for (auto& quest : quests) {
if (quest.name == "找到钥匙" && player.keys >= 1) {
quest.completed = true;
completeQuest(quest);
}
}
} else if (maze[newY][newX] == END) {
int timeTaken = difftime(time(nullptr), startTime);
player.addExp(200 * floor - (timeTaken * 2));
player.gold += 100 * floor;
floorCompleted = true;
}
for (auto& enemy : enemies) {
if (enemy.position.x == newX && enemy.position.y == newY && enemy.isAlive()) {
battle(&enemy);
if (gameOver) return false;
if (!enemy.isAlive()) {
player.position.x = newX;
player.position.y = newY;
}
return true;
}
}
player.position.x = newX;
player.position.y = newY;
return true;
}
void battle(Enemy* enemy) {
clearBuffer();
WORD redBlack = getColorAttribute(RED, BLACK);
WORD whiteBlack = getColorAttribute(WHITE, BLACK);
WORD greenBlack = getColorAttribute(GREEN, BLACK);
drawString(10, 10, "遭遇了" + enemy->name + "!", redBlack);
swapBuffers();
Sleep(500);
while (enemy->isAlive() && player.health > 0) {
clearBuffer();
// 绘制战斗信息
drawString(10, 8, "=== 战斗 ===", redBlack);
drawString(10, 10, "你的状态: " + to_string(player.health) + "/" + to_string(player.maxHealth), whiteBlack);
drawString(10, 11, enemy->name + "状态: " + to_string(enemy->health) + "/" + to_string(enemy->maxHealth), whiteBlack);
// 战斗逻辑:速度快的先攻击
bool playerAttacksFirst = player.speed >= enemy->speed;
string log;
if (playerAttacksFirst) {
// 玩家攻击
int baseDamage = player.strength * 2;
int actualDamage = max(1, baseDamage - enemy->defense / 2);
enemy->takeDamage(actualDamage);
log = "你对" + enemy->name + "造成了" + to_string(actualDamage) + "点伤害!";
drawString(10, 13, log, greenBlack);
if (!enemy->isAlive()) {
drawString(10, 15, enemy->name + "被击败了!", greenBlack);
swapBuffers();
Sleep(1000);
break;
}
}
// 敌人攻击
int baseEnemyDamage = enemy->damage;
int actualEnemyDamage = max(1, baseEnemyDamage - player.defense / 3);
player.health = max(0, player.health - actualEnemyDamage);
log = enemy->name + "对你造成了" + to_string(actualEnemyDamage) + "点伤害!";
drawString(10, 14, log, redBlack);
if (!playerAttacksFirst && !enemy->isAlive()) {
drawString(10, 15, enemy->name + "被击败了!", greenBlack);
swapBuffers();
Sleep(1000);
break;
}
drawString(10, 16, "按任意键继续战斗...", whiteBlack);
swapBuffers();
_getch();
}
if (enemy->isAlive()) {
// 玩家战败
gameOver = true;
} else {
clearBuffer();
drawString(10, 10, "你击败了" + enemy->name + "!", greenBlack);
drawString(10, 11, "获得了" + to_string(enemy->expReward) + "点经验和" + to_string(enemy->goldReward) + "金币!", greenBlack);
player.addExp(enemy->expReward);
player.gold += enemy->goldReward;
static int enemiesDefeated = 0;
enemiesDefeated++;
for (auto& quest : quests) {
if (quest.name == "消灭敌人" && enemiesDefeated >= 3) {
quest.completed = true;
completeQuest(quest);
}
}
drawString(10, 13, "按任意键继续...", whiteBlack);
swapBuffers();
_getch();
}
}
void completeQuest(Quest& quest) {
clearBuffer();
WORD yellowBlack = getColorAttribute(YELLOW, BLACK);
WORD whiteBlack = getColorAttribute(WHITE, BLACK);
drawString(10, 10, "完成任务: " + quest.name + "!", yellowBlack);
string reward = "获得奖励: " + to_string(quest.expReward) + "经验, " + to_string(quest.goldReward) + "金币";
if (quest.itemReward) {
reward += ", 1个" + quest.itemReward->name;
player.items[quest.itemReward->type]++;
}
drawString(10, 11, reward, yellowBlack);
player.addExp(quest.expReward);
player.gold += quest.goldReward;
drawString(10, 13, "按任意键继续...", whiteBlack);
swapBuffers();
_getch();
}
void enterShop() {
clearBuffer();
WORD blueBlack = getColorAttribute(LIGHTBLUE, BLACK);
WORD whiteBlack = getColorAttribute(WHITE, BLACK);
WORD greenBlack = getColorAttribute(GREEN, BLACK);
WORD redBlack = getColorAttribute(RED, BLACK);
drawString(10, 8, "===== 商店 =====", blueBlack);
drawString(10, 10, "你的金币: " + to_string(player.gold), whiteBlack);
drawString(10, 11, "0. 离开商店", whiteBlack);
for (size_t i = 0; i < shopItems.size(); ++i) {
string itemStr = to_string(i + 1) + ". " + shopItems[i].name +
" - " + to_string(shopItems[i].value) + "金币 - " + shopItems[i].description;
drawString(10, 12 + i, itemStr, whiteBlack);
}
drawString(10, 12 + shopItems.size() + 1, "请选择购买的物品: ", whiteBlack);
swapBuffers();
int choice;
cin >> choice;
cin.ignore(); // 清除输入缓冲区
clearBuffer();
drawString(10, 8, "===== 商店 =====", blueBlack);
if (choice >= 1 && choice <= (int)shopItems.size()) {
Item item = shopItems[choice - 1];
if (player.gold >= item.value) {
player.gold -= item.value;
player.items[item.type]++;
drawString(10, 10, "购买了" + item.name + "!", greenBlack);
} else {
drawString(10, 10, "金币不足!", redBlack);
}
}
drawString(10, 12, "按任意键离开商店...", whiteBlack);
swapBuffers();
_getch();
}
void useItemMenu() {
clearBuffer();
WORD greenBlack = getColorAttribute(GREEN, BLACK);
WORD whiteBlack = getColorAttribute(WHITE, BLACK);
drawString(10, 8, "===== 物品菜单 =====", greenBlack);
drawString(10, 10, "0. 关闭菜单", whiteBlack);
vector<Item> availableItems;
for (const auto& item : itemsList) {
if (player.items[item.type] > 0) {
availableItems.push_back(item);
}
}
for (size_t i = 0; i < availableItems.size(); ++i) {
string itemStr = to_string(i + 1) + ". " + availableItems[i].name +
" x" + to_string(player.items[availableItems[i].type]) +
" - " + availableItems[i].description;
drawString(10, 11 + i, itemStr, whiteBlack);
}
if (availableItems.empty()) {
drawString(10, 11, "没有可用物品!", whiteBlack);
} else {
drawString(10, 11 + availableItems.size() + 1, "请选择使用的物品: ", whiteBlack);
swapBuffers();
int choice;
cin >> choice;
cin.ignore(); // 清除输入缓冲区
clearBuffer();
drawString(10, 8, "===== 物品菜单 =====", greenBlack);
if (choice >= 1 && choice <= (int)availableItems.size()) {
player.useItem(availableItems[choice - 1].type);
drawString(10, 10, "使用了" + availableItems[choice - 1].name + "!", greenBlack);
}
}
drawString(10, 12 + availableItems.size(), "按任意键继续...", whiteBlack);
swapBuffers();
_getch();
}
void moveEnemies() {
uniform_int_distribution<int> distDir(0, 3);
for (auto& enemy : enemies) {
if (!enemy.isAlive()) continue;
if (enemy.type == BOSS) {
Direction dir = NONE;
if (enemy.position.x < player.position.x) dir = RIGHT;
else if (enemy.position.x > player.position.x) dir = LEFT;
else if (enemy.position.y < player.position.y) dir = DOWN;
else if (enemy.position.y > player.position.y) dir = UP;
if (dir != NONE) {
int dx = 0, dy = 0;
switch (dir) {
case UP: dy = -1; break;
case DOWN: dy = 1; break;
case LEFT: dx = -1; break;
case RIGHT: dx = 1; break;
default: break;
}
int newX = enemy.position.x + dx;
int newY = enemy.position.y + dy;
if (newX >= 0 && newX < width && newY >= 0 && newY < height &&
maze[newY][newX] != WALL && maze[newY][newX] != OBSTACLE &&
!(newX == start.x && newY == start.y)) {
bool hasEnemy = false;
for (const auto& other : enemies) {
if (&other != &enemy && other.isAlive() &&
other.position.x == newX && other.position.y == newY) {
hasEnemy = true;
break;
}
}
if (!hasEnemy) {
if (newX == player.position.x && newY == player.position.y) {
battle(&enemy);
return;
}
enemy.position.x = newX;
enemy.position.y = newY;
}
}
}
} else {
if (distDir(rng) < 2) {
Direction dir = (Direction)distDir(rng);
int dx = 0, dy = 0;
switch (dir) {
case UP: dy = -1; break;
case DOWN: dy = 1; break;
case LEFT: dx = -1; break;
case RIGHT: dx = 1; break;
default: break;
}
int newX = enemy.position.x + dx;
int newY = enemy.position.y + dy;
if (newX >= 0 && newX < width && newY >= 0 && newY < height &&
maze[newY][newX] != WALL && maze[newY][newX] != OBSTACLE &&
!(newX == start.x && newY == start.y)) {
bool hasEnemy = false;
for (const auto& other : enemies) {
if (&other != &enemy && other.isAlive() &&
other.position.x == newX && other.position.y == newY) {
hasEnemy = true;
break;
}
}
if (!hasEnemy) {
if (newX == player.position.x && newY == player.position.y) {
battle(&enemy);
return;
}
enemy.position.x = newX;
enemy.position.y = newY;
}
}
}
}
}
}
void handleInput() {
if (_kbhit()) {
int key = _getch();
if (key == 224) { // 方向键前缀
key = _getch();
switch (key) {
case 72: movePlayer(UP); break;
case 80: movePlayer(DOWN); break;
case 75: movePlayer(LEFT); break;
case 77: movePlayer(RIGHT); break;
}
} else if (key == 'q' || key == 'Q') {
gameOver = true;
} else if (key == 'i' || key == 'I') {
useItemMenu();
} else if (key == 's' || key == 'S') { // 保存游戏
saveGame(0); // 默认保存到第一个存档位
} else if (key == 'l' || key == 'L') { // 加载游戏
loadGame(0); // 默认加载第一个存档位
} else if (key == 27) { // ESC键打开菜单
showGameMenu();
}
}
}
void showGameMenu() {
clearBuffer();
WORD yellowBlack = getColorAttribute(YELLOW, BLACK);
WORD whiteBlack = getColorAttribute(WHITE, BLACK);
drawString(10, 8, "===== 游戏菜单 =====", yellowBlack);
drawString(10, 10, "1. 继续游戏", whiteBlack);
drawString(10, 11, "2. 保存游戏", whiteBlack);
drawString(10, 12, "3. 读取存档", whiteBlack);
drawString(10, 13, "4. 重新开始", whiteBlack);
drawString(10, 14, "5. 退出游戏", whiteBlack);
drawString(10, 16, "请选择: ", whiteBlack);
swapBuffers();
int choice;
cin >> choice;
cin.ignore();
switch (choice) {
case 1: // 继续游戏
break;
case 2: // 保存游戏
showSaveMenu();
break;
case 3: // 读取存档
showLoadMenu();
break;
case 4: // 重新开始
*this = MazeAdventure(width, height);
break;
case 5: // 退出游戏
gameOver = true;
break;
}
}
void showSaveMenu() {
clearBuffer();
WORD yellowBlack = getColorAttribute(YELLOW, BLACK);
WORD whiteBlack = getColorAttribute(WHITE, BLACK);
drawString(10, 8, "===== 保存游戏 =====", yellowBlack);
drawString(10, 10, "1. 存档位 1", whiteBlack);
drawString(10, 11, "2. 存档位 2", whiteBlack);
drawString(10, 12, "3. 存档位 3", whiteBlack);
drawString(10, 13, "4. 返回", whiteBlack);
drawString(10, 15, "请选择存档位: ", whiteBlack);
swapBuffers();
int choice;
cin >> choice;
cin.ignore();
if (choice >= 1 && choice <= 3) {
if (saveGame(choice - 1)) {
clearBuffer();
drawString(10, 10, "游戏保存成功!", getColorAttribute(GREEN, BLACK));
drawString(10, 12, "按任意键继续...", whiteBlack);
swapBuffers();
_getch();
} else {
clearBuffer();
drawString(10, 10, "保存失败!", getColorAttribute(RED, BLACK));
drawString(10, 12, "按任意键继续...", whiteBlack);
swapBuffers();
_getch();
}
}
}
void showLoadMenu() {
clearBuffer();
WORD yellowBlack = getColorAttribute(YELLOW, BLACK);
WORD whiteBlack = getColorAttribute(WHITE, BLACK);
drawString(10, 8, "===== 读取存档 =====", yellowBlack);
drawString(10, 10, "1. 存档位 1", whiteBlack);
drawString(10, 11, "2. 存档位 2", whiteBlack);
drawString(10, 12, "3. 存档位 3", whiteBlack);
drawString(10, 13, "4. 返回", whiteBlack);
drawString(10, 15, "请选择存档位: ", whiteBlack);
swapBuffers();
int choice;
cin >> choice;
cin.ignore();
if (choice >= 1 && choice <= 3) {
if (loadGame(choice - 1)) {
clearBuffer();
drawString(10, 10, "游戏加载成功!", getColorAttribute(GREEN, BLACK));
drawString(10, 12, "按任意键继续...", whiteBlack);
swapBuffers();
_getch();
} else {
clearBuffer();
drawString(10, 10, "加载失败或存档不存在!", getColorAttribute(RED, BLACK));
drawString(10, 12, "按任意键继续...", whiteBlack);
swapBuffers();
_getch();
}
}
}
// 保存游戏到指定存档位(0-2)
bool saveGame(int slot) {
if (slot < 0 || slot > 2) return false;
string filename = "save" + to_string(slot) + ".dat";
ofstream file(filename, ios::binary);
if (!file.is_open()) return false;
// 保存版本号,用于未来兼容性
file << SAVE_VERSION << " ";
// 保存基本游戏状态
file << floor << " " << width << " " << height << " "
<< gameOver << " " << floorCompleted << " ";
// 保存时间信息
auto now = chrono::system_clock::now();
time_t now_time = chrono::system_clock::to_time_t(now);
file << now_time << " ";
// 保存玩家信息
player.save(file);
// 保存起点和终点
start.save(file);
end.save(file);
// 保存迷宫数据
file << maze.size() << " " << maze[0].size() << " ";
for (const auto& row : maze) {
for (int cell : row) {
file << cell << " ";
}
}
// 保存敌人信息
file << enemies.size() << " ";
for (const auto& enemy : enemies) {
enemy.save(file);
}
// 保存任务状态
file << quests.size() << " ";
for (const auto& quest : quests) {
quest.save(file);
}
return true;
}
// 从指定存档位加载游戏(0-2)
bool loadGame(int slot) {
if (slot < 0 || slot > 2) return false;
string filename = "save" + to_string(slot) + ".dat";
ifstream file(filename, ios::binary);
if (!file.is_open()) return false;
// 检查版本号
int version;
file >> version;
if (version != SAVE_VERSION) return false;
// 加载基本游戏状态
file >> floor >> width >> height >> gameOver >> floorCompleted;
// 加载时间信息(仅用于显示,不影响游戏逻辑)
time_t save_time;
file >> save_time;
// 加载玩家信息
player.load(file);
// 加载起点和终点
start.load(file);
end.load(file);
// 加载迷宫数据
int rows, cols;
file >> rows >> cols;
maze.resize(rows, vector<int>(cols));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
file >> maze[i][j];
}
}
// 加载敌人信息
int enemyCount;
file >> enemyCount;
enemies.clear();
for (int i = 0; i < enemyCount; ++i) {
Enemy temp(SLIME, "", 0, 0, 0, 0, 0, 0, ' ', BLACK, Point());
temp.load(file);
enemies.push_back(temp);
}
// 重新初始化任务并加载状态
initializeQuests();
int questCount;
file >> questCount;
for (int i = 0; i < questCount && i < (int)quests.size(); ++i) {
quests[i].load(file);
}
// 重置开始时间(从加载时开始计算)
startTime = time(nullptr);
return true;
}
void nextFloor() {
floor++;
if (floor % 5 == 0) {
width += 6;
height += 4;
if (width % 2 == 0) width++;
if (height % 2 == 0) height++;
}
for (auto& quest : quests) {
if (quest.name == "收集宝藏" || quest.name == "消灭敌人") {
quest.completed = false;
}
}
generateFloor();
startTime = time(nullptr);
}
void showFloorComplete() {
clearBuffer();
WORD greenBlack = getColorAttribute(GREEN, BLACK);
WORD whiteBlack = getColorAttribute(WHITE, BLACK);
drawString(10, 10, "恭喜!完成第 " + to_string(floor) + " 层!", greenBlack);
drawString(10, 11, "得分: " + to_string(player.exp) + " | 用时: " + to_string((int)difftime(time(nullptr), startTime)) + "秒", greenBlack);
drawString(10, 13, "按任意键进入下一层...", whiteBlack);
swapBuffers();
_getch();
}
void showGameOver() {
clearBuffer();
WORD redBlack = getColorAttribute(RED, BLACK);
WORD yellowBlack = getColorAttribute(YELLOW, BLACK);
WORD whiteBlack = getColorAttribute(WHITE, BLACK);
drawString(30, 10, "游戏结束!", redBlack);
drawString(25, 12, "最终楼层: " + to_string(floor), yellowBlack);
drawString(25, 13, "角色等级: " + to_string(player.level), yellowBlack);
drawString(25, 14, "收集金币: " + to_string(player.gold), yellowBlack);
drawString(20, 16, "按任意键退出...", whiteBlack);
swapBuffers();
_getch();
}
void showStartScreen() {
clearBuffer();
WORD yellowBlack = getColorAttribute(YELLOW, BLACK);
WORD whiteBlack = getColorAttribute(WHITE, BLACK);
WORD greenBlack = getColorAttribute(GREEN, BLACK);
drawString(35, 8, "迷宫冒险", yellowBlack);
drawString(25, 11, "使用方向键移动", whiteBlack);
drawString(25, 12, "收集宝藏($)增加金币", whiteBlack);
drawString(25, 13, "避开陷阱(?)和障碍物", whiteBlack);
drawString(25, 14, "I键打开物品菜单使用道具", whiteBlack);
drawString(25, 15, "S键保存游戏,L键加载游戏", whiteBlack);
drawString(25, 16, "到达终点(E)进入下一层", whiteBlack);
drawString(25, 17, "与敌人战斗获得经验升级", whiteBlack);
drawString(30, 19, "按任意键开始...", greenBlack);
swapBuffers();
_getch();
}
void run() {
hideCursor();
showStartScreen();
while (!gameOver) {
display();
handleInput();
if (floorCompleted) {
showFloorComplete();
nextFloor();
}
moveEnemies();
if (gameOver) break;
Sleep(100); // 控制游戏速度
}
showGameOver();
}
};
// 初始化静态常量
const int MazeAdventure::SAVE_VERSION = 1;
int main() {
// 设置控制台编码为系统默认编码以支持中文
SetConsoleOutputCP(CP_ACP);
// 初始化双缓冲
initDoubleBuffering();
MazeAdventure game(31, 17);
game.run();
// 清理双缓冲资源
cleanupDoubleBuffering();
return 0;
}MC
备注:游玩体验不行
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <ctime>
#include <conio.h>
#include <windows.h>
#include <map>
#include <algorithm>
using namespace std;
// 全局常量
const int WORLD_WIDTH = 30;
const int WORLD_HEIGHT = 20;
const int WORLD_DEPTH = 5;
const int INVENTORY_SIZE = 10;
const int DAY_DURATION = 1000; // 白天持续的游戏刻数
// 方块类型枚举
enum BlockType {
AIR,
GRASS,
DIRT,
STONE,
COBBLESTONE,
WOOD,
LEAVES,
WATER,
SAND,
BEDROCK,
GLASS,
TORCH
};
// 工具类型枚举
enum ToolType {
HAND,
WOODEN_PICKAXE,
STONE_PICKAXE,
IRON_PICKAXE,
WOODEN_AXE,
STONE_AXE,
IRON_AXE,
SHOVEL
};
// 生物类型枚举
enum EntityType {
PLAYER,
ZOMBIE,
SHEEP,
PIG,
CREEPER
};
// 方向枚举
enum Direction {
NORTH,
SOUTH,
EAST,
WEST
};
// 时间枚举
enum TimeOfDay {
DAY,
SUNSET,
NIGHT,
SUNRISE
};
// 物品类
class Item {
private:
string name;
int count;
bool isStackable;
bool isTool;
ToolType toolType;
BlockType placeableBlock; // 如果是方块类物品,放置后变成的方块类型
public:
Item(string n, int c = 1, bool stackable = true, bool tool = false,
ToolType tt = HAND, BlockType pb = AIR)
: name(n), count(c), isStackable(stackable), isTool(tool),
toolType(tt), placeableBlock(pb) {}
string getName() const { return name; }
int getCount() const { return count; }
bool getIsStackable() const { return isStackable; }
bool getIsTool() const { return isTool; }
ToolType getToolType() const { return toolType; }
BlockType getPlaceableBlock() const { return placeableBlock; }
void addCount(int amount) { count += amount; }
void setCount(int amount) { count = amount; }
bool removeOne() {
if (count > 0) {
count--;
return true;
}
return false;
}
};
// 生物类
class Entity {
protected:
int x, y, z;
EntityType type;
int health;
int maxHealth;
bool isAlive;
public:
Entity(EntityType t, int xPos, int yPos, int zPos, int hp = 10)
: type(t), x(xPos), y(yPos), z(zPos), health(hp), maxHealth(hp), isAlive(true) {}
virtual ~Entity() {}
int getX() const { return x; }
int getY() const { return y; }
int getZ() const { return z; }
EntityType getType() const { return type; }
int getHealth() const { return health; }
bool getIsAlive() const { return isAlive; }
void setPosition(int xPos, int yPos, int zPos) {
x = xPos;
y = yPos;
z = zPos;
}
void damage(int amount) {
if (!isAlive) return;
health -= amount;
if (health <= 0) {
health = 0;
isAlive = false;
onDeath();
}
}
void heal(int amount) {
if (!isAlive) return;
health = min(health + amount, maxHealth);
}
virtual void update() {}
virtual void onDeath() {}
virtual void move(Direction dir) {
switch (dir) {
case NORTH: x--; break;
case SOUTH: x++; break;
case EAST: z++; break;
case WEST: z--; break;
}
}
};
// 玩家类
class Player : public Entity {
private:
Direction facing;
vector<Item*> inventory;
int selectedSlot;
int level;
int experience;
int hunger;
public:
Player(int xPos, int yPos, int zPos)
: Entity(PLAYER, xPos, yPos, zPos, 20), facing(NORTH),
selectedSlot(0), level(1), experience(0), hunger(20) {
// 初始化空 inventory
for (int i = 0; i < INVENTORY_SIZE; i++) {
inventory.push_back(nullptr);
}
// 给玩家一些初始物品
addItem(new Item("木材", 5, true, false, HAND, WOOD));
addItem(new Item("泥土", 5, true, false, HAND, DIRT));
addItem(new Item("木斧", 1, false, true, WOODEN_AXE));
addItem(new Item("木镐", 1, false, true, WOODEN_PICKAXE));
}
Direction getFacing() const { return facing; }
int getSelectedSlot() const { return selectedSlot; }
Item* getSelectedItem() const { return inventory[selectedSlot]; }
int getLevel() const { return level; }
int getExperience() const { return experience; }
int getHunger() const { return hunger; }
void turnLeft() {
switch (facing) {
case NORTH: facing = WEST; break;
case WEST: facing = SOUTH; break;
case SOUTH: facing = EAST; break;
case EAST: facing = NORTH; break;
}
}
void turnRight() {
switch (facing) {
case NORTH: facing = EAST; break;
case EAST: facing = SOUTH; break;
case SOUTH: facing = WEST; break;
case WEST: facing = NORTH; break;
}
}
void selectSlot(int slot) {
if (slot >= 0 && slot < INVENTORY_SIZE) {
selectedSlot = slot;
}
}
void addExperience(int amount) {
experience += amount;
// 简单的升级逻辑
while (experience >= level * 10) {
experience -= level * 10;
level++;
maxHealth += 2;
health = maxHealth;
cout << "升级了!现在是 " << level << " 级!" << endl;
}
}
void addHunger(int amount) {
hunger = min(hunger + amount, 20);
}
void reduceHunger(int amount) {
hunger = max(hunger - amount, 0);
if (hunger == 0) {
damage(1); // 饥饿状态下持续掉血
}
}
bool addItem(Item* item) {
// 尝试堆叠物品
if (item->getIsStackable()) {
for (int i = 0; i < INVENTORY_SIZE; i++) {
if (inventory[i] && inventory[i]->getName() == item->getName()) {
inventory[i]->addCount(item->getCount());
delete item;
return true;
}
}
}
// 寻找空槽位
for (int i = 0; i < INVENTORY_SIZE; i++) {
if (!inventory[i]) {
inventory[i] = item;
return true;
}
}
// inventory 已满
delete item;
return false;
}
bool removeItem(int slot) {
if (slot >= 0 && slot < INVENTORY_SIZE && inventory[slot]) {
if (inventory[slot]->removeOne()) {
if (inventory[slot]->getCount() == 0) {
delete inventory[slot];
inventory[slot] = nullptr;
}
return true;
}
}
return false;
}
void showInventory() const {
system("cls");
cout << "===== 背包 =====" << endl;
for (int i = 0; i < INVENTORY_SIZE; i++) {
cout << "[" << i << "] ";
if (inventory[i]) {
cout << inventory[i]->getName() << " x" << inventory[i]->getCount();
if (i == selectedSlot) cout << " <--";
} else {
cout << "空";
}
cout << endl;
}
cout << "=================" << endl;
cout << "按任意键继续..." << endl;
_getch();
}
void showStatus() const {
cout << "生命值: " << health << "/" << maxHealth << " ";
cout << "饥饿值: " << hunger << "/20 ";
cout << "等级: " << level << " (" << experience << "/" << level*10 << ")" << endl;
}
void update() override {
// 每段时间减少饥饿值
static int hungerTimer = 0;
if (++hungerTimer >= 100) {
hungerTimer = 0;
reduceHunger(1);
}
}
void onDeath() override {
cout << "你死了!" << endl;
// 简单的重生逻辑
health = maxHealth;
hunger = 20;
isAlive = true;
// 掉落一半经验
experience /= 2;
cout << "你在出生点重生了,并失去了一半经验!" << endl;
}
};
// 敌对生物类
class HostileMob : public Entity {
private:
int attackDamage;
public:
HostileMob(EntityType t, int xPos, int yPos, int zPos, int hp = 10, int damage = 2)
: Entity(t, xPos, yPos, zPos, hp), attackDamage(damage) {}
int getAttackDamage() const { return attackDamage; }
void update() override {
// 简单的AI - 随机移动
if (rand() % 5 == 0) { // 20% 的概率移动
move((Direction)(rand() % 4));
}
}
void onDeath() override {
cout << getTypeName() << " 被击败了!" << endl;
}
string getTypeName() const {
switch (type) {
case ZOMBIE: return "僵尸";
case CREEPER: return "爬行者";
default: return "怪物";
}
}
};
// 被动生物类
class PassiveMob : public Entity {
public:
PassiveMob(EntityType t, int xPos, int yPos, int zPos, int hp = 5)
: Entity(t, xPos, yPos, zPos, hp) {}
void update() override {
// 简单的AI - 随机移动
if (rand() % 10 == 0) { // 10% 的概率移动
move((Direction)(rand() % 4));
}
}
void onDeath() override {
cout << getTypeName() << " 被杀死了!" << endl;
}
string getTypeName() const {
switch (type) {
case SHEEP: return "绵羊";
case PIG: return "猪";
default: return "动物";
}
}
};
// 世界类
class World {
private:
BlockType blocks[WORLD_WIDTH][WORLD_HEIGHT][WORLD_DEPTH];
vector<Entity*> entities;
Player* player;
TimeOfDay timeOfDay;
int timeTicks;
// 方块的显示字符和颜色
char getBlockChar(BlockType type) const {
switch (type) {
case AIR: return ' ';
case GRASS: return 'G';
case DIRT: return 'D';
case STONE: return 'S';
case COBBLESTONE: return 'C';
case WOOD: return 'W';
case LEAVES: return 'L';
case WATER: return '~';
case SAND: return 'N';
case BEDROCK: return '#';
case GLASS: return '=';
case TORCH: return 't';
default: return '?';
}
}
// 设置控制台文本颜色
void setColor(int color) {
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
}
// 获取方块的颜色代码
int getBlockColor(BlockType type) const {
switch (type) {
case GRASS: return 2; // 绿色
case DIRT: return 6; // 棕色
case STONE: return 8; // 灰色
case COBBLESTONE: return 7; // 浅灰色
case WOOD: return 6; // 棕色
case LEAVES: return 10; // 亮绿色
case WATER: return 9; // 蓝色
case SAND: return 14; // 黄色
case BEDROCK: return 8; // 灰色
case GLASS: return 15; // 白色
case TORCH: return 14; // 黄色
default: return 15; // 白色
}
}
public:
World() : timeOfDay(DAY), timeTicks(0) {
// 初始化世界
generateTerrain();
// 创建玩家
player = new Player(WORLD_WIDTH / 2, 10, WORLD_DEPTH / 2);
entities.push_back(player);
// 生成一些生物
spawnEntities();
}
~World() {
for (Entity* entity : entities) {
delete entity;
}
}
Player* getPlayer() const { return player; }
// 生成地形
void generateTerrain() {
// 填充基岩
for (int x = 0; x < WORLD_WIDTH; x++) {
for (int z = 0; z < WORLD_DEPTH; z++) {
blocks[x][0][z] = BEDROCK;
}
}
// 生成简单地形
for (int x = 0; x < WORLD_WIDTH; x++) {
for (int z = 0; z < WORLD_DEPTH; z++) {
// 简单的高度图 - 使用正弦函数生成起伏
int height = 5 + sin(x * 0.5) * 2 + cos(z * 0.5) * 2;
// 填充石头
for (int y = 1; y < height - 1; y++) {
blocks[x][y][z] = STONE;
}
// 填充泥土
if (height > 1) {
blocks[x][height - 1][z] = DIRT;
}
// 顶部是草方块
blocks[x][height][z] = GRASS;
// 生成一些树木
if (rand() % 20 == 0 && height < 15) {
// 树干
for (int y = height + 1; y < height + 4; y++) {
if (y < WORLD_HEIGHT) {
blocks[x][y][z] = WOOD;
}
}
// 树叶
for (int dy = -2; dy <= 2; dy++) {
for (int dx = -2; dx <= 2; dx++) {
for (int dz = -2; dz <= 2; dz++) {
int nx = x + dx;
int ny = height + 4 + dy;
int nz = z + dz;
if (nx >= 0 && nx < WORLD_WIDTH &&
ny >= 0 && ny < WORLD_HEIGHT &&
nz >= 0 && nz < WORLD_DEPTH) {
if (dx*dx + dy*dy + dz*dz < 4) { // 球形树叶
blocks[nx][ny][nz] = LEAVES;
}
}
}
}
}
}
// 生成一些水
if (rand() % 30 == 0 && height < 7) {
for (int y = height; y < height + 2; y++) {
if (y < WORLD_HEIGHT) {
blocks[x][y][z] = WATER;
}
}
}
}
}
}
// 生成生物
void spawnEntities() {
// 生成一些被动生物
for (int i = 0; i < 5; i++) {
int x = rand() % WORLD_WIDTH;
int z = rand() % WORLD_DEPTH;
// 找到地面高度
int y = 1;
for (; y < WORLD_HEIGHT; y++) {
if (blocks[x][y][z] != AIR) break;
}
y++; // 站在方块上面
EntityType type = (rand() % 2 == 0) ? SHEEP : PIG;
entities.push_back(new PassiveMob(type, x, y, z));
}
// 生成一些敌对生物
for (int i = 0; i < 3; i++) {
int x = rand() % WORLD_WIDTH;
int z = rand() % WORLD_DEPTH;
int y = 1;
for (; y < WORLD_HEIGHT; y++) {
if (blocks[x][y][z] != AIR) break;
}
y++;
EntityType type = (rand() % 2 == 0) ? ZOMBIE : CREEPER;
entities.push_back(new HostileMob(type, x, y, z));
}
}
// 获取方块
BlockType getBlock(int x, int y, int z) const {
if (x < 0 || x >= WORLD_WIDTH || y < 0 || y >= WORLD_HEIGHT || z < 0 || z >= WORLD_DEPTH) {
return AIR; // 超出世界范围视为空气
}
return blocks[x][y][z];
}
// 设置方块
bool setBlock(int x, int y, int z, BlockType type) {
if (x < 0 || x >= WORLD_WIDTH || y < 0 || y >= WORLD_HEIGHT || z < 0 || z >= WORLD_DEPTH) {
return false;
}
if (blocks[x][y][z] == BEDROCK) {
return false; // 基岩无法改变
}
blocks[x][y][z] = type;
return true;
}
// 破坏方块
bool breakBlock(int x, int y, int z, ToolType tool) {
BlockType type = getBlock(x, y, z);
if (type == AIR || type == BEDROCK) {
return false;
}
// 检查工具是否适合破坏该方块
bool canBreak = true;
int dropChance = 100; // 掉落概率百分比
switch (type) {
case STONE:
case COBBLESTONE:
canBreak = (tool == STONE_PICKAXE || tool == IRON_PICKAXE);
dropChance = (tool == IRON_PICKAXE) ? 100 : 80;
break;
case WOOD:
canBreak = (tool == WOODEN_AXE || tool == STONE_AXE || tool == IRON_AXE);
dropChance = (tool == IRON_AXE) ? 100 : 90;
break;
case LEAVES:
canBreak = true;
dropChance = 30; // 树叶有几率不掉落物品
break;
// 其他方块可以被任何工具破坏
}
if (!canBreak) {
cout << "你需要合适的工具来破坏这个方块!" << endl;
return false;
}
// 破坏方块
setBlock(x, y, z, AIR);
// 掉落物品
if (rand() % 100 < dropChance) {
string itemName;
BlockType placeable;
switch (type) {
case GRASS: itemName = "泥土"; placeable = DIRT; break;
case DIRT: itemName = "泥土"; placeable = DIRT; break;
case STONE: itemName = "石头"; placeable = STONE; break;
case COBBLESTONE: itemName = "圆石"; placeable = COBBLESTONE; break;
case WOOD: itemName = "木材"; placeable = WOOD; break;
case LEAVES: itemName = "树叶"; placeable = LEAVES; break;
case SAND: itemName = "沙子"; placeable = SAND; break;
default: itemName = "未知物品"; placeable = AIR;
}
player->addItem(new Item(itemName, 1, true, false, HAND, placeable));
player->addExperience(1); // 破坏方块获得经验
}
return true;
}
// 更新世界
void update() {
// 更新时间
timeTicks++;
if (timeTicks >= DAY_DURATION) {
timeTicks = 0;
timeOfDay = (TimeOfDay)((timeOfDay + 1) % 4);
// 昼夜交替时的消息
switch (timeOfDay) {
case DAY: cout << "太阳升起了,新的一天开始了!" << endl; break;
case SUNSET: cout << "太阳开始落山了..." << endl; break;
case NIGHT: cout << "夜幕降临,危险的生物开始出现!" << endl;
// 夜晚生成更多怪物
if (rand() % 2 == 0) {
spawnEntities();
}
break;
case SUNRISE: cout << "黎明将至,怪物开始消失..." << endl; break;
}
}
// 更新所有实体
for (Entity* entity : entities) {
entity->update();
// 检查实体是否在地面上
if (entity->getType() != PLAYER) {
int x = entity->getX();
int y = entity->getY();
int z = entity->getZ();
// 简单的重力系统
if (getBlock(x, y - 1, z) == AIR && y > 1) {
entity->setPosition(x, y - 1, z);
}
}
}
// 检查玩家与生物的碰撞
checkCollisions();
}
// 检查碰撞
void checkCollisions() {
int px = player->getX();
int py = player->getY();
int pz = player->getZ();
for (Entity* entity : entities) {
if (entity->getType() == PLAYER || !entity->getIsAlive()) continue;
int ex = entity->getX();
int ey = entity->getY();
int ez = entity->getZ();
// 简单的碰撞检测(1格范围内)
if (abs(px - ex) <= 1 && abs(py - ey) <= 1 && abs(pz - ez) <= 1) {
if (entity->getType() == ZOMBIE || entity->getType() == CREEPER) {
// 敌对生物攻击玩家
HostileMob* mob = dynamic_cast<HostileMob*>(entity);
if (mob) {
player->damage(mob->getAttackDamage());
cout << mob->getTypeName() << " 攻击了你!";
cout << " 生命值: " << player->getHealth() << "/" << player->getMaxHealth() << endl;
}
}
}
}
}
// 渲染世界
void render() {
system("cls");
// 显示时间
cout << "时间: ";
switch (timeOfDay) {
case DAY: cout << "白天"; break;
case SUNSET: cout << "黄昏"; break;
case NIGHT: cout << "夜晚"; break;
case SUNRISE: cout << "黎明"; break;
}
cout << " ";
player->showStatus();
cout << endl;
// 渲染玩家周围的区域(简单的第一人称视角)
int px = player->getX();
int py = player->getY();
int pz = player->getZ();
Direction facing = player->getFacing();
// 根据面向方向调整渲染视角
for (int dy = -5; dy <= 5; dy++) { // 垂直方向
for (int dz = -8; dz <= 8; dz++) { // 深度方向
bool foundBlock = false;
// 根据面向方向计算坐标
for (int dx = 1; dx <= 10; dx++) { // 距离
int x, z;
switch (facing) {
case NORTH:
x = px - dx;
z = pz + dz;
break;
case SOUTH:
x = px + dx;
z = pz - dz;
break;
case EAST:
x = px + dz;
z = pz + dx;
break;
case WEST:
x = px - dz;
z = pz - dx;
break;
}
int y = py + dy;
BlockType block = getBlock(x, y, z);
if (block != AIR) {
// 渲染方块
setColor(getBlockColor(block));
cout << getBlockChar(block);
foundBlock = true;
break;
}
}
if (!foundBlock) {
// 渲染天空/背景
setColor((timeOfDay == NIGHT) ? 1 : 15); // 夜晚是深蓝色,白天是白色
cout << ((timeOfDay == NIGHT && rand() % 50 == 0) ? '*' : ' ');
}
}
setColor(15); // 重置颜色
cout << endl;
}
setColor(15); // 重置颜色
// 显示实体
cout << endl << "附近的生物: ";
bool hasEntities = false;
for (Entity* entity : entities) {
if (entity->getType() != PLAYER && entity->getIsAlive()) {
int dx = abs(entity->getX() - px);
int dz = abs(entity->getZ() - pz);
if (dx <= 10 && dz <= 10) { // 只显示一定范围内的实体
if (hasEntities) cout << ", ";
HostileMob* hostile = dynamic_cast<HostileMob*>(entity);
PassiveMob* passive = dynamic_cast<PassiveMob*>(entity);
if (hostile) {
setColor(12); // 敌对生物显示红色
cout << hostile->getTypeName();
} else if (passive) {
setColor(10); // 被动生物显示绿色
cout << passive->getTypeName();
}
hasEntities = true;
}
}
}
if (!hasEntities) {
cout << "无";
}
setColor(15); // 重置颜色
cout << endl;
// 显示选中的物品
Item* selected = player->getSelectedItem();
cout << "手中物品: ";
if (selected) {
cout << selected->getName() << " x" << selected->getCount() << endl;
} else {
cout << "无" << endl;
}
// 显示操作提示
cout << endl;
cout << "WASD: 移动, QE: 切换物品, 空格: 放置方块, 左Ctrl: 破坏方块, ";
cout << "I: 打开背包, R: 旋转视角, ESC: 退出游戏" << endl;
}
// 玩家攻击
void playerAttack() {
int px = player->getX();
int py = player->getY();
int pz = player->getZ();
Direction facing = player->getFacing();
// 攻击方向
int ax = px, az = pz;
switch (facing) {
case NORTH: ax--; break;
case SOUTH: ax++; break;
case EAST: az++; break;
case WEST: az--; break;
}
// 检查是否击中生物
for (Entity* entity : entities) {
if (entity->getType() == PLAYER || !entity->getIsAlive()) continue;
if (entity->getX() == ax && entity->getY() == py && entity->getZ() == az) {
// 计算伤害,受工具影响
int damage = 2;
Item* weapon = player->getSelectedItem();
if (weapon && weapon->getIsTool()) {
switch (weapon->getToolType()) {
case WOODEN_AXE: damage = 3; break;
case STONE_AXE: damage = 4; break;
case IRON_AXE: damage = 5; break;
default: damage = 2;
}
}
entity->damage(damage);
cout << "你攻击了" << ((entity->getType() == ZOMBIE || entity->getType() == CREEPER) ?
dynamic_cast<HostileMob*>(entity)->getTypeName() :
dynamic_cast<PassiveMob*>(entity)->getTypeName()) << "!" << endl;
// 生物被击败,获得经验和物品
if (!entity->getIsAlive()) {
player->addExperience(5);
// 随机掉落物品
if (rand() % 3 == 0) {
string drop;
if (entity->getType() == SHEEP) drop = "羊毛";
else if (entity->getType() == PIG) drop = "猪肉";
else if (entity->getType() == ZOMBIE) drop = "腐肉";
else drop = "火药";
player->addItem(new Item(drop, 1));
cout << "获得了 " << drop << endl;
}
}
return;
}
}
cout << "没有击中任何东西!" << endl;
}
// 合成系统
void craftItem() {
system("cls");
cout << "===== 合成 =====" << endl;
cout << "1. 木板 -> 木棍 (需要 1 木材)" << endl;
cout << "2. 木棍 + 木材 -> 木斧 (需要 1 木材, 2 木棍)" << endl;
cout << "3. 木棍 + 木材 -> 木镐 (需要 1 木材, 2 木棍)" << endl;
cout << "4. 木棍 + 石头 -> 石斧 (需要 1 石头, 2 木棍)" << endl;
cout << "5. 木棍 + 石头 -> 石镐 (需要 1 石头, 2 木棍)" << endl;
cout << "6. 退出合成" << endl;
cout << "选择要合成的物品: ";
int choice;
cin >> choice;
cin.ignore();
switch (choice) {
case 1:
// 木板 -> 木棍
if (hasItem("木材")) {
removeItem("木材", 1);
player->addItem(new Item("木棍", 4));
cout << "合成了 4 根木棍!" << endl;
} else {
cout << "缺少木材!" << endl;
}
break;
case 2:
// 木斧
if (hasItem("木材") && hasItem("木棍", 2)) {
removeItem("木材", 1);
removeItem("木棍", 2);
player->addItem(new Item("木斧", 1, false, true, WOODEN_AXE));
cout << "合成了木斧!" << endl;
} else {
cout << "缺少材料!需要 1 木材和 2 木棍" << endl;
}
break;
// 可以添加更多合成配方
default:
if (choice != 6) cout << "无效的选择!" << endl;
}
cout << "按任意键继续..." << endl;
_getch();
}
// 检查玩家是否有特定物品
bool hasItem(string name, int count = 1) {
int total = 0;
for (int i = 0; i < INVENTORY_SIZE; i++) {
if (player->getInventory()[i] && player->getInventory()[i]->getName() == name) {
total += player->getInventory()[i]->getCount();
if (total >= count) return true;
}
}
return false;
}
// 从玩家物品栏移除物品
bool removeItem(string name, int count) {
int remaining = count;
for (int i = 0; i < INVENTORY_SIZE && remaining > 0; i++) {
if (player->getInventory()[i] && player->getInventory()[i]->getName() == name) {
int take = min(remaining, player->getInventory()[i]->getCount());
player->getInventory()[i]->setCount(player->getInventory()[i]->getCount() - take);
remaining -= take;
if (player->getInventory()[i]->getCount() == 0) {
delete player->getInventory()[i];
player->getInventory()[i] = nullptr;
}
}
}
return remaining == 0;
}
};
// 游戏类
class Game {
private:
World* world;
bool running;
public:
Game() : running(true) {
world = new World();
srand(time(0));
}
~Game() {
delete world;
}
void run() {
cout << "欢迎来到我的世界!" << endl;
cout << "按任意键开始游戏..." << endl;
_getch();
while (running) {
// 处理输入
handleInput();
// 更新游戏状态
world->update();
// 渲染游戏
world->render();
// 控制游戏速度
Sleep(50);
}
cout << "游戏结束,谢谢游玩!" << endl;
}
void handleInput() {
if (_kbhit()) {
Player* player = world->getPlayer();
int key = _getch();
switch (key) {
case 'w':
case 'W':
player->move(NORTH);
break;
case 's':
case 'S':
player->move(SOUTH);
break;
case 'd':
case 'D':
player->move(EAST);
break;
case 'a':
case 'A':
player->move(WEST);
break;
case 'q':
case 'Q':
// 切换到上一个物品槽
player->selectSlot((player->getSelectedSlot() - 1 + INVENTORY_SIZE) % INVENTORY_SIZE);
break;
case 'e':
case 'E':
// 切换到下一个物品槽
player->selectSlot((player->getSelectedSlot() + 1) % INVENTORY_SIZE);
break;
case ' ': // 空格 - 放置方块
{
Item* selected = player->getSelectedItem();
if (selected && selected->getPlaceableBlock() != AIR) {
int x = player->getX();
int y = player->getY();
int z = player->getZ();
Direction facing = player->getFacing();
// 计算放置位置(玩家前方)
switch (facing) {
case NORTH: x--; break;
case SOUTH: x++; break;
case EAST: z++; break;
case WEST: z--; break;
}
if (world->getBlock(x, y, z) == AIR) {
world->setBlock(x, y, z, selected->getPlaceableBlock());
player->removeItem(player->getSelectedSlot());
}
}
break;
}
case 17: // Ctrl键 - 破坏方块
{
int x = player->getX();
int y = player->getY();
int z = player->getZ();
Direction facing = player->getFacing();
// 计算破坏位置(玩家前方)
switch (facing) {
case NORTH: x--; break;
case SOUTH: x++; break;
case EAST: z++; break;
case WEST: z--; break;
}
ToolType tool = HAND;
Item* selected = player->getSelectedItem();
if (selected && selected->getIsTool()) {
tool = selected->getToolType();
}
world->breakBlock(x, y, z, tool);
break;
}
case 'i':
case 'I':
// 打开背包
player->showInventory();
break;
case 'r':
case 'R':
// 旋转视角(向右)
player->turnRight();
break;
case 'f':
case 'F':
// 攻击
world->playerAttack();
break;
case 'c':
case 'C':
// 打开合成界面
world->craftItem();
break;
case 27: // ESC键
running = false;
break;
}
}
}
};
int main() {
// 设置控制台窗口大小
HWND console = GetConsoleWindow();
RECT r;
GetWindowRect(console, &r);
MoveWindow(console, r.left, r.top, 800, 600, TRUE);
Game game;
game.run();
return 0;
}