Exemplo n.º 1
0
        public async Task SendRoomDataToGameServerAsync(BattleRoyaleMatchModel model)
        {
            if (string.IsNullOrEmpty(model.GameServerIp))
            {
                throw new Exception("При отправке данных на игровой сервер ip не указан");
            }

            string serverIp = $"http://{model.GameServerIp}:{Globals.DefaultGameServerHttpPort}";

            byte[] roomData = ZeroFormatterSerializer.Serialize(model);
            Console.WriteLine($"Отправка данных на игровой сервер по ip = {serverIp} количество байт = {roomData.Length}");
            HttpContent content  = new ByteArrayContent(roomData);
            var         response = await httpClient.PostAsync(serverIp, content);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                Console.WriteLine("Получен ответ от игрового сервера. Статус = \"успешно\" ");
                byte[] responseData = await response.Content.ReadAsByteArrayAsync();

                var r = ZeroFormatterSerializer.Deserialize <GameRoomValidationResult>(responseData);
                Console.WriteLine($"ResultEnum = {r.ResultEnum}");
            }
            else
            {
                //TODO убрать после тестирования
                throw new Exception($"Брошено исключение при отправке запроса игровому серверу. " +
                                    $"Код = {response.StatusCode}");
            }
        }
Exemplo n.º 2
0
        public async Task <bool> TryCreateMatch(int numberOfPlayersInMatch, bool botsCanBeUsed)
        {
            GameUnits gameUnits = new GameUnits();

            List <MatchEntryRequest> requests = battleRoyaleQueueSingletonService
                                                .TakeMatchEntryRequests(numberOfPlayersInMatch);

            //Достать игроков из очереди без извлечения
            gameUnits.Players = requests
                                .Select(request => request.GetPlayerModel())
                                .ToList();

            //Если нужно дополнить ботами
            if (0 < gameUnits.Players.Count && gameUnits.Players.Count < numberOfPlayersInMatch)
            {
                //и можно дополнить ботами
                if (botsCanBeUsed)
                {
                    //дополнить
                    int numberOfBots = numberOfPlayersInMatch - gameUnits.Players.Count;
                    gameUnits.Bots = battleRoyaleBotFactoryService.CreateBotModels(numberOfBots);
                }
            }

            //Достаточно игроков?
            if (gameUnits.Players.Count + gameUnits.Bots?.Count != numberOfPlayersInMatch)
            {
                return(false);
            }

            // Присвоить временные id игрокам на один бой
            List <ushort> playerTmpIds = PlayerTemporaryIdsFactory.Create(gameUnits.Players.Count);

            for (int i = 0; i < gameUnits.Players.Count; i++)
            {
                PlayerModel playerModel = gameUnits.Players[i];
                playerModel.TemporaryId = playerTmpIds[i];
            }

            //На каком сервере будет запускаться матч?
            MatchRoutingData matchRoutingData = matchRoutingDataService.GetMatchRoutingData();

            //Сделать запись об матче в БД
            Match match = await matchDbWriterService
                          .WriteAsync(matchRoutingData, requests.Select(request => request.GetWarshipId()).ToList());

            //Создать объект с информацией про бой
            BattleRoyaleMatchModel matchModel = BattleRoyaleMatchDataFactory.Create(gameUnits, match);

            //Добавить игроков в таблицу тех кто в бою
            unfinishedMatchesService.AddPlayersToMatch(matchModel);

            //Извлечь игроков из очереди
            battleRoyaleQueue.RemovePlayersFromQueue(matchModel.GameUnits.Players);

            //Сообщить на гейм сервер
            await gameServerNegotiatorService.SendRoomDataToGameServerAsync(matchModel);

            return(true);
        }
Exemplo n.º 3
0
 public MapInitSystem(Contexts contexts, BattleRoyaleMatchModel matchModel, UdpSendUtils udpSendUtils, out PositionChunks chunks)
 {
     gameContext       = contexts.game;
     this.matchModel   = matchModel;
     this.udpSendUtils = udpSendUtils;
     chunks            = new PositionChunks(mapIntRadius);
 }
Exemplo n.º 4
0
 //TODO добавить чеки
 public void AddPlayersToMatch(BattleRoyaleMatchModel matchModel)
 {
     matches.TryAdd(matchModel.MatchId, matchModel);
     foreach (var playerInfoForMatch in matchModel.GameUnits.Players)
     {
         playersInMatches.TryAdd(playerInfoForMatch.ServiceId, matchModel.MatchId);
     }
 }
        public GameRoomValidationResult Validate(BattleRoyaleMatchModel matchModel)
        {
            CheckPrefabNames(matchModel);
            bool matchWithThisIdDoesNotExist = CheckMatchId(matchModel);
            var  result = GetValidationResult(matchWithThisIdDoesNotExist);

            return(result);
        }
Exemplo n.º 6
0
        public MapInitializeSystem(Contexts contexts, BattleRoyaleMatchModel matchModel,
                                   WarshipsCharacteristicsStorage warshipsCharacteristicsStorage)
        {
            this.matchModel = matchModel;
            var warshipEntityFactory = new WarshipEntityFactory(contexts);

            warshipsSpawnerBuilder = new WarshipsSpawnerBuilder(new WarshipSpawnerHelper(warshipEntityFactory,
                                                                                         warshipsCharacteristicsStorage));
            asteroidsSpawnerBuilder = new AsteroidsSpawnerBuilder(new AsteroidSpawnerHelper(contexts));
        }
        public void AddMatch(BattleRoyaleMatchModel matchModel)
        {
            ConcurrentDictionary <ushort, IPEndPoint> playersIpAddresses = new ConcurrentDictionary <ushort, IPEndPoint>();

            foreach (PlayerModel playerModel in matchModel.GameUnits.Players)
            {
                playersIpAddresses.TryAdd(playerModel.TemporaryId, new IPEndPoint(1, 1));
            }
            ipEndPoints.TryAdd(matchModel.MatchId, playersIpAddresses);
        }
Exemplo n.º 8
0
        //ECS
        public void ConfigureSystems(BattleRoyaleMatchModel matchModelArg, UdpSendUtils udpSendUtils,
                                     IpAddressesStorage ipAddressesStorage)
        {
            log.Info($"Создание нового матча {nameof(matchId)} {matchId}");

            //TODO это нужно убрать в отдельный класс
            Dictionary <int, (int playerId, ViewTypeId type)> possibleKillersInfo = new Dictionary <int, (int playerId, ViewTypeId type)>();


            // var test = new BattleRoyalePlayerModelFactory().Create(matchModelArg).Select(model=>model.AccountId);
            // playersIds = new HashSet<int>(test);

            contexts = ContextsPool.GetContexts();
            contexts.SubscribeId();
            TryEnableDebug();

            playerDeathHandler = new PlayerDeathHandler(matchmakerNotifier, udpSendUtils, ipAddressesStorage);
            var playersViewAreas = new PlayersViewAreas(matchModelArg.GameUnits.Players.Count);

            systems = new Entitas.Systems()
                      .Add(new MapInitSystem(contexts, matchModelArg, udpSendUtils, out var chunks))
                      .Add(new ViewAreasInitSystem(contexts, playersViewAreas))
                      // .Add(new TestEndMatchSystem(contexts))
                      .Add(new PlayerMovementHandlerSystem(contexts))
                      .Add(new PlayerAttackHandlerSystem(contexts))
                      .Add(new PlayerAbilityHandlerSystem(contexts))
                      .Add(new ParentsSystems(contexts))
                      .Add(new AISystems(contexts))
                      .Add(new MovementSystems(contexts))
                      .Add(new GlobalTransformSystem(contexts))
                      .Add(new ShootingSystems(contexts))
                      .Add(new UpdatePositionChunksSystem(contexts, chunks))
                      .Add(new CollisionSystems(contexts, chunks))
                      .Add(new EffectsSystems(contexts))
                      .Add(new TimeSystems(contexts))
                      .Add(new UpdatePossibleKillersSystem(contexts, possibleKillersInfo))

                      .Add(new PlayerExitSystem(contexts, matchModelArg.MatchId, playerDeathHandler, matchRemover))
                      .Add(new FinishMatchSystem(contexts, matchRemover, matchId))
                      .Add(new NetworkKillsSenderSystem(contexts, possibleKillersInfo, matchModelArg.MatchId, playerDeathHandler, udpSendUtils))

                      .Add(new DestroySystems(contexts))
                      // .Add(new MatchDebugSenderSystem(contexts, matchModelArg.MatchId, udpSendUtils))
                      .Add(new NetworkSenderSystems(contexts, matchModelArg.MatchId, udpSendUtils, playersViewAreas))
                      .Add(new MovingCheckerSystem(contexts))

                      .Add(new DeleteSystem(contexts))
                      .Add(new InputDeletingSystem(contexts))
                      .Add(new GameDeletingSystem(contexts))
            ;

            systems.ActivateReactiveSystems();
            systems.Initialize();
            gameStartTime = DateTime.UtcNow;
        }
Exemplo n.º 9
0
        private async Task HandleNextRequest()
        {
            try
            {
                HttpListenerContext context = await listener.GetContextAsync();

                HttpListenerRequest request = context.Request;
                if (request.Url.AbsolutePath != "/")
                {
                    return;
                }
                Stream inputStream = request.InputStream;
                byte[] data;

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    await inputStream.CopyToAsync(memoryStream);

                    data = memoryStream.ToArray();
                }

                inputStream.Close();

                BattleRoyaleMatchModel   matchModel = ZeroFormatterSerializer.Deserialize <BattleRoyaleMatchModel>(data);
                GameRoomValidationResult result     = matchModelMessageHandler.Handle(matchModel);


                if (result != null)
                {
                    if (result.ResultEnum != GameRoomValidationResultEnum.Ok)
                    {
                        Log.Error(result.ResultEnum);
                    }
                    byte[] responseData = ZeroFormatterSerializer.Serialize(result);
                    context.Response.StatusCode      = 200;
                    context.Response.ContentLength64 = responseData.Length;
                    await context.Response.OutputStream.WriteAsync(responseData, 0, responseData.Length);

                    context.Response.OutputStream.Close();
                }
                else
                {
                    throw new Exception("Отправка пустого ответа гейм матчеру запрещена.");
                }
            }
            catch (Exception e)
            {
                Log.Error("Брошено исключение при обработке http запроса " + e.Message);
            }
        }
        public Match Create(BattleRoyaleMatchModel matchModel)
        {
            ipAddressesStorage.AddMatch(matchModel);

            foreach (ushort playerId in matchModel.GameUnits.Players.Select(player => player.TemporaryId))
            {
                messageIdFactory.AddPlayer(matchModel.MatchId, playerId);
                messagesPackIdFactory.AddPlayer(matchModel.MatchId, playerId);
            }

            Match match = new Match(matchModel.MatchId, matchRemover, matchmakerNotifier);

            match.ConfigureSystems(matchModel, udpSendUtils, ipAddressesStorage);
            return(match);
        }
        public GameRoomValidationResult Handle(BattleRoyaleMatchModel matchModel)
        {
            GameRoomValidationResult result = matchModelValidator.Validate(matchModel);

            if (result?.ResultEnum == GameRoomValidationResultEnum.Ok)
            {
                AddMatchToQueue(matchModel);
            }
            else
            {
                string errMessage = "От матчмейкера пришло сообщение о создании матча, но оно было " +
                                    $"отклонено. result?.ResultEnum = {result?.ResultEnum.ToString()}";
                throw new Exception(errMessage);
            }
            return(result);
        }
Exemplo n.º 12
0
        public static BattleRoyaleMatchModel Create(GameUnits gameUnits, Match match)
        {
            BattleRoyaleMatchModel result = new BattleRoyaleMatchModel
            {
                MatchId        = match.Id,
                GameServerIp   = match.GameServerIp,
                GameServerPort = match.GameServerUdpPort,
                GameUnits      = new GameUnits
                {
                    Bots    = gameUnits.Bots,
                    Players = gameUnits.Players
                }
            };

            return(result);
        }
        private void CheckPrefabNames(BattleRoyaleMatchModel matchModel)
        {
            foreach (PlayerModel playerModel in matchModel.GameUnits.Players)
            {
                if (string.IsNullOrWhiteSpace(playerModel.WarshipName))
                {
                    throw new ArgumentException(nameof(playerModel.WarshipName));
                }
            }

            foreach (BotModel botModel in matchModel.GameUnits.Bots)
            {
                if (string.IsNullOrWhiteSpace(botModel.WarshipName))
                {
                    throw new ArgumentException(nameof(botModel.WarshipName));
                }
            }
        }
Exemplo n.º 14
0
        public async Task <MatchmakerResponse> GetMatchDataAsync(string playerServiceId, int warshipId)
        {
            //Данные для окна ожидания боя
            MatchmakerResponse response = new MatchmakerResponse
            {
                NumberOfPlayersInQueue   = queueSingletonService.GetNumberOfPlayers(),
                NumberOfPlayersInBattles = unfinishedMatchesService.GetNumberOfPlayersInBattles()
            };

            //Игрок в очереди?
            if (queueSingletonService.Contains(playerServiceId))
            {
                Console.WriteLine("PlayerInQueue");
                response.PlayerInQueue = true;
                return(response);
            }
            //Игрок в бою?
            else if (unfinishedMatchesService.IsPlayerInMatch(playerServiceId))
            {
                Console.WriteLine("IsPlayerInMatch");
                BattleRoyaleMatchModel matchModel = unfinishedMatchesService.GetMatchModel(playerServiceId);
                response.PlayerInBattle = true;
                response.MatchModel     = new BattleRoyaleClientMatchModel(matchModel, playerServiceId);
                return(response);
            }
            //Добавить в очередь
            else
            {
                Console.WriteLine("TryEnqueuePlayerAsync");
                bool success = await queueExtenderService.TryEnqueuePlayerAsync(playerServiceId, warshipId);

                if (!success)
                {
                    throw new Exception("Не удалось добавить игрока в очередь.");
                }
                response.PlayerHasJustBeenRegistered = true;
                return(response);
            }
        }
Exemplo n.º 15
0
        public void SpawnPlayers(BattleRoyaleMatchModel matchModel)
        {
            Vector3 position = new Vector3();

#if ONE_PLAYER
            var firstPlayer = matchModel.GameUnits.Players.First();
            CreateWarship(position, firstPlayer.TemporaryId, firstPlayer.AccountId, ViewTypeEnum.StarSparrow1);
#else
            foreach (var player in matchModel.GameUnits.Players)
            {
                warshipSpawnerHelper.CreateWarship(position, player.TemporaryId, player.AccountId,
                                                   ViewTypeEnum.StarSparrow1);
                position = position + new Vector3(15, 0, 15);
            }

            foreach (var botModel in matchModel.GameUnits.Bots)
            {
                ServerGameEntity bot = warshipSpawnerHelper.CreateWarship(position, botModel.TemporaryId, -botModel.TemporaryId,
                                                                          ViewTypeEnum.StarSparrow1);
                bot.isBot = true;
                position  = position + new Vector3(15, 0, 15);
            }
#endif
        }
 private void AddMatchToQueue(BattleRoyaleMatchModel matchModel)
 {
     matchCreator.AddMatchToCreationQueue(matchModel);
 }
#pragma warning disable 1998
        public async Task SendRoomDataToGameServerAsync(BattleRoyaleMatchModel model)
#pragma warning restore 1998
        {
            Console.WriteLine(nameof(SendRoomDataToGameServerAsync));
        }
Exemplo n.º 18
0
 public void AddMatchToCreationQueue(BattleRoyaleMatchModel battleRoyaleMatchModel)
 {
     matchesToCreate.Enqueue(battleRoyaleMatchModel);
 }
 private bool CheckMatchId(BattleRoyaleMatchModel matchModel)
 {
     return(!matchStorage.HasMatch(matchModel.MatchId));
 }