1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
|
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
// Weapon Class Definition
class Weapon
{
public:
std::string name() const
{ return name_m; };
int damage() const
{ return damage_m; }
int cost() const
{ return cost_m; }
void display() const;
static Weapon create(const std::string& weapon);
private:
Weapon(std::string name_, int cost_, int damage_)
: name_m(name_), cost_m(cost_), damage_m(damage_) {}
std::string name_m;
int cost_m;
int damage_m;
};
void Weapon::display() const
{
std::cout << "Name: " << name() << '\n' <<
"Cost: " << cost() << '\n' <<
"Damage: " << damage() << '\n';
}
Weapon Weapon::create(const std::string& weapon)
{
static std::unordered_map<std::string, Weapon> weapons = { {"shotgun", {"ShotGun", 700, 93}},
{"rifle", {"Rifle", 960, 120}}, {"laser_rifle", {"Laser-Rifle", 1400, 175}},
};
return weapons.at(weapon); //Throws exceptions if tried to create unknown weapon
}
class Shop
{
public:
Shop();
void stock() const;
void info(std::size_t index) const;
Weapon buy(std::size_t index);
private:
std::vector<Weapon> goods;
};
Shop::Shop()
: goods( {Weapon::create("shotgun"), Weapon::create("rifle"),
Weapon::create("laser_rifle") }) {}
void Shop::stock() const
{
for(int i = 0; i < goods.size(); ++i)
std::cout << i + 1 << ": " << goods[i].name() << '\n';
}
void Shop::info(std::size_t index) const
{
goods.at(index).display();
}
Weapon Shop::buy(std::size_t index)
{
return goods.at(index);
}
// Player Class Definition
class player
{
std::string name;
int coins;
public:
void shop(Shop& where);
};
void player::shop(Shop& where)
{
while (std::cin) {
std::cout << "Enter 0 to exit or choose something to get extra information:\n";
where.stock();
int choice;
std::cin >> choice;
if (choice == 0)
break;
where.info(--choice);
std::cout << "Do you want to buy? (Y/N)\n";
char ans;
std::cin >> ans;
if (ans == 'Y')
coins -= where.buy(choice).cost();
}
}
int main()
{
Shop generic_shop;
player red_player;
red_player.shop(generic_shop);
}
|