private GameDTO BuildGame(CreateGameResponse data)
 {
     try {
         return(new GameDTO()
         {
             Assignments = data.Assignments,
             TeamId = data.TeamId,
             DurationInMinutes = data.DurationInMinutes,
             Id = data.Id,
             IsCanceled = data.IsCanceled,
             IsTimeTbd = data.IsTimeTbd,
             Location = data.Location,
             LocationDetails = data.LocationDetails,
             MinutesToArriveEarly = data.MinutesToArriveEarly,
             Notes = data.Notes,
             NotForStandings = data.NotForStandings,
             Opponent = data.Opponent,
             StartDate = data.StartDate,
             Type = data.Type,
             Uniform = data.Uniform
         });
     }
     catch (Exception exc) {
         throw new InvalidOperationException("SchedulingService BuildGame()", exc);
     }
 }
Example #2
0
 private void HandleCreateGameResponse(CreateGameResponse response)
 {
     _logger.LogInformation("HandleCreateGameResponse Message={0}", response);
     if (OnCreateGameResponse != null)
     {
         OnCreateGameResponse(response);
     }
 }
Example #3
0
        private static CreateGameResponse GetCreateGameResponse(OperationResponse op)
        {
            var res = new CreateGameResponse();

            res.GameId  = GetParameter <string>(op, Operations.ParameterCode.GameId, true);
            res.Address = GetParameter <string>(op, Operations.ParameterCode.Address, true);
            return(res);
        }
        public CreateGameResponse CreateGame(CreateGameRequest request)
        {
            CreateGameResponse response = new CreateGameResponse {
                IsSuccess = true
            };

            return(response);
        }
Example #5
0
        public void JoinGame(CreateGameResponse gameInformation)
        {
            var stringData = JsonConvert.SerializeObject(gameInformation);
            var response   = _dataReceiver.SendRequest("join", GetAccountDictionary(), stringData);

            inGame  = true;
            gameKey = Decode <string>(response);
        }
Example #6
0
        public override void Execute()
        {
            Guid userID = (request as CreateGameRequest).UserID;
            Guid gameID = this.gameService.CreateGame(userID);

            response = new CreateGameResponse(gameID);

            SendMessage(userID); // Отправляем сформированный ответ
        }
Example #7
0
        protected static CreateGameResponse GetCreateGameResponse(OperationResponse op)
        {
            var res = new CreateGameResponse
            {
                GameId  = GetParameter <string>(op, ParameterCode.RoomName, true),
                Address = GetParameter <string>(op, ParameterCode.Address, true)
            };

            return(res);
        }
Example #8
0
        public CreateGameOutput CreateGame()
        {
            CreateGameResponse createGameResponse = DependencyResolver.Instance()
                                                    .GetInstanceOf <IService <CreateGameRequest, CreateGameResponse> >()
                                                    .Run(new CreateGameRequest());

            return(new CreateGameOutput()
            {
                id = createGameResponse.id,
                firstPlayer = createGameResponse.firstPlayer
            });
        }
        public Task <GameDTO> CreateNewGameAsync(ManageGameDataModel newGameDataModel, CancellationTokenSource cancellationTokenSource) =>
        Task <GameDTO> .Run(async() => {
            if (!CrossConnectivity.Current.IsConnected)
            {
                throw new InvalidOperationException(AppConsts.ERROR_INTERNET_CONNECTION);
            }

            GameDTO createdGame = null;

            CreateGameRequest createGameRequest = new CreateGameRequest()
            {
                AccessToken = GlobalSettings.Instance.UserProfile.AccesToken,
                Data        = newGameDataModel,
                Url         = GlobalSettings.Instance.Endpoints.ScheduleEndpoints.CreateNewGame
            };

            try {
                CreateGameResponse createGameResponse = await _requestProvider.PostAsync <CreateGameRequest, CreateGameResponse>(createGameRequest);

                if (createGameResponse != null)
                {
                    createdGame = BuildGame(createGameResponse);
                }
                else
                {
                    throw new InvalidOperationException(CREATE_NEW_GAME_COMMON_ERROR_MESSAGE);
                }
            }
            catch (HttpRequestExceptionEx exc) {
                CreateUpdateGameBadResponse createGameBadResponse = JsonConvert.DeserializeObject <CreateUpdateGameBadResponse>(exc.Message);

                string output = string.Format("{0} {1} {2} {3} {4} {5} {6}",
                                              createGameBadResponse.Errors?.FirstOrDefault(),
                                              createGameBadResponse.LocationId?.FirstOrDefault(),
                                              createGameBadResponse.OpponentId?.FirstOrDefault(),
                                              createGameBadResponse.TeamId?.FirstOrDefault(),
                                              createGameBadResponse.Type?.FirstOrDefault(),
                                              createGameBadResponse.DurationInMinutes?.FirstOrDefault(),
                                              createGameBadResponse.MinutesToArriveEarly?.FirstOrDefault());

                output = (string.IsNullOrWhiteSpace(output) || string.IsNullOrEmpty(output)) ? CREATE_NEW_GAME_COMMON_ERROR_MESSAGE : output.Trim();

                throw new InvalidOperationException(output);
            }
            catch (Exception exc) {
                Crashes.TrackError(exc);

                throw;
            }

            return(createdGame);
        }, cancellationTokenSource.Token);
        public async Task <IActionResult> CreateGame([FromBody] CreateGameRequest createGameRequest)
        {
            var user = await _UserLogic.GetUserAsync(HttpContext.User.Identity.Name).ConfigureAwait(false);

            var org = await _OrganizationLogic.GetOrganizationByUserAsync(user.UserId).ConfigureAwait(false);

            var game = await _GameLogic.CreateNewGameAsync(createGameRequest.GameVariantId, org.OrganizationId, user.UserId).ConfigureAwait(false);

            var response = new CreateGameResponse(game.GameId, game.AccessCode);


            return(Ok(response));
        }
Example #11
0
        private void Realm_OnCreateGameResponse(CreateGameResponse Packet)
        {
            CreateGameResult result = Packet.Result;

            if (result == CreateGameResult.Sucess)
            {
                this.Realm.WriteToLog("Game Created", Color.Green);
            }
            else
            {
                this.Realm.WriteToLog("Game Creation Failed, Reason: " + Packet.Result, Color.Red);
                this.FailToCreateGameEvent?.Invoke();
            }
        }
        public void CreateGameResponse_Correct_ObjectCreated()
        {
            // Arrange
            var createGameResponse = new CreateGameResponse
            {
                GameId       = this.gameGuid,
                IsSuccessful = this.isSuccessful
            };

            // Act
            // Assert
            Assert.Equal(this.gameGuid, createGameResponse.GameId);
            Assert.Equal(this.isSuccessful, createGameResponse.IsSuccessful);
        }
Example #13
0
        private void CreateGame(object sender, ResponseEventArgs e)
        {
            CreateGameResponse response = e.Response as CreateGameResponse;

            if (response != null)
            {
                if (response.IsSuccess)
                {
                    Switcher.SwitchPage(new Game(true));
                }
                else
                {
                    errorMessageTextBlock.Text = response.Error;
                }
            }
        }
        public async Task PostStartGameAsyncTest(string playerId, Lobby lobby, CreateGameResponse gameResponse)
        {
            // Arrange
            _lobbyRepo.Setup(r => r.GetAsync(It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(lobby)
            .Verifiable();
            _lobbyRepo.Setup(r => r.UpdateAsync(It.IsAny <string>(), It.IsAny <Lobby>(), It.IsAny <CancellationToken>()))
            .Returns(Task.CompletedTask)
            .Verifiable();
            _gameService
            .Setup(c => c.CreateGameAsync(
                       It.IsAny <protos.CreateGameRequest>(),
                       null,
                       null,
                       It.IsAny <CancellationToken>()
                       ))
            .Returns(new Grpc.Core.AsyncUnaryCall <CreateGameResponse>(
                         Task.FromResult(gameResponse),
                         null,
                         null,
                         null,
                         null
                         ))
            .Verifiable();
            _host.ConfigureServices(services =>
            {
                services.AddTransient <protos.GamesService.GamesServiceClient>(_ => _gameService.Object);
                services.AddTransient <ILobbyRepository>(_ => _lobbyRepo.Object);
            });
            // Act
            using var server = await _host.StartAsync();

            var client  = server.GetTestClient();
            var request = new HttpRequestMessage(HttpMethod.Post, $"{client.BaseAddress}{lobby.GameId}/start_game");

            request.Headers.Add("Cookie", $"player_id={playerId};");
            var response = await client.SendAsync(request, CancellationToken.None);

            var result = response.Content.ReadAsStringAsync();

            // Assert
            result.Should().NotBeNull();
            response.StatusCode.Should().Be(HttpStatusCode.NoContent);
            _lobbyRepo.Verify();
            _gameService.Verify();
        }
Example #15
0
        private void ProcessCreateGameRequest(CreateGameRequest request, int clientID)
        {
            Console.WriteLine($"Request to create room from player {clientID}");

            Player player = players.FirstOrDefault(p => p.ClientID == clientID);

            if (player == null)
            {
                Console.WriteLine($"Player {clientID} doesn't exist");
                return;
            }
            if (player.Match != null)
            {
                Console.WriteLine($"Player {clientID} is already in the game");

                DropRoom(player.Match);
            }

            string roomID = GetNewRoomNumber().ToString();

            player.Name = request.PlayerName;

            GameMatch match = new GameMatch();

            match.Player1      = player;
            match.RoomID       = roomID;
            match.CardPackName = request.CardPack;
            match.Difficulty   = request.Difficulty;
            match.Width        = request.Width;
            match.Height       = request.Height;

            match.IsRunning = false;
            player.Match    = match;

            matches.Add(match);

            Console.WriteLine($"Room {roomID} created");

            CreateGameResponse response = new CreateGameResponse();

            response.RoomID = roomID;
            Server.SendDataToClient(clientID, (int)DataTypes.CreateGameResponse, response);
        }
Example #16
0
        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
        {
            CreateGameResponse response = new CreateGameResponse();

            context.Read();
            int targetDepth = context.CurrentDepth;

            while (context.ReadAtDepth(targetDepth))
            {
                if (context.TestExpression("Game", targetDepth))
                {
                    var unmarshaller = GameDetailsUnmarshaller.Instance;
                    response.Game = unmarshaller.Unmarshall(context);
                    continue;
                }
            }

            return(response);
        }
Example #17
0
        void OnCreateGameResponse(CreateGameResponse response)
        {
            if (_request != null && response.RequestId == _request.RequestId)
            {
                ResetRequest();

                if (response.IsSuccess)
                {
                    CreatedGames.Add(response.Game);
                    _ = _localStorage.SetItemAsync(CREATED_GAMES_KEY, CreatedGames);
                    _ = ShowGamePlayer(response.Game);
                }
                else
                {
                    IsCreateGameFailedDialogVisible = true;
                    CreateGameFailedDialogMessage   = response.ErrorMessage;
                    InvokeStateChanged(EventArgs.Empty);
                }
            }
        }
Example #18
0
        public async Task CreateGameAsync(CreateGameRequest request, Func <CreateGameResponse, Task> responseHandler)
        {
            _logger.LogInformation("CreateGame: Request={}", request);
            var resp = new CreateGameResponse()
            {
                RequestId = request.RequestId
            };

            if (String.IsNullOrWhiteSpace(request.Game.GameName))
            {
                resp.ErrorMessage = "Invalid GameName";
                await responseHandler(resp);

                return;
            }

            var numPlayerGames = await _dbContext.GameStates
                                 .CountAsync(x => x.PlayerId == request.Player.PlayerId && !x.IsFinished);

            _logger.LogInformation($"numPlayerGames={numPlayerGames}");
            if (numPlayerGames > MAX_GAMES_PER_USER)
            {
                resp.ErrorMessage = "Too many active games for player";
                await responseHandler(resp);

                return;
            }

            var gameEngine  = new GameEngine(_loggerProvider, _dbContext, _cardRepo);
            var playerState = await gameEngine.CreateGameAsync(request);

            resp.IsSuccess = true;
            resp.Game      = gameEngine.GameState.Game;
            await responseHandler(resp);

            InvokeOnPlayerUpdate(MakePlayerUpdateResponse(playerState));
            InvokeOnGameUpdate(MakeGameUpdateResponse(gameEngine.GameState));
            InvokeOnTradeUpdate(null, MakeTradeUpdateResponse(gameEngine.GameState.GameId, gameEngine.GameState.Trades));
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="message"></param>
        private void HandleCreateGameResponse(CreateGameResponse message)
        {
            if (message.Status)
            {
                this.log.Info("GameServerClientActor - a new game has been created; guid={0}", message.Guid);

                // DeadWatch the game service.
                this.gameServiceRef = Sender;
                Context.Watch(this.gameServiceRef);

                //
                this.game.Guid = message.Guid;
                //
                this.game.OnGameCreated(message.Guid);

                // start the game
                this.gameServiceSelection.Tell(new Gomoku.Actors.StartGame(message.Guid));
            }
            else
            {
                this.log.Error("GameServerClientActor - failed to create a new game. Error: {0}", message.ErrorMessage);
            }
        }
Example #20
0
        public void ClientReceiveData(int type, object data)
        {
            switch ((DataTypes)type)
            {
            case DataTypes.StartGameResponse:
                StartGameResponse startGameResponse = (StartGameResponse)data;

                GameSettings.PlayersCount = 2;
                GameSettings.IsOnline     = true;
                GameSettings.PlayerID     = startGameResponse.PlayerID;
                GameSettings.CardPackage  = CardPackages.Packages[startGameResponse.CardPackName];
                GameSettings.Difficulty   = startGameResponse.Difficulty;
                GameSettings.FieldHeight  = startGameResponse.Field.GetLength(0);
                GameSettings.FieldWidth   = startGameResponse.Field.GetLength(1);
                GameSettings.FieldData    = startGameResponse.Field;
                GameSettings.PlayersNames = startGameResponse.PlayersNames;

                SceneManager.LoadScene("GameScene");
                break;

            case DataTypes.PlayersTurnData:
                GameManager.Instance.CardManager.Handle((PlayersTurnData)data);
                break;

            case DataTypes.CreateGameResponse:
                CreateGameResponse createGameResponse = (CreateGameResponse)data;

                MainMenuUIManager.Instance.RoomCreated(createGameResponse.RoomID);
                break;

            case DataTypes.CreateGameRequest:
            case DataTypes.JoinGameRequest:
            case DataTypes.RestartGameRequest:
            default:
                throw new ArgumentOutOfRangeException(nameof(type), type, null);
            }
        }
Example #21
0
        public async Task <IActionResult> CreateGame(CreateGameRequest createGameRequest)
        {
            if (!createGameRequest.WhitePlayer.HasValue)
            {
                createGameRequest.WhitePlayer = (int)_randomService.GetRandomColor();
            }

            var newGame = await _directChessRepository.AddGame(
                createGameRequest.Player1Name,
                createGameRequest.Player2Name,
                createGameRequest.WhitePlayer.Value);

            var response = new CreateGameResponse
            {
                GameKey     = newGame.GameKey,
                Player1Name = newGame.Player1Name,
                Player1Key  = newGame.Player1Key,
                Player2Name = newGame.Player2Name,
                Player2Key  = newGame.Player2Key,
                WhitePlayer = newGame.WhitePlayer
            };

            return(Ok(response));
        }
Example #22
0
 public void CreateGameCallBack(CreateGameResponse response)
 {
     syncContext.Post(new SendOrPostCallback(OnBroadcast <CreateGameResponse>), response);
 }
Example #23
0
        public async Task <APIGatewayProxyResponse> Post(APIGatewayProxyRequest request, ILambdaContext context)
        {
            CreateGameRequest    body         = JsonSerializer.Deserialize <CreateGameRequest>(request.Body);
            AmazonGameLiftClient amazonClient = new AmazonGameLiftClient(Amazon.RegionEndpoint.USEast1);

            ListAliasesRequest aliasReq = new ListAliasesRequest();

            aliasReq.Name = "WarshopServer";
            Alias aliasRes = (await amazonClient.ListAliasesAsync(aliasReq)).Aliases[0];
            DescribeAliasRequest describeAliasReq = new DescribeAliasRequest();

            describeAliasReq.AliasId = aliasRes.AliasId;
            string fleetId = (await amazonClient.DescribeAliasAsync(describeAliasReq.AliasId)).Alias.RoutingStrategy.FleetId;

            CreateGameSessionRequest req = new CreateGameSessionRequest();

            req.MaximumPlayerSessionCount = 2;
            req.FleetId   = fleetId;
            req.CreatorId = body.playerId;
            req.GameProperties.Add(new GameProperty()
            {
                Key   = "IsPrivate",
                Value = body.isPrivate.ToString()
            });
            req.GameProperties.Add(new GameProperty()
            {
                Key   = "Password",
                Value = body.password == null ? "" : body.password
            });
            try
            {
                CreateGameSessionResponse res = await amazonClient.CreateGameSessionAsync(req);

                GameSession gameSession = res.GameSession;
                int         retries     = 0;
                while (gameSession.Status.Equals(GameSessionStatus.ACTIVATING) && retries < 100)
                {
                    DescribeGameSessionsRequest describeReq = new DescribeGameSessionsRequest();
                    describeReq.GameSessionId = res.GameSession.GameSessionId;
                    gameSession = (await amazonClient.DescribeGameSessionsAsync(describeReq)).GameSessions[0];
                    retries++;
                }

                CreatePlayerSessionRequest playerSessionRequest = new CreatePlayerSessionRequest();
                playerSessionRequest.PlayerId      = body.playerId;
                playerSessionRequest.GameSessionId = gameSession.GameSessionId;
                CreatePlayerSessionResponse playerSessionResponse = await amazonClient.CreatePlayerSessionAsync(playerSessionRequest);

                CreateGameResponse response = new CreateGameResponse {
                    playerSessionId = playerSessionResponse.PlayerSession.PlayerSessionId,
                    ipAddress       = playerSessionResponse.PlayerSession.IpAddress,
                    port            = playerSessionResponse.PlayerSession.Port
                };
                return(new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.OK,
                    Body = JsonSerializer.Serialize(response),
                    Headers = new Dictionary <string, string> {
                        { "Content-Type", "application/json" }
                    }
                });
            }
            catch (NotFoundException e)
            {
                return(new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.NotFound,
                    Body = "Your game is out of date! Download the newest version\n" + e.Message,
                });
            }
            catch (FleetCapacityExceededException e)
            {
                return(new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.InternalServerError,
                    Body = "Our game servers are too busy right now, come back later!\n" + e.Message,
                });
            }
            catch (Exception e)
            {
                return(new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.InternalServerError,
                    Body = "An unexpected error occurred! Please notify the developers.\n" + e.Message,
                });
            }
        }