Esempio n. 1
0
        private static void OnPlayerPlaceShip(Packet recv)
        {
            if (gameStarted)
            {
                return;
            }

            var player = GetPlayerForPeerID(recv.GetSender());

            if (player == null)
            {
                return;
            }

            using (var instream = recv.GetStream()) {
                // reassemble the ship's settings from the stream data
                var type = (ShipType)instream.ReadByte();
                var ori  = (ShipOrientation)instream.ReadByte();
                var pos  = new BoardPosition(instream.ReadByte(), instream.ReadByte());
                var ship = new Ship(type)
                {
                    Position    = pos,
                    Orientation = ori
                };

                bool acceptable = false;
                if (player.Board.CanPlaceShip(ship))
                {
                    // the player sent a valid request, so honor it
                    player.Board.PlaceShip(type, ship);
                    acceptable = true;
                }

                // send out the response, with the ship type in the payload
                using (var ms = new MemoryStream()) {
                    using (var outstream = new BinaryWriter(ms, Encoding.UTF8)) {
                        outstream.Write((byte)type);
                        outstream.Write(acceptable);

                        using (var packet = new Packet((PacketCommand)GameCommand.PlaceShip, ms.ToArray()))
                            peer.Send(packet, player.NetworkID, PacketOptions.RELIABLE);
                    }
                }
            }

            // all ships placed?
            bool p1done = player1.Board.Ships.Count == 5;
            bool p2done = player2.Board.Ships.Count == 5;

            if (p1done && p2done)
            {
                // instruct both players that the game is now starting
                using (var packet = new Packet((PacketCommand)GameCommand.BeginGame, EmptyPayload)) {
                    peer.Send(packet, player1.NetworkID, PacketOptions.RELIABLE);
                    peer.Send(packet, player2.NetworkID, PacketOptions.RELIABLE);
                }

                whoseTurn   = rng.Next() % 2 == 0;
                gameStarted = true;
                BeginNextTurn();
            }
        }