#include <iostream>
#include <memory>
#include <vector>
#include <cstdlib>
#include <ctime>
class Dice {
private:
int sides_;
public:
Dice(int sides);
~Dice();
int roll() const;
};
class Player {
private:
std::shared_ptr<Dice> dice_;
public:
Player();
~Player();
Player& takeDice(std::vector<std::shared_ptr<Dice>>& dices, int index);
Player& rollDice();
Player& putDice(std::vector<std::shared_ptr<Dice>>& dices, int index);
};
Dice::Dice(int sides) : sides_(sides) { std::cout << "Кубик " << this << " создан" << std::endl; }
Dice::~Dice() { std::cout << "Кубик " << this << " удален" << std::endl; }
int Dice::roll() const { return rand() % sides_ + 1; }
Player::Player() { std::cout << "Игрок " << this << " создан" << std::endl; }
Player::~Player() { std::cout << "Игрок " << this << " удален" << std::endl; }
Player& Player::takeDice(std::vector<std::shared_ptr<Dice>>& dices, int index) {
if (dices.at(index)) {
dice_ = dices.at(index);
dices.at(index).reset();
std::cout << "Игрок взял кубик" << std::endl;
}
return *this;
}
Player& Player::rollDice() {
if (dice_) {
std::cout << "Игрок бросил кубик. Выпало: " << dice_->roll() << std::endl;
}
return *this;
}
Player& Player::putDice(std::vector<std::shared_ptr<Dice>>& dices, int index) {
if (dice_) {
dices.at(index) = dice_;
dice_.reset();
std::cout << "Игрок положил кубик обратно" << std::endl;
}
return *this;
}
int main() {
srand(static_cast<unsigned int>(time(0)));
std::vector<std::shared_ptr<Dice>> dices{
std::make_shared<Dice>(6),
std::make_shared<Dice>(12),
std::make_shared<Dice>(20)
};
Player player{};
std::cout << "\nБроски кубиков на столе:" << std::endl;
for (int i = 0; i < dices.size(); i++) {
std::cout << "Кубик " << i + 1 << ": " << dices.at(i)->roll() << std::endl;
}
std::cout << "\nИгрок берет первый кубик" << std::endl;
player.takeDice(dices, 0).rollDice().putDice(dices, 0);
std::cout << "\nИгрок берет второй кубик" << std::endl;
player.takeDice(dices, 1).rollDice().putDice(dices, 1);
std::cout << "\nИгрок берет третий кубик" << std::endl;
player.takeDice(dices, 2).rollDice().putDice(dices, 2);
return 0;
}