Example #1
0
        public void SeekMatch(string displayName)
        {
            lock (WaitingPlayers)
            {
                this.Locker.WaitOne();

                if (this.CurrentMatch != null)
                {
                    this.Locker.Release();
                    return;
                }

                this.DisplayName = displayName;

                while (WaitingPlayers.Count > 0)
                {
                    Player waitingPlayer = WaitingPlayers.Peek();

                    waitingPlayer.Locker.WaitOne();

                    try
                    {
                        waitingPlayer.InvokeStartMatch(this.DisplayName, this.ClientId, false);
                    }
                    catch (Exception)
                    {
                        WaitingPlayers.Dequeue();
                        waitingPlayer.Locker.Release();

                        continue;
                    }

                    try
                    {
                        this.InvokeStartMatch(waitingPlayer.DisplayName, waitingPlayer.ClientId, true);
                    }
                    catch (Exception)
                    {
                        try
                        {
                            waitingPlayer.InvokeCancelMatch();
                        }
                        catch (Exception)
                        {
                            WaitingPlayers.Dequeue();
                        }
                        waitingPlayer.Locker.Release();

                        this.Locker.Release();
                        return;
                    }

                    WaitingPlayers.Dequeue();

                    this.CurrentMatch = GameMaster.NewMatch(waitingPlayer, this);
                    this.Locker.Release();

                    waitingPlayer.CurrentMatch = this.CurrentMatch;
                    waitingPlayer.Locker.Release();

                    Console.WriteLine("Game #" + CurrentMatch.Id + " has started between players " +
                                      waitingPlayer.ClientId + " and " + this.ClientId);
                    Console.WriteLine();

                    return;
                }

                WaitingPlayers.Enqueue(this);

                this.Locker.Release();
            }

            Console.WriteLine("Player " + this.ClientId + " is waiting for an opponent");
            Console.WriteLine();
        }