Video Coming Soon...
55: Implement a Basic Object System
This exercise is pending. Quick notes about this exercise:
- This will effectively use functions on structs to recreate everything in OOP except inheritance
The Code
First, using functions that live outside of the struct, kind of C-style OOP:
View Source file ex55a.cpp Only
#include <fmt/core.h>
#include <chrono>
#include <thread>
#include <string>
#include <functional>
#include <memory>
using std::shared_ptr, std::make_shared, std::string;
struct Person {
std::string name;
int age;
};
shared_ptr<Person> Person_new(const string& name, int age) {
auto self = make_shared<Person>(name, age);
return self;
}
void Person_talk(shared_ptr<Person> self) {
fmt::println("I am {} and I am {} years old.",
self->name, self->age);
}
int main(int argc, char* argv[]) {
auto zed = Person_new("Zed", 51);
auto mary = Person_new("Mary", 28);
Person_talk(zed);
Person_talk(mary);
return 0;
}
Then using a lambda inside struct Person since they know that you can assign a lambda to a variable, and you can put a variable in a struct, so it follows:
View Source file ex55b.cpp Only
#include <fmt/core.h>
#include <chrono>
#include <thread>
#include <string>
#include <functional>
#include <memory>
using std::shared_ptr, std::make_shared, std::string;
struct Person {
std::string name;
int age;
std::function<void()> talk = nullptr;
};
shared_ptr<Person> Person_new(const string& name, int age) {
auto self = make_shared<Person>(name, age);
self->talk = [self]() {
fmt::println("I am {} and I am {} years old.",
self->name, self->age);
};
return self;
}
int main(int argc, char* argv[]) {
auto zed = Person_new("Zed", 51);
auto mary = Person_new("Mary", 28);
zed->talk();
mary->talk();
return 0;
}
Finally, using this in the combat engine so that you can tell two combatants to fight:
View Source file ex55.cpp Only
#include <fmt/core.h>
#include <string>
#include <random>
#include <memory>
#include <algorithm>
#include <unordered_map>
#include <vector>
#include <ranges>
#include <functional>
using std::shared_ptr, std::make_shared, std::string;
std::random_device RNG;
std::mt19937 GENERATOR(RNG());
struct Combatant {
string name;
int damage{0};
int hp{0};
bool dead{false};
std::function<void(shared_ptr<Combatant>)> fight = nullptr;
};
using ArenaID = int;
using Arena = std::unordered_map<ArenaID, shared_ptr<Combatant>>;
using CombatQueue = std::vector<size_t>;
int random_number(int from, int to) {
std::uniform_int_distribution rand(from, to);
return rand(GENERATOR);
}
void fight(shared_ptr<Combatant> attacker, shared_ptr<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);
}
}
shared_ptr<Combatant> Combatant_new(const string& name, int damage, int hp) {
auto self = make_shared<Combatant>(name, damage, hp);
self->fight = [self](shared_ptr<Combatant> target) {
fight(self, target);
};
return self;
}
void fill_arena(Arena& arena, int combatants) {
using namespace std::ranges;
for(auto arena_id : views::iota(0, combatants)) {
string name = fmt::format("Giant Rat #{}", arena_id);
int hp = random_number(5,20);
int damage = random_number(2,10);
auto fighter = Combatant_new(name, damage, hp);
arena.try_emplace(arena_id, fighter);
}
}
bool combat_active(Arena& arena, shared_ptr<Combatant> player) {
return !arena.empty() && player->hp > 0;
}
CombatQueue queue_combat(Arena& arena) {
using namespace std::ranges;
auto queue = arena | views::keys | to<CombatQueue>();
shuffle(queue, GENERATOR);
return queue;
}
void run_combat(shared_ptr<Combatant> player, shared_ptr<Combatant> who) {
bool player_turn = random_number(0,1);
if(player_turn) {
who->fight(player);
} else {
player->fight(who);
}
// now how to remove when dead
if(who->hp <= 0) {
who->dead = true;
}
}
void cull_the_dead(Arena& arena) {
using namespace std::ranges;
auto is_dead = [&](auto& tuple) -> bool { return tuple.second->dead; };
auto dead = arena | views::filter(is_dead) | views::elements<0> | to<CombatQueue>();
for(auto id : dead) {
arena.erase(id);
}
}
int main(int argc, char* argv[]) {
using namespace std::ranges;
Arena arena;
auto player = Combatant_new("Player", 20, 50);
fill_arena(arena, 10);
// now with multiple combatants we have to keep going until the player dies
while(combat_active(arena, player)) {
auto whos_next = queue_combat(arena);
for_each(whos_next, [&](auto enemy_id) {
run_combat(player, arena[enemy_id]);
});
cull_the_dead(arena);
}
if(arena.empty()) {
fmt::println("The Player Wins! You defeated all of the rats.");
} else {
fmt::println("You Died! The Rats Win.");
}
}
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.