#include "Game.h" /* Helpers */ double getRandomBetween(int a, int b) { if (a > b) { int temp = b; b = a; a = temp; } srand(time(NULL)); return a + (double(rand()) / RAND_MAX) * (b - a); } /* Private */ void Game::copyFrom(const Game& other) { this->caseCount = other.caseCount; cases = new GameCase[this->caseCount]; for (int i = 0; i < this->caseCount; i++) cases[i] = other.cases[i]; } void Game::free() { delete[] cases; } TurnResult Game::turn(double& bet) const { std::cout << "Available commands: " << std::endl; for (int i = 0; i < this->caseCount; i++) cases[i].print(); std::cout << "Enter command: "; char buffer; std::cin >> buffer; bool result = false; int caseI = 0; while (cases[caseI].get_comm() != buffer && caseI < this->caseCount) caseI++; if (caseI < this->caseCount) result = cases[caseI].exec(bet); else std::cout << "Invalid command! "; if (result) { std::cout << "You won this turn. Your current bet is " << bet << std::endl << "Do you want to continue? [y/n] "; std::cin >> buffer; return (buffer == 'N' || buffer == 'n') ? Win : Continue; } else if (bet > 0) { std::cout << "Do you want to quit? [y/n] "; std::cin >> buffer; return (buffer == 'N' || buffer == 'n') ? Continue : Quit; } return Lost; } /* Public */ Game::Game(const GameCase* cases, unsigned casesCount) { this->cases = new GameCase[casesCount]; for (int i = 0; i < casesCount; i++) this->cases[i] = cases[i]; this->caseCount = casesCount; } Game::Game(const Game& other) { this->copyFrom(other); } Game& Game::operator=(const Game& other) { if (this != &other) { this->free(); this->copyFrom(other); } return *this; } Game::~Game() { this->free(); } void Game::play(Player& player) const { if (player.get_age() < 18) { std::cout << "You must be at least 18 years old to play." << std::endl; return; } std::cout << "Password: "; char password[2048]; std::cin >> password; std::cout << "Your current balance: " << player.get_balance() << std::endl << "Enter bet: "; double bet; std::cin >> bet; player.deductFromBalance(password, bet); TurnResult result = Continue; while (result == Continue) result = this->turn(bet); switch (result) { case Win: std::cout << "You've won! " << bet << " will be added to your account." << std::endl; player.addToBalance(password, bet); break; case Quit: // If your bet drops to 0, you'll automatically lose, so you'll never quit with bet of 0. std::cout << "Quitting game. " << bet << " will be added to your account." << std::endl; player.addToBalance(password, bet); break; default: std::cout << "You lost! Your balance is " << player.get_balance() << "." << std::endl; break; } }