C++ FOR RPG B-0.0.1
2025-09-05 20:20:02
发布于:广东
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
// 角色类
class Character {
public:
string name;
int hp;
int maxHp;
int atk;
int def;
int level;
int exp;
Character(string n, int h, int a, int d) :
name(n), hp(h), maxHp(h), atk(a), def(d), level(1), exp(0) {}
void attack(Character &target) {
int damage = max(1, atk - target.def/2);
target.hp -= damage;
cout << name << "对" << target.name << "造成" << damage << "点伤害!\n";
}
void levelUp() {
if(exp >= level*50) {
level++;
maxHp += 10;
atk += 3;
def += 2;
hp = maxHp;
exp -= (level-1)*50;
cout << "★ " << name << "升级到Lv." << level << "!\n";
}
}
bool isAlive() { return hp > 0; }
};
// 怪物类
class Monster {
public:
string name;
int hp;
int atk;
int def;
int expReward;
Monster(string n, int h, int a, int d, int exp) :
name(n), hp(h), atk(a), def(d), expReward(exp) {}
};
// 游戏场景
void battle(Character &player, Monster &monster) {
cout << "\n遭遇" << monster.name << "!\n";
while(player.isAlive() && monster.hp > 0) {
// 玩家回合
cout << "\n[你的回合] HP:" << player.hp << "/" << player.maxHp << endl;
cout << "1.攻击 2.逃跑\n选择:";
int choice;
cin >> choice;
if(choice == 1) {
player.attack(monster);
cout << monster.name << "剩余HP:" << max(0, monster.hp) << endl;
} else {
if(rand()%100 < 30) {
cout << "逃跑成功!\n";
return;
}
cout << "逃跑失败!\n";
}
// 怪物回合
if(monster.hp > 0) {
cout << "\n[" << monster.name << "的回合]\n";
int damage = max(1, monster.atk - player.def/2);
player.hp -= damage;
cout << monster.name << "对你造成" << damage << "点伤害!\n";
}
}
if(monster.hp <= 0) {
player.exp += monster.expReward;
cout << "\n★ 击败" << monster.name << ",获得" << monster.expReward << "经验!\n";
player.levelUp();
}
}
int main() {
srand(time(0));
cout << "=== 文字RPG游戏 ===\n";
cout << "输入角色名:";
string name;
cin >> name;
Character player(name, 100, 15, 5);
Monster monsters[3] = {
Monster("史莱姆", 30, 5, 2, 20),
Monster("骷髅兵", 50, 10, 5, 40),
Monster("巨龙", 150, 20, 10, 100)
};
while(player.isAlive()) {
cout << "\n=== 主菜单 ===\n";
cout << "1.探索 2.状态 3.休息 4.退出\n选择:";
int choice;
cin >> choice;
switch(choice) {
case 1: {
Monster &m = monsters[rand()%3];
battle(player, m);
break;
}
case 2:
cout << "\n=== 角色状态 ===\n";
cout << "名称:" << player.name << endl;
cout << "Lv." << player.level << endl;
cout << "HP:" << player.hp << "/" << player.maxHp << endl;
cout << "攻击:" << player.atk << " 防御:" << player.def << endl;
cout << "经验:" << player.exp << "/" << player.level*50 << endl;
break;
case 3:
player.hp = min(player.maxHp, player.hp + 30);
cout << "休息恢复30HP,当前HP:" << player.hp << endl;
break;
case 4:
cout << "游戏结束\n";
return 0;
default:
cout << "无效输入\n";
}
}
cout << "\nGAME OVER - " << player.name << "已阵亡\n";
return 0;
}
这里空空如也
有帮助,赞一个