我对C ++很新,并试图创建一个史诗般的RPG。游戏中有四个玩家,每个玩家都有一个包含所有信息(名称,等级,等等)的类角色实例。
class character
{
public:
string name = "Nameless";
int hp = 10;
int mp = 5;
}
代码中的其他地方我使用此类的实例创建播放字符:
character player1;
character player2;
character player3;
character player4;
在战斗中,我需要能够动态更改玩家值。我有两个具体问题:
也许我应该使用别的东西而不是类,接受建议:)
干杯!
答案 0 :(得分:2)
如何更改随机选择的字符的HP? (string =“1”; player [string] .hp = 0;)
使用数组而不是变量:
character players[4];
如果需要,您还可以添加对玩家的引用:
character &player1 = players[0];
character &player2 = players[1];
character &player3 = players[2];
character &player4 = players[3];
如何动态选择要加载的类值? (string =“hp”; player1。[string] = 10;)
最初你不能。
如果需要,请尝试使用字典,或在课程中重载[]
运算符。
无论如何,这似乎不是一个好主意。
答案 1 :(得分:2)
如何更改随机选择的字符的HP? (string =" 1&#34 ;; player [string] .hp = 0;)
要轻松选择要修改的随机播放器,最简单的方法是将所有播放器放在容器中,例如矢量。然后你可以在向量中生成一个随机索引并修改那个位置的玩家。
如何动态选择要加载的类值? (string =" hp&#34 ;; player1。[string] = 10;)
要动态选择要修改的属性,有几种方法。下面显示了一个简单的解决方案,其中包含从字符串属性名到属性值的映射。另一种方法是创建一个枚举不同属性的枚举类,然后将其用作键而不是字符串。
#include <iostream>
#include <iterator>
#include <random>
#include <string>
#include <unordered_map>
#include <vector>
class character
{
public:
std::string name = "Nameless";
std::unordered_map<std::string, int> properties{
{ "hp", 10 },
{ "mp", 5 }
};
};
void print_players(const std::vector<character>& players) {
for (const auto& player : players) {
std::cout << player.name;
for (const auto& property : player.properties) {
std::cout << ", " << property.first << "=" << property.second;
}
std::cout << std::endl;
}
}
int main() {
auto players = std::vector<character>{
character{"Player 1"},
character{"Player 2"},
character{"Player 3"},
character{"Player 4"}
};
print_players(players);
auto rng = std::default_random_engine{std::random_device{}()};
// Select a random player
auto random_player_distribution = std::uniform_int_distribution<>{0, players.size() - 1};
auto& random_player = players[random_player_distribution(rng)];
// Select a random property
auto random_property_distribution = std::uniform_int_distribution<>{0, random_player.properties.size() - 1};
auto random_property_iterator = random_player.properties.begin();
std::advance(random_property_iterator, random_property_distribution(rng));
// Modify random property
random_property_iterator->second = 42;
print_players(players);
}