using System; using System.Collections.Generic; using System.Linq; namespace PingPong.GameEngine.Components { public class Score { #region Members /// /// The score history. /// private Stack history; /// /// The score value. /// private Lazy value; #endregion #region Properties /// /// Gets the score value. /// /// /// The value. /// public int Value { get { return this.value.Value; } private set { history.Push(this.Value); this.value = new Lazy(() => value); } } /// /// Gets the increment expression. /// /// /// The increment expression. /// public string IncrementExpression { get; private set; } /// /// Gets the decrement expression. /// /// /// The decrement expression. /// public string DecrementExpression { get; private set; } #endregion #region Constructors /// /// Initializes a new instance of the class. /// public Score() { this.history = new Stack(); this.value = new Lazy(() => default(int)); } #endregion #region Methods /// /// Sets the increment expression. /// /// /// The increment expression. /// /// /// Expression. /// public Score SetIncrementExpression(string expression) { if (string.IsNullOrWhiteSpace(expression)) { throw new ArgumentNullException("expression"); } this.IncrementExpression = expression; return this; } /// /// Sets the decrement expression. /// /// /// The decrement expression. /// /// /// Expression. /// public Score SetDecrementExpression(string expression) { this.DecrementExpression = expression; return this; } /// /// Sets the score. /// /// /// The score. /// /// /// Expression. /// public Score SetScore(string expression) { if (string.IsNullOrWhiteSpace(expression)) { throw new ArgumentNullException("expression"); } Engine.ExpressionParser.Interpret(expression); this.Value = Engine.ExpressionParser.Int; return this; } /// /// Sets the score. /// /// /// The score. /// /// /// Score. /// public Score SetScore(int score) { this.Value = score; return this; } /// /// Increment this instance. /// public int Increment() { if (string.IsNullOrWhiteSpace(this.IncrementExpression)) { throw new NotImplementedException("No increment expression set."); } Engine.ExpressionParser.Interpret(this.IncrementExpression); this.Value += Engine.ExpressionParser.Int; return this.Value; } /// /// Decrement this instance. /// public int Decrement() { if (string.IsNullOrWhiteSpace(this.DecrementExpression)) { Reverse(); } else { throw new NotImplementedException("No decrement expression set."); } Engine.ExpressionParser.Interpret(this.DecrementExpression); this.Value += Engine.ExpressionParser.Int; return this.Value; } /// /// Reverse the last action. /// public int Reverse() { if (!this.history.Any()) { throw new ArgumentOutOfRangeException("No history found."); } this.value = new Lazy(() => this.history.Pop()); return this.Value; } #endregion #region Operators /// /// Score. /// public static implicit operator int(Score score) { return score.Value; } #endregion } }