Kata Tennis C++ / src / Game.cpp

#include "Game.h"

#include <iostream>
#include "Player.h"
using namespace std;

Game::Game(Player * player1, Player * player2)
{
	this->player1 = player1;
	this->player2 = player2;

	scores.push_back("Love");
	scores.push_back("Fifteen");
	scores.push_back("Thirty");
	scores.push_back("Forty");

	state = INITIAL;
}

Game::~Game()
{
	delete player1;
	delete player2;
}

void Game::pointTo(Player * player)
{
	if(not gameStateIsGameOver())
	{
		player->winPoint();

		updateState();
	}
}

void Game::updateState()
{
	if(thereIsDeuce())
	{
		state = DEUCE;
	}
	else if(gameStateIsDeuce())
	{
		state = ADVANTAGE;
	}
	else if(isGameOver())
	{
		state = GAME_OVER;
	}
}

std::string Game::score() const
{
	if(gameStateIsDeuce())
	{
		return "Deuce";
	}
	else if(gameStateIsGameOver())
	{
		return victoryMessage();
	}
	else if(gameStateIsAdvantage())
	{
		return advantageMessage();
	}

	return computeScore(player1) + "-" + computeScore(player2);
}

std::string Game::victoryMessage() const
{
	return whoWon()->getName() + " won!";
}

Player * Game::whoWon() const
{
	if(playerWon(player1))
		return player1;

	return player2;
}

std::string Game::advantageMessage() const
{
	std::string message = "Advantage for ";

	if(player1->getPoints() > player2->getPoints())
		return message + player1->getName();

	return message + player2->getName();
}

std::string Game::computeScore(Player * player) const
{
	return scores[player->getPoints()];
}

bool Game::thereIsDeuce() const
{
	return playersAreTight() and player1->getPoints() >= 3;
}

bool Game::playersAreTight() const
{
	return player1->getPoints() == player2->getPoints();
}

bool Game::gameStateIsGameOver() const
{
	return state == GAME_OVER;
}

bool Game::isGameOver() const
{
	return playerWon(player1) or playerWon(player2);
}

bool Game::playerWon(Player * player) const
{
	if(state == INITIAL)
		return player->wonMoreThanThreePoints();

	return player->getPoints() > getOtherPlayer(player)->getPoints();
}

Player * Game::getOtherPlayer(Player * player) const
{
	if(player == player1)
		return player2;

	return player1;
}

bool Game::gameStateIsDeuce() const
{
	return state == DEUCE;
}

bool Game::gameStateIsAdvantage() const
{
	return state == ADVANTAGE;
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.