using System;
using System.Linq;
using NJDOTNET.Trivia.Exceptions;
namespace NJDOTNET.Trivia
{
///
/// GameController is a base implementation of an IGameController
/// which takes care of most of the basic/typical behaviors.
///
public abstract class GameController : IGameController
{
protected readonly Game game;
private GameStatus _Status = GameStatus.PlayerRegistration;
///
/// Gets or sets the current game status.
///
/// The current game status.
public virtual GameStatus Status
{
get { return _Status; }
internal set { _Status = value; }
}
protected virtual bool CanStart
{
get
{
// Make sure the game is not already in progress
// and that we've got some players registered.
// (there's nothing more boring than a game without players...)
return
Status != GameStatus.InProgress
&& game.Players.Count() > 0;
}
}
protected virtual bool CanEnd
{
get { return Status == GameStatus.InProgress; }
}
public event EventHandler> OnNextQuestion;
public event EventHandler> OnGameStarted;
public event EventHandler> OnGameEnded;
protected GameController(Game game)
{
this.game = game;
}
public GameSummary GenerateGameSummary()
{
return new GameSummary(game);
}
public void AddPlayer(Player player)
{
if (Status == GameStatus.PlayerRegistration)
game.AddPlayer(player);
else
throw new PlayerRegistrationClosedException();
}
public virtual void Start()
{
// If we're not in the right state to start right now,
// boot 'em out (and not very nicely)
if (!CanStart)
throw new InvalidStateException();
Status = GameStatus.InProgress;
if (OnGameStarted != null)
OnGameStarted(this, new EventArgs(game));
}
public virtual void End()
{
// If we're not in the right state to end right now,
// boot 'em out (and not very nicely)
if (!CanEnd)
throw new InvalidStateException();
Status = GameStatus.Ended;
if (OnGameEnded != null)
OnGameEnded(this, new EventArgs(GenerateGameSummary()));
}
protected virtual void TriggerNextQuestion(Question question)
{
if (OnNextQuestion != null)
OnNextQuestion(this, new EventArgs(question));
}
}
}