public TzaarClientLogic(PictureBox aPictureBox, GameMessage.Version versionMsg, GamePlayer playerNumber, GameBoard initialBoard)
 {
     this.pictureBox1 = aPictureBox;
     this.versionMsg = versionMsg;
     this.painter = new TzaarClientPainter(this.pictureBox1);
     this.playerNumber = playerNumber;
     this.painter.SetLocalPlayerColor((playerNumber == GamePlayer.One) ? TzaarColor.WHITE : TzaarColor.BLACK);
     this.logic = new TzaarLogic(new TzaarGameState((TzaarBoard)initialBoard));
 }
        public OwariClientLogic(PictureBox aPictureBox, GameMessage.Version versionMsg, GamePlayer playerNumber, GameBoard initialBoard)
        {
            this.playerNumber = 0;

            this.pictureBox1 = aPictureBox;
            this.versionMsg = versionMsg;

            // Make the configuration active.
            try
            {
                OwariConfiguration.SetConfig(versionMsg.GameConfig);
            }
            catch
            {
                Console.WriteLine("[OwariClientLogic] WARNING: unable to set configuration from string '" + versionMsg.GameConfig + "'");
            }

            this.painter = new OwariPainter(this.pictureBox1);
            this.logic = new OwariLogic();

            this.playerNumber = playerNumber;

            this.logic = new OwariLogic(new OwariGameState(initialBoard));
        }
            // Connect the client to the server, begin a new game, and make
            // the predefined moves for the game.
            private void ClientWork()
            {
                // Try to connect to the server.
                TcpClient client = new TcpClient(host.ToString(), port);

                // Create our reader/writer streams.
                NetworkStream ns = client.GetStream();

                StreamWriter sw = new StreamWriter(ns);
                StreamReader sr = new StreamReader(ns);

                // Immediately flush data we put into the write buffer.
                sw.AutoFlush = true;

                // First we should receive the Version message.
                string msg;
                try
                {
                    msg = sr.ReadLine();
                }
                catch
                {
                    return;
                }

                GameMessage.Version versionMsg = new GameMessage.Version(msg);

                Console.WriteLine(string.Format("Received Version Message: {0}", versionMsg));

                // Next we should receive our player number.
                try
                {
                    msg = sr.ReadLine();
                }
                catch
                {
                    return;
                }

                GamePlayer myPlayerNumber = new GameMessage.YourPlayerNumber(msg).PlayerNumber;

                Console.WriteLine(string.Format("[{0}] Received YourPlayerNumber: {1}", myPlayerNumber.ToString(), msg));

                // Next we receive the board state.
                try
                {
                    msg = sr.ReadLine();
                }
                catch
                {
                    return;
                }

                if (!GameMessage.IsBoardState(msg))
                    throw new Exception();

                Console.WriteLine(string.Format("[{0}] Received BoardState: {1}", myPlayerNumber.ToString(), GameMessage.GetMessageData(msg)));

                while (true)
                {
                    // Ok, now we wait for a message.
                    try
                    {
                        msg = sr.ReadLine();
                    }
                    catch
                    {
                        // Connection lost.
                        break;
                    }

                    // Connection lost.
                    if (msg == null)
                        break;

                    Console.WriteLine(string.Format("[{0}] Received Message: {1}", myPlayerNumber.ToString(), msg));

                    if (GameMessage.IsYourTurn(msg))
                    {
                        string nextMove;

                        try
                        {
                            nextMove = GetNextMove((myPlayerNumber == GamePlayer.One) ? 1 : 2);
                        }
                        catch
                        {
                            // Out of moves!
                            continue;
                        }

                        Thread.Sleep(DelayBetweenMoves);

                        // Send our next move.
                        Console.WriteLine(string.Format("[{0}] (move {1} of {2}) Sending Message: {3}", myPlayerNumber.ToString(), GetMoveNumber((myPlayerNumber == GamePlayer.One) ? 1 : 2), GetTotalMoves((myPlayerNumber == GamePlayer.One) ? 1 : 2), nextMove));
                        sw.WriteLine(nextMove);
                    }
                    else if (GameMessage.IsGameOver(msg))
                    {
                        break;
                    }
                }

                sr.Close();
                sw.Close();

                client.Close();
            }
        // NetworkServer callback handler.
        private void ServerEventHandler(NetworkServerEventInfo info)
        {
            if (this.shutDown)
                // We have been told to shut down, don't start any new
                // connections now.
                return;

            if (info.Code == NetworkServerEventInfoCode.ClientConnected)
            {
                if (this.client1Id == -1)
                    this.client1Id = info.ClientId;
                else
                    this.client2Id = info.ClientId;

                // Send a Version message to the client.
                string managerVersion = this.GetType().Assembly.GetName().Version.ToString();
                string gameName = GameChoice.CurrentGame.GetGameName();
                string gameVersion = this.logic.GetType().Assembly.GetName().Version.ToString();

                string gameConfig = "";
                if (GameChoice.GameSupportsConfiguration(GameChoice.CurrentGame))
                {
                    // Get the configuration string for this game.
                    gameConfig = ((IGameConfig)GameChoice.CurrentGame).GetConfigString();
                }

                GameMessage.Version versionMsg = new GameMessage.Version(managerVersion, gameName, gameVersion, gameConfig);
                this.server.SendMessage(info.ClientId, versionMsg);

                // Call the upper layer's event handler to give it the good
                // news!
                GameServerEventInfo tinfo = new GameServerEventInfo(GameServerEventInfoCode.ClientConnected, "Remote Client ( " + this.server.GetClientRemoteEndPoint(info.ClientId).ToString() + " ) has connected.");
                this.gameStateUpdateEventHandler(tinfo);

                if (++this.connectionCount == 2)
                    // This is connection 2!  That means the game can begin!
                    StartGame();
            }
            else if (info.Code == NetworkServerEventInfoCode.ClientDisconnected)
            {
                // A client has disconnected.

                this.connectionCount--;

                if (info.ClientId == this.client1Id)
                    this.client1Id = -1;
                else
                    this.client2Id = -1;

                if (this.gameInProgress)
                {
                    this.logic.GetGameState().SetGameOver(GetPlayerFromClientId(GetOtherClientId(info.ClientId)), GameOverCondition.OpponentDisconnected);
                    EndGame();
                }
            }
            else if (info.Code == NetworkServerEventInfoCode.LogMessage)
            {
                CallEvent_LogMessage(info.Message);
            }
            else if (info.Code == NetworkServerEventInfoCode.NewData)
            {
                // A new message has been received.

                // Split multiple messages up on carriage return and linefeed.
                string[] msgs = info.Message.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

                // Add each new message to the read queue.
                foreach (string m in msgs)
                    ProcessNewMessageFromClient(info.ClientId, m);
            }
            else if (info.Code == NetworkServerEventInfoCode.ServerStopped)
            {
                CallEvent_LogMessage("NetworkServer stopped.");
            }
            else
            {
                // Should never be here!
                new Exception("NetworkServer generated an event with code " + info.Code);
            }
        }
        private void NewMessageCallbackHandler(string msg)
        {
            // New data received.
            this.Display("> " + msg);

            if (GameMessage.IsVersion(msg))
            {
                // Version Info.
                GameMessage.Version versionMsg = new GameMessage.Version(msg);

                if (this.stateCode == ClientStateCode.WaitingForVersionMsg)
                {
                    this.stateCode = ClientStateCode.WaitingForYourPlayerNumberMsg;

                    this.Display("Received game manager Version message.");

                    this.Display("Version: " + versionMsg.ManagerVersion + " Game: '" + versionMsg.GameName + "' v" + versionMsg.GameVersion + " conf: '" + versionMsg.GameConfig + "'");

                    if (versionMsg.GameName.Equals("Owari"))
                        this.gameClient = new OwariClientInterface();
                    else if (versionMsg.GameName.Equals("Tzaar"))
                        this.gameClient = new TzaarClientInterface();
                    else
                    {
                        this.Display("The game is not supported by this client!");
                        return;
                    }

                    this.initVersionMsg = versionMsg;
                }
                else if (this.stateCode == ClientStateCode.WaitingForYourPlayerNumberMsg || this.stateCode == ClientStateCode.WaitingForBoardStateMsg || this.stateCode == ClientStateCode.WaitingForVersionMsg)
                {
                    this.Display("(0) I did not receive the correct initialization sequence!");
                    ResetClientSideGameState();
                }
                else
                {
                    this.Display("Ignoring unexpected Version message: " + this.initVersionMsg);
                }
            }
            else if (GameMessage.IsChat(msg))
            {
                // Chat message.
                GameMessage.Chat chatMsg = new GameMessage.Chat(msg);

                this.Display("Your Opponent Says: " + msg);
            }
            else if (GameMessage.IsBoardState(msg))
            {
                if (this.stateCode == ClientStateCode.WaitingForBoardStateMsg)
                {
                    this.stateCode = ClientStateCode.GameIsInProgress;

                    this.initBoardStateMsg = this.gameClient.GetNewBoardStateGameMessage(msg);

                    this.gameStateQueue.Clear();

                    this.gameClientLogic = this.gameClient.GetNewGameClientLogic(this.pictureBox1, this.initVersionMsg, this.playerNumber, this.initBoardStateMsg.Board);

                    this.gameStateQueue.Enqueue(this.gameClientLogic.GetGameState());
                }
                else if (InInitPhase())
                {
                    this.Display("Received BoardState out of sequence!");
                    ResetClientSideGameState();
                }
                else
                {
                    this.Display("Ignoring unexpected BoardState message.");
                }
            }
            else if (GameMessage.IsYourPlayerNumber(msg))
            {
                if (this.stateCode == ClientStateCode.WaitingForYourPlayerNumberMsg)
                {
                    this.stateCode = ClientStateCode.WaitingForBoardStateMsg;

                    this.playerNumber = new GameMessage.YourPlayerNumber(msg).PlayerNumber;
                }
                else if (InInitPhase())
                {
                    this.Display("Received YourPlayerNumber out of sequence!");
                    ResetClientSideGameState();
                }
                else
                {
                    this.Display("Ignoring unexpected YourPlayerNumber message.");
                }
            }
            else if (GameMessage.IsYourTurn(msg))
            {
                GameMessage.YourTurn yourTurnMsg = new GameMessage.YourTurn(msg);
                this.Display("Received YourTurn message.");
            }
            else if (GameMessage.IsMove(msg))
            {
                if (this.stateCode == ClientStateCode.GameIsInProgress)
                {
                    GameMessage.Move newMove = this.gameClient.GetNewMoveGameMessage(msg);

                    RecordMove(this.playerNumber, newMove);
                }
                else
                {
                    this.Display("Ignoring unexpected Move message.");
                }
            }
            else if (GameMessage.IsGameOver(msg))
            {
                if (this.stateCode == ClientStateCode.GameIsInProgress)
                {
                    GameMessage.GameOver gameOverMsg = new GameMessage.GameOver(msg);

                    EndGame(gameOverMsg.Condition);
                }
                else
                {
                    this.Display("Ignoring unexpected GameOver message.");
                }
            }
            else
            {
                this.Display("Unrecognized command: " + msg);
            }

            this.pictureBox1.Invalidate();
        }