Video Coming Soon...
44: Basic struct
Talk about how we're going to make a mini combat system for multiple combatants.
The Code
View Source file ex44.cpp Only
#include <fmt/core.h>
#include <string>
#include <random>
std::random_device RNG;
std::mt19937 GENERATOR(RNG());
struct Combatant {
std::string name;
int damage{0};
int hp{0};
float hearing_distance{0.0f};
};
int random_number(int from, int to) {
std::uniform_int_distribution rand(from, to);
return rand(GENERATOR);
}
void fight(Combatant& attacker, Combatant& defender) {
int damage = random_number(0, attacker.damage);
if(damage > 0) {
defender.hp -= damage;
fmt::println("{} hit {} for {}. {} now has {} hp",
attacker.name, defender.name, damage,
defender.name, defender.hp);
} else {
fmt::println("{} missed {}!",
attacker.name, defender.name);
}
if(defender.hp <= 0) {
fmt::println("{} died. {} wins! {} has {} HP",
defender.name, attacker.name,
attacker.name, attacker.hp);
}
}
int main(int argc, char* argv[]) {
Combatant giant_rat{"Giant Rat", 20, 30, 2.4f};
Combatant player{"Player", 20, 50, 1.4f};
bool player_turn = false;
while(giant_rat.hp > 0 && player.hp > 0) {
if(player_turn) {
fight(giant_rat, player);
} else {
fight(player, giant_rat);
}
player_turn = !player_turn;
}
}
The Breakdown
line of code- Description.
The Discussion
Blah blah.
Further Study
- Do this next.
Register for Learn C++ the Hard Way
Register to gain access to additional videos which demonstrate each exercise. Videos are priced to cover the cost of hosting.