How can I change the HP of a randomly selected character? (string = "1"; player[string].hp = 0;)
To easily select a random player to modify, the easiest approach is to place all players in a container such as a vector. Then you can generate a random index into the vector and modify the player at that position.
How can I dynamically choose the class value to be loaded? (string = "hp"; player1.[string] = 10;)
To dynamically choose which property you wish to modify there are a few approaches. An easy solution is shown below with a mapping from string property names to property values. Another approach is to create an enum class which enumerates the different properties and then use that as a key instead of strings.
#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);
}