89 lines
2.6 KiB
C++
89 lines
2.6 KiB
C++
|
//
|
||
|
// Created by caleb on 4/22/24.
|
||
|
//
|
||
|
|
||
|
#include <cstdio>
|
||
|
#include <iostream>
|
||
|
#include <boost/algorithm/string.hpp>
|
||
|
#include "DiceGame.h"
|
||
|
|
||
|
int computerScore = 0, playerScore = 0, playerRoundScore = 0, computerRoundScore = 0;
|
||
|
Die playerDie;
|
||
|
Die computerDie;
|
||
|
|
||
|
void DiceGame::diceGameLoop() {
|
||
|
std::string userInput;
|
||
|
bool gameLoop = true;
|
||
|
do {
|
||
|
std::printf("\033[2J\033[1;1H"); // special character sequence to clear the screen
|
||
|
userInput = ""; // clear string
|
||
|
do {
|
||
|
userInput = "";
|
||
|
std::printf("Score:\nComputer: %i\nPlayer: %i\nYour current round score: %i\n", computerScore, playerScore, playerRoundScore);
|
||
|
std::printf("Press r to roll, or press enter to continue.");
|
||
|
std::getline(std::cin, userInput);
|
||
|
boost::algorithm::to_lower(userInput);
|
||
|
std::printf("\033[2J\033[1;1H");
|
||
|
if (userInput == "r") {
|
||
|
userInput = "";
|
||
|
playerDie.roll();
|
||
|
playerRoundScore += playerDie.getValue();
|
||
|
}
|
||
|
} while (!userInput.empty());
|
||
|
computerDie.roll();
|
||
|
computerRoundScore += computerDie.getValue();
|
||
|
if (isRoundOver()) {
|
||
|
std::printf("%s\nWould you like to play again? (y/n)", determineScore().c_str());
|
||
|
playerRoundScore = 0, computerRoundScore = 0; // reset round scores
|
||
|
std::getline(std::cin, userInput);
|
||
|
boost::algorithm::to_lower(userInput);
|
||
|
std::printf("\033[2J\033[1;1H");
|
||
|
if (userInput == "n") {
|
||
|
gameLoop = false;
|
||
|
}
|
||
|
}
|
||
|
} while (gameLoop);
|
||
|
std::printf("Final Scores:\nComputer: %i\nPlayer: %i\n", computerScore, playerScore);
|
||
|
std::printf("Press enter to continue.\n");
|
||
|
std::cin.ignore();
|
||
|
}
|
||
|
|
||
|
std::string DiceGame::determineScore() {
|
||
|
std::string response;
|
||
|
switch (compareScores()) {
|
||
|
case -1:
|
||
|
response.append("You won! ");
|
||
|
playerScore++;
|
||
|
break;
|
||
|
case 0:
|
||
|
response.append("It's a tie. ");
|
||
|
break;
|
||
|
case 1:
|
||
|
response.append("The computer won. ");
|
||
|
computerScore++;
|
||
|
break;
|
||
|
}
|
||
|
return response;
|
||
|
}
|
||
|
|
||
|
int DiceGame::compareScores() {
|
||
|
if (playerRoundScore > computerRoundScore) {
|
||
|
return -1;
|
||
|
}
|
||
|
if (playerRoundScore == computerRoundScore) {
|
||
|
return 0;
|
||
|
}
|
||
|
if (playerRoundScore < computerRoundScore) {
|
||
|
return 1;
|
||
|
}
|
||
|
// code should never reach here
|
||
|
return -69420;
|
||
|
}
|
||
|
|
||
|
bool DiceGame::isRoundOver() {
|
||
|
if (playerRoundScore >= 21 || computerRoundScore >= 21) {
|
||
|
return true;
|
||
|
}
|
||
|
return false;
|
||
|
}
|