public GameSquare(int x, int y, GameBoard board) { this.X = x; this.Y = y; this.Board = board; CurrentStatus = new SquareStatus(); }
private void BeginSimulatedTimer(TimeSpan Interval) { while (!StopTimerRequest.Token.IsCancellationRequested) { // ForEach square in Squares foreach (var sqr in Squares) { // Before doing anything just check if the game is ending and needs to break this loop if (StopTimerRequest.Token.IsCancellationRequested) { break; } var dtRef = DateTime.Now; var lockRef = sqr.CurrentStatus.LockingTime; if (lockRef.Ticks < dtRef.Ticks) { if (sqr.CurrentStatus.IsLocked) { if (Monitor.IsEntered(sqr.CurrentStatus)) { sqr.CurrentStatus.IsLocked = false; Monitor.Exit(sqr.CurrentStatus); //Debug.WriteLine($"Timer thread released lock on ({sqr.X}, {sqr.Y})"); } } else { // Don't sit here and wait for a square if it's locked by a player // Just skip it if (Monitor.TryEnter(sqr.CurrentStatus)) { sqr.CurrentStatus.IsLocked = true; //Debug.WriteLine($"Timer thread acquired lock on ({sqr.X}, {sqr.Y})"); } else { //Debug.WriteLine($"Timer thread couldn't acquire lock on ({sqr.X}, {sqr.Y})"); } } // Generate a new period of wait before the locking changes sqr.CurrentStatus.LockingTime = dtRef.Add(TimeSpan.FromMilliseconds(SquareStatus.GenerateNextDelay())); } } Thread.Sleep(Interval.Milliseconds); } foreach (var sqr in Squares) { // Run through and if a lock is being held let it go if (Monitor.IsEntered(sqr.CurrentStatus)) { //Debug.WriteLine($"Timer thread released lock on ({sqr.X}, {sqr.Y})"); Monitor.Exit(sqr.CurrentStatus); } } // End the Game State GameIsRunning = false; // Compile list of player threads and wait for them to finish var playerThreads = Teams.SelectMany(x => x.Players).Select(x => x.MovementThread).ToArray(); Task.WaitAll(playerThreads); // Trigger score tally and fire event to GUI NotifyGameEnded(); }