Exemplo n.º 1
0
        public async Task <LobbyModel> CreateAsync([NotNull] string playerServiceId)
        {
            AccountDbDto account = await accountFacadeService.ReadOrCreateAccountAsync(playerServiceId);

            if (account == null)
            {
                throw new NullReferenceException(nameof(account));
            }

            RewardsThatHaveNotBeenShown rewardsThatHaveNotBeenShown = await notShownRewardsReaderService
                                                                      .GetNotShownRewardAndMarkAsRead(playerServiceId);

            WarshipRatingScaleModel warshipRatingScaleModel = warshipRatingScale.GetWarshipRatingScaleModel();

            if (warshipRatingScaleModel == null)
            {
                throw new Exception($"{nameof(warshipRatingScaleModel)} was null");
            }

            AccountDto accountDto = accountMapperService.Map(account);
            LobbyModel lobbyModel = new LobbyModel
            {
                AccountDto = accountDto,
                RewardsThatHaveNotBeenShown = rewardsThatHaveNotBeenShown,
                WarshipRatingScaleModel     = warshipRatingScaleModel
            };

            lobbyModel.BundleVersion = bundleVersionService.GetBundleVersion();

            return(lobbyModel);
        }
Exemplo n.º 2
0
        public async Task <ActionResult <string> > Create([FromForm] string playerServiceId, [FromForm] string username)
        {
            Console.WriteLine($"{nameof(playerServiceId)} {playerServiceId}");
            if (string.IsNullOrEmpty(playerServiceId))
            {
                return(BadRequest());
            }

            LobbyModel lobbyModel = await lobbyModelFacadeService.CreateAsync(playerServiceId);

            foreach (var warshipDto in lobbyModel.AccountDto.Warships)
            {
                if (warshipDto.PowerLevel == 0)
                {
                    throw new Exception("Нулевой уровень корабля");
                }
            }

            //обновить ник
            if (lobbyModel.AccountDto.Username != username && username != null)
            {
                var validationResult = await usernameChangingService.ChangeUsername(playerServiceId, username);

                if (validationResult == UsernameValidationResultEnum.Ok)
                {
                    lobbyModel.AccountDto.Username = username;
                }
            }

            Console.WriteLine("Всё нормально");
            return(lobbyModel.SerializeToBase64String());
        }
        public static void Initialize(LobbyModel lobby)
        {
            // Load all the spawn points and place the players into them
            GamesHandler.LoadSpawnPoints(lobby);

            // Make all the players load the map from the track
            GamesHandler.LoadTrackForPlayers(lobby);
        }
Exemplo n.º 4
0
        public static void StartCountdown(int lobby)
        {
            // Add the countdown for the lobby
            LobbyModel lobbyModel = lobbyList[lobby];

            lobbyModel.Countdown = Constants.COUNTDOWN_TIME;

            // Start the countdown timer
            countdown = new Timer(CountdownTimer, lobby, 0, 1000);
        }
Exemplo n.º 5
0
        private static SnakeModel newFruitLocation(LobbyModel lobby)
        {
            Random rand = new Random();
            int    x    = rand.Next(0, 24);
            int    y    = rand.Next(0, 24);

            return(new SnakeModel {
                X = x, Y = y
            });
        }
Exemplo n.º 6
0
 public ActionResult JoinLobby(LobbyModel model)
 {
     if (!ModelState.IsValid)
     {
         return(View(model));
     }
     else
     {
         return(RedirectToAction("Lobby", model));
     }
 }
Exemplo n.º 7
0
        private void SetData(LobbyModel lobbyModel)
        {
            //Заблокировать ui, если версия игры старая
            updateGameVersionMenuSwitcher.CheckBundleVersion(lobbyModel.BundleVersion);

            //Отнять от данных аккаунта значения, которые будут начислены с анимацией
            lobbyEcsController.SetLobbyModel(lobbyModel);

            //Установить данные для шкалы рейтинга кораблей
            WarshipRatingScaleStorage.Instance.SetValue(lobbyModel.WarshipRatingScaleModel);
        }
Exemplo n.º 8
0
        private static bool checkWin(LobbyModel lobby, bool isHost)
        {
            bool       hasLost = false;
            SnakeModel head;

            if (isHost)
            {
                head = lobby.HostSnake;
                if (head.Compare(lobby.MemberSnake))
                {
                    hasLost = true;
                }
                foreach (var point in lobby.MemBody)
                {
                    if (head.Compare(point))
                    {
                        hasLost = true;
                    }
                }
                foreach (var point in lobby.MemWalls)
                {
                    if (head.Compare(point))
                    {
                        hasLost = true;
                    }
                }
            }
            else
            {
                head = lobby.MemberSnake;
                if (head.Compare(lobby.HostSnake))
                {
                    hasLost = true;
                }
                foreach (var point in lobby.HostBody)
                {
                    if (head.Compare(point))
                    {
                        hasLost = true;
                    }
                }
                foreach (var point in lobby.HostWalls)
                {
                    if (head.Compare(point))
                    {
                        hasLost = true;
                    }
                }
            }


            return(hasLost);
        }
Exemplo n.º 9
0
 public ActionResult JoinHost(LobbyModel sentLobby)
 {
     for (int i = 0; i < lobbies.Count; i++)
     {
         var lobby = lobbies[i];
         if (sentLobby.Host.Equals(lobby.Host))
         {
             lobbies[i] = sentLobby;
             return(Json(lobbies[i].Host, JsonRequestBehavior.AllowGet));
         }
     }
     return(Json("could not find host", JsonRequestBehavior.AllowGet));
 }
Exemplo n.º 10
0
 private void TryUpdateAccountModel()
 {
     if (lobbyModelDownloadingTask.IsCompleted)
     {
         if (lobbyModelDownloadingTask.IsCanceled)
         {
             return;
         }
         if (!lobbyModelDownloadingTask.IsFaulted)
         {
             LobbyModel lobbyModel = lobbyModelDownloadingTask.Result;
             if (lobbyModel != null)
             {
                 log.Info("Установка новой модели аккаунта");
                 lobbyEcsController.SetLobbyModel(lobbyModel);
             }
             else
             {
                 log.Error("Модель лобби пуста");
             }
         }
         else
         {
             log.Error("Новая модель лобби не успела скачаться пока показывалась красивая анимация");
         }
     }
     else
     {
         log.Info("Новая модель аккаунта не успела скачаться.");
         lobbyModelDownloadingTask.ContinueWith(task =>
         {
             if (task.Status == TaskStatus.RanToCompletion)
             {
                 LobbyModel lobbyModel = task.Result;
                 if (lobbyModel != null)
                 {
                     lobbyEcsController.SetLobbyModel(lobbyModel);
                 }
                 else
                 {
                     log.Error("Пришла пустая модель лобби.");
                 }
             }
             else
             {
                 log.Error("Не удалось скачать модель лобби.");
             }
         });
     }
 }
Exemplo n.º 11
0
        public void PlayerLoadedMapEvent(Client player)
        {
            // Get the lobby where the player is and add a player to the count
            LobbyModel lobby = lobbyList.First(l => l.Players.Contains(player));

            lobby.PlayersReady++;

            if (lobby.PlayersReady == lobby.Players.Count)
            {
                // Start the game
                lobby.PlayersReady = 0;
                StartCountdown(lobby.Id);
            }
        }
Exemplo n.º 12
0
        public static async void LoadTrackForPlayers(LobbyModel lobby)
        {
            // Load the items for the selected track
            List <MapModel> trackObjects = await DatabaseHandler.LoadTrackMap(lobby.Track).ConfigureAwait(false);

            if (trackObjects.Count > 0)
            {
                // Get the JSON string of the objects
                string trackObjectsJson = NAPI.Util.ToJson(trackObjects);

                // Load the track for all the players
                lobby.Players.ForEach(p => p.TriggerEvent("LoadTrack", lobby.Id, trackObjectsJson));
            }
        }
Exemplo n.º 13
0
    public void ApplyModel(LobbyModel model)
    {
        if (Model != null)
        {
            Model.OnChanged -= OnModelChanged;
            Model            = null;

            RemoveCoroutine();
        }

        Model = model;

        if (Model != null)
        {
            Model.OnChanged += OnModelChanged;
            OnModelChanged();
        }
    }
Exemplo n.º 14
0
        public void SetLobbyModel(LobbyModel lobbyModel)
        {
            AccountDto accountDto = lobbyModel.AccountDto.Subtract(lobbyModel.RewardsThatHaveNotBeenShown);

            foreach (WarshipDto accountDataWarship in accountDto.Warships)
            {
                log.Info(accountDataWarship.GetCurrentSkinName());
            }

            //Установить данные для анимации начисления наград
            movingAwardsMainSystem.CreateAwards(lobbyModel.RewardsThatHaveNotBeenShown);

            //Установить данные аккаунта
            accountDtoComponentsCreatorSystem.SetAccountDto(accountDto);
            PlayerIdStorage.AccountId = accountDto.AccountId;

            warshipsCount = lobbyModel.AccountDto.Warships.Count;
        }
Exemplo n.º 15
0
        public static async void LoadSpawnPoints(LobbyModel lobby)
        {
            // Load the items for the selected track
            List <SpawnPointModel> spawnPoints = await DatabaseHandler.LoadTrackSpawns(lobby.Track).ConfigureAwait(false);

            // Initialize the random seems
            Random random = new Random();

            foreach (Client player in lobby.Players)
            {
                // Get a random spawn point
                SpawnPointModel spawn = spawnPoints[random.Next(spawnPoints.Count)];

                // Set the player into the spawn
                player.Position  = spawn.Position;
                player.Rotation  = spawn.Rotation;
                player.Dimension = (uint)lobby.Id;

                // Remove the spawn point
                spawnPoints.Remove(spawn);
            }
        }
Exemplo n.º 16
0
        private static void CountdownTimer(object parameter)
        {
            // Get the lobby from the identifier
            int        lobbyId    = Convert.ToInt32(parameter);
            LobbyModel lobbyModel = lobbyList[lobbyId];

            if (lobbyModel.Countdown != -2)
            {
                // Check if it's the first launch
                bool justJoined = lobbyModel.Countdown == Constants.COUNTDOWN_TIME;

                // Show the counter for the players
                lobbyModel.Players.ForEach(c => c.TriggerEvent("ShowCountdown", lobbyModel.Countdown, justJoined));
                lobbyModel.Countdown--;

                return;
            }

            // Start the game
            countdown.Dispose();
            countdown = null;
        }
Exemplo n.º 17
0
        public void GameSelection(Client player, int game)
        {
            //Destroy current CEF Browser, camera and return radar
            player.TriggerEvent("DestroyConnectionBrowser");
            player.TriggerEvent("DestroyCam");

            // Create the lobby
            LobbyModel lobby = new LobbyModel()
            {
                Id        = 0,
                Countdown = 0,
                Players   = new List <Client>(),
                Track     = 1
            };

            // Add the lobby to the list
            GamesHandler.lobbyList.Add(lobby);

            // Switch to the game chosen
            // Derby = 1
            switch (game)
            {
            case 1:
                // Iniciate Derby
                Games.Derby.Initializer.StartDerby(player);
                GamesHandler.lobbyList[0].Players.Add(player);
                GamesHandler.StartCountdown(GamesHandler.lobbyList[0].Id);
                break;

            case 2:
                Games.CVH.Initializer.StartCVH(player);
                break;

            case 3:
                SumoStartupHandler.Initialize(lobby);
                break;
            }
        }
Exemplo n.º 18
0
        public ActionResult KeyPush(KeyModel model)
        {
            LobbyModel lobby          = lobbies[getIndex(model.Username)];
            SnakeModel hostPieceAdded = null;
            SnakeModel memPieceAdded  = null;

            if (lobby.lost != "no")
            {
                return(Json(lobby, JsonRequestBehavior.AllowGet));
            }
            int  x;
            int  y;
            bool isHost = false;

            if (lobby.Host == model.Username)
            {
                isHost = true;
                x      = lobby.HostSnake.X;
                y      = lobby.HostSnake.Y;
            }
            else
            {
                x = lobby.MemberSnake.X;
                y = lobby.MemberSnake.Y;
            }

            string key = model.Key;

            if (model.Drop)
            {
                if (isHost)
                {
                    lobby.HostWalls.AddRange(lobby.HostBody);
                    lobby.HostBody = new List <SnakeModel>();
                }
                else
                {
                    lobby.MemWalls.AddRange(lobby.MemBody);
                    lobby.HostBody = new List <SnakeModel>();
                }
            }

            if (key.CompareTo("w") == 0)
            {
                y = y - 1;
                if (y < 0)
                {
                    y = 0;
                }
            }
            else if (key.CompareTo("a") == 0)
            {
                x = x - 1;
                if (x < 0)
                {
                    x = 0;
                }
            }
            else if (key.CompareTo("s") == 0)
            {
                y = y + 1;
                if (y > MAXHEIGHT)
                {
                    y = MAXHEIGHT;
                }
            }
            else if (key.CompareTo("d") == 0)
            {
                x += 1;
                if (x > MAXWIDTH)
                {
                    x = MAXWIDTH;
                }
            }
            if (isHost)
            {
                lobby.HostBody.Add(new SnakeModel
                {
                    X = lobby.HostSnake.X,
                    Y = lobby.HostSnake.Y
                });
                hostPieceAdded = lobby.HostSnake;
                lobby.HostBody.RemoveAt(0);
                lobby.HostSnake.X = x;
                lobby.HostSnake.Y = y;
                lobby.Board[x, y] = "hHead";
            }
            else
            {
                lobby.MemBody.Add(new SnakeModel
                {
                    X = lobby.MemberSnake.X,
                    Y = lobby.MemberSnake.Y
                });
                memPieceAdded = lobby.MemberSnake;
                lobby.MemBody.RemoveAt(0);
                lobby.MemberSnake.X = x;
                lobby.MemberSnake.Y = y;
                lobby.Board[x, y]   = "hHead";
            }
            if (lobby.MemberSnake.X == lobby.Fruit.X && lobby.MemberSnake.Y == lobby.Fruit.Y)
            {
                lobby.MemSize += 1;
                lobby.MemBody.Add(memPieceAdded);
                lobby.Fruit = newFruitLocation(lobby);
            }
            else if (lobby.HostSnake.X == lobby.Fruit.X && lobby.HostSnake.Y == lobby.Fruit.Y)
            {
                lobby.HostSize += 1;
                lobby.HostBody.Add(hostPieceAdded);
                lobby.Fruit = newFruitLocation(lobby);
            }

            if (checkWin(lobby, isHost))
            {
                if (isHost)
                {
                    lobby.lost = lobby.Member;
                }
                else
                {
                    lobby.lost = lobby.Host;
                }
            }

            lobbies[getIndex(model.Username)] = lobby;
            return(Json(lobby, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 19
0
 public IActionResult Lobby(LobbyModel model)
 {
     return(View(model));
 }
Exemplo n.º 20
0
        public IActionResult LobbyHost()
        {
            LobbyModel model = new LobbyModel();

            return(View(model));
        }
Exemplo n.º 21
0
 public void SetLobby(LobbyModel lobby)
 {
     Lobby = lobby;
 }
Exemplo n.º 22
0
        public async Task <LobbyModel> Load(CancellationToken cts)
        {
            log.Info("Старт скачивания модели аккаунта");
            HttpClient httpClient    = new HttpClient();
            int        attemptNumber = 0;

            while (true)
            {
                log.Info("Номер попытки " + attemptNumber++);
                await Task.Delay(1000, cts);

                try
                {
                    if (!PlayerIdStorage.TryGetServiceId(out string playerServiceId))
                    {
                        log.Warn("Не удалось получить id игрока");
                        continue;
                    }

                    if (!PlayerIdStorage.TryGetUsername(out string username))
                    {
                        log.Warn("Не удалось получить username игрока");
                        continue;
                    }

                    HttpResponseMessage response;
                    using (MultipartFormDataContent formData = new MultipartFormDataContent())
                    {
                        formData.Add(new StringContent(playerServiceId), nameof(playerServiceId));
                        formData.Add(new StringContent(username), nameof(username));
                        response = await httpClient.PostAsync(NetworkGlobals.InitializeLobbyUrl, formData, cts);
                    }


                    if (!response.IsSuccessStatusCode)
                    {
                        log.Warn("Статус ответа " + response.StatusCode);
                        continue;
                    }

                    string base64String = await response.Content.ReadAsStringAsync();

                    if (base64String.Length == 0)
                    {
                        log.Warn("Ответ пуст ");
                        continue;
                    }

                    byte[] data = Convert.FromBase64String(base64String);
                    log.Info("Длина ответа в байтах " + data.Length);
                    LobbyModel result = ZeroFormatterSerializer.Deserialize <LobbyModel>(data);
                    log.Info("Десериализация прошла нормально");
                    return(result);
                }
                catch (TaskCanceledException e)
                {
                    log.Warn("Task был отменён");
                }
                catch (Exception e)
                {
                    UiSoundsManager.Instance().PlayError();
                    log.Error("Упало при скачивании модели " + e.Message + " " + e.StackTrace);
                }
            }
        }
Exemplo n.º 23
0
 public LobbyController()
 {
     lobbyModel = new LobbyModel();
 }