c++——文字rpg游戏
时间: 2023-12-17 14:28:37 浏览: 59
以下是一个简单的C++文字RPG游戏的示例代码,其中包括了基本的角色、战斗和物品系统:
```c++
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
// 角色类
class Character {
public:
string name;
int hp;
int atk;
int def;
int gold;
Character(string n, int h, int a, int d, int g) {
name = n;
hp = h;
atk = a;
def = d;
gold = g;
}
// 攻击函数
void attack(Character& other) {
int damage = atk - other.def;
if (damage < 0) {
damage = 0;
}
other.hp -= damage;
cout << name << "攻击了" << other.name << ",造成了" << damage << "点伤害。" << endl;
}
// 是否死亡
bool isDead() {
return hp <= 0;
}
};
// 物品类
class Item {
public:
string name;
int price;
int hp;
int atk;
int def;
Item(string n, int p, int h, int a, int d) {
name = n;
price = p;
hp = h;
atk = a;
def = d;
}
};
// 商店类
class Shop {
public:
Item items[3];
Shop() {
items[0] = Item("草药", 10, 20, 0, 0);
items[1] = Item("铁剑", 50, 0, 10, 0);
items[2] = Item("铁甲", 100, 0, 0, 10);
}
// 显示商店物品
void showItems() {
cout << "欢迎光临!以下是本店的物品:" << endl;
for (int i = 0; i < 3; i++) {
cout << i + 1 << ". " << items[i].name << " - " << items[i].price << "金币" << endl;
}
}
// 购买物品
bool buy(Character& c, int choice) {
if (c.gold < items[choice - 1].price) {
cout << "金币不足,法购买!" << endl;
return false;
}
c.gold -= items[choice - 1].price;
c.hp += items[choice - 1].hp;
c.atk += items[choice - 1].atk;
c.def += items[choice - 1].def;
cout << "购买成功!" << endl;
return true;
}
};
// 战斗函数
void battle(Character& player, Character& enemy) {
cout << "你遇到了一只" << enemy.name << ",准备战斗!" << endl;
while (!player.isDead() && !enemy.isDead()) {
player.attack(enemy);
if (enemy.isDead()) {
cout << enemy.name << "被你打败了!" << endl;
player.gold += enemy.gold;
return;
}
enemy.attack(player);
if (player.isDead()) {
cout << "你被" << enemy.name << "打败了!" << endl;
return;
}
}
}
int main() {
srand(time(NULL)); // 初始化随机数种子
// 初始化角色和商店
Character player("勇者", 100, 10, 5, 50);
Character enemies[3] = {
Character("史莱姆", 30, 5, 2, 10),
Character("骷髅兵", 50, 10, 5, 20),
Character("巨龙", 100, 20, 10, 50)
};
Shop shop;
// 游戏循环
while (true) {
cout << "你的状态 - HP:" << player.hp << " ATK:" << player.atk << " DEF:" << player.def << " 金币:" << player.gold << endl;
cout << "请选择操作:" << endl;
cout << "1. 进入商店" << endl;
cout << "2. 进行战斗" << endl;
cout << "3. 离开游戏" << endl;
int choice;
cin >> choice;
switch (choice) {
case 1:
shop.showItems();
cout << "请选择要购买的物品(输入编号):" << endl;
cin >> choice;
shop.buy(player, choice);
break;
case 2:
battle(player, enemies[rand() % 3]);
break;
case 3:
cout << "游戏结束,欢迎再次光临!" << endl;
return 0;
default:
cout << "无效的操作!" << endl;
break;
}
}
return 0;
}
```