예제 #1
0
        /// <summary>
        /// Получить доступные игры и отправить.
        /// </summary>
        private static void GiveGames(Socket handler)
        {
            try
            {
                List <BeginGame> bg = new List <BeginGame>();

                lock (sessions)
                {
                    foreach (var game in sessions)
                    {
                        if (!game.GameStarted)
                        {
                            bg.Add(new BeginGame()
                            {
                                GameName = game.SessionName, PlayerName = game.Player1?.Name ?? game.Player2.Name
                            });
                        }
                    }
                }

                string data     = AnswerHandler.GetGamesMessage(bg);
                byte[] byteData = Encoding.UTF8.GetBytes(data);
                Console.WriteLine($"Sending: {data}");
                handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                handler?.Close();
            }
        }
예제 #2
0
        /// <summary>
        /// Отправить Ок.
        /// </summary>
        private static void SendOk(Socket handler, bool closeSocket = false)
        {
            string data = AnswerHandler.GetOkMessage();

            byte[] byteData = Encoding.UTF8.GetBytes(data);
            Console.WriteLine($"Sending: {data}");

            if (closeSocket)
            {
                handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
            }
            else
            {
                handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallbackSaveConnect), handler);
            }
        }
예제 #3
0
        /// <summary>
        /// Задать игровое поле.
        /// </summary>
        /// <param name="gameField">Игровое поле.</param>
        private static void SetField(Socket handler, GameField gameField)
        {
            GameSession game         = null;
            Player      player       = null;
            Player      secondPlayer = null;

            try
            {
                lock (sessions)
                {
                    game = sessions.Find(x => x.Player1?.IPEndPoint == handler.RemoteEndPoint || x.Player2?.IPEndPoint == handler.RemoteEndPoint);
                }

                player       = game.Player1.IPEndPoint == handler.RemoteEndPoint ? game.Player1 : game.Player2;
                secondPlayer = game.Player1.IPEndPoint != handler.RemoteEndPoint ? game.Player1 : game.Player2;

                player.GameField = gameField;

                // если второй игрок не присоединился
                if (secondPlayer == null)
                {
                    string message   = AnswerHandler.AwaitSecondPlayer();
                    byte[] data      = Encoding.UTF8.GetBytes(message);
                    int    bytesSent = player.PlayerSocket.Send(data, 0, data.Length, SocketFlags.None);
                    Console.WriteLine($"Sent {bytesSent} bytes to {player.PlayerSocket.RemoteEndPoint.ToString()}.\n{message}\n");
                }
                // если оба игрока готовы.
                else if (secondPlayer.GameField != null && player.GameField != null)
                {
                    string message   = AnswerHandler.GetGameReadyMessage(true);
                    byte[] data      = Encoding.UTF8.GetBytes(message);
                    int    bytesSent = secondPlayer.PlayerSocket.Send(data, 0, data.Length, SocketFlags.None);
                    Console.WriteLine($"Sent {bytesSent} bytes to {secondPlayer.PlayerSocket.RemoteEndPoint.ToString()}.\n{message}\n");


                    message   = AnswerHandler.GetGameReadyMessage(false);
                    data      = Encoding.UTF8.GetBytes(message);
                    bytesSent = player.PlayerSocket.Send(data, 0, data.Length, SocketFlags.None);
                    Console.WriteLine($"Sent {bytesSent} bytes to {player.PlayerSocket.RemoteEndPoint.ToString()}.\n{message}\n");

                    game.WhoseTurn = secondPlayer;

                    // Ждать выстрела от player.
                    BeginReceive(secondPlayer.PlayerSocket);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);

                lock (sessions)
                {
                    sessions.Remove(game);
                }

                if (game != null)
                {
                    player?.PlayerSocket?.Close();
                    secondPlayer?.PlayerSocket?.Close();
                }

                handler?.Close();
            }
        }
예제 #4
0
        /// <summary>
        /// Произведен выстрел.
        /// </summary>
        /// <param name="shotLocation">Позиция выстрела.</param>
        private static void Shot(Socket handler, Location shotLocation)
        {
            GameSession session = null;

            lock (sessions)
            {
                session = sessions.Find(x => x.Player1?.IPEndPoint == handler.RemoteEndPoint || x.Player2?.IPEndPoint == handler.RemoteEndPoint);
            }

            if (session == null)
            {
                handler?.Shutdown(SocketShutdown.Both);
                handler?.Close();
            }

            try
            {
                if (!session.CanGo)
                {
                    BeginReceive(handler);
                    return;
                }

                Player player1 = session.Player1.IPEndPoint == handler.RemoteEndPoint ? session.Player1 : session.Player2;
                Player player2 = session.Player1.IPEndPoint != handler.RemoteEndPoint ? session.Player1 : session.Player2;

                if (session.WhoseTurn.IPEndPoint != handler.RemoteEndPoint)
                {
                    return;
                }

                session.CanGo = false;

                Ship ship = player2.GameField.Shot(shotLocation);

                string message   = AnswerHandler.GetShotResultMessage(ship, shotLocation);
                byte[] data      = Encoding.UTF8.GetBytes(message);
                int    bytesSent = player1.PlayerSocket.Send(data, 0, data.Length, SocketFlags.None);
                Console.WriteLine($"Sent {bytesSent} bytes to {player1.PlayerSocket.RemoteEndPoint.ToString()}.\n{message}\n\n");

                message   = AnswerHandler.GetShotResultMessage(shotLocation);
                data      = null;
                data      = Encoding.UTF8.GetBytes(message);
                bytesSent = player2.PlayerSocket.Send(data, 0, data.Length, SocketFlags.None);
                Console.WriteLine($"Sent {bytesSent} bytes to {player2.PlayerSocket.RemoteEndPoint.ToString()}.\n{message}\n\n");

                if (player2.GameField.IsGameOver)
                {
                    player1?.PlayerSocket?.Shutdown(SocketShutdown.Both);
                    player1?.PlayerSocket?.Close();
                    player2?.PlayerSocket?.Shutdown(SocketShutdown.Both);
                    player2?.PlayerSocket?.Close();

                    lock (sessions)
                    {
                        sessions.Remove(session);
                    }
                    return;
                }

                if (ship == null)
                {
                    session.WhoseTurn = player2;
                    BeginReceive(player2.PlayerSocket);
                }
                else
                {
                    session.WhoseTurn = player1;
                    BeginReceive(player1.PlayerSocket);
                }

                session.CanGo = true;
            }
            catch (Exception e)
            {
                lock (sessions)
                {
                    sessions.Remove(session);
                }

                session?.Player1?.PlayerSocket?.Close();
                session?.Player2?.PlayerSocket?.Close();
                handler?.Close();
                Console.WriteLine(e);
            }
        }