private void SetupGameProperties(LitePeer peer, JoinGameRequest createRequest, Hashtable gameProperties, ref SendParameters sendParameters, out byte?newMaxPlayer, out bool?newIsOpen, out bool?newIsVisible, out object[] newLobbyProperties) { newMaxPlayer = null; newIsOpen = null; newIsVisible = null; newLobbyProperties = null; // special treatment for game and actor properties sent by AS3/Flash or JSON clients var protocol = peer.Protocol.ProtocolType; if (protocol == ProtocolType.Amf3V152 || protocol == ProtocolType.Json) { Utilities.ConvertAs3WellKnownPropertyKeys(createRequest.GameProperties, createRequest.ActorProperties); } // try to parse build in properties for the first actor (creator of the game) if (this.Actors.Count == 0) { if (gameProperties != null && gameProperties.Count > 0) { if (!TryParseDefaultProperties(peer, createRequest, gameProperties, sendParameters, out newMaxPlayer, out newIsOpen, out newIsVisible, out newLobbyProperties)) { return; } } } return; }
public bool TryAddExpectedUsers(HiveGame hiveGame, JoinGameRequest joinRequest) { if (joinRequest.AddUsers == null) { return(true); } if (!this.CheckMayAddSlots(joinRequest.AddUsers, hiveGame.MaxPlayers)) { return(false); } var added = new List <string>(); foreach (var userName in joinRequest.AddUsers) { switch (this.TryAddExpectedUser(hiveGame, userName)) { case SLOT_ADD_FAIL: return(false); case SLOT_ADD_OK: added.Add(userName); break; } } joinRequest.AddUsers = added.Count > 0 ? added.ToArray() : null; return(true); }
public async Task JoinGame(JoinGameRequest request) { var connectionId = Context.ConnectionId; async Task InvokeOnJoinGameResponse(JoinGameResponse resp) { if (resp.IsSuccess) { await _gameService.EventManager.AddConnection(request.GameId, request.Player.PlayerId, Context.ConnectionId); } _logger.LogInformation("Sending Response: {}", resp); await Clients.Caller.SendAsync("OnJoinGameResponse", resp); } try { await _gameService.JoinGameAsync(request, InvokeOnJoinGameResponse); } catch (Exception ex) { _logger.LogError(ex, nameof(JoinGame)); await InvokeOnJoinGameResponse(new JoinGameResponse() { ErrorMessage = $"{ex.GetType()}: {ex.Message}" }); } }
public GameResponse JoinGame([FromUri] JoinGameRequest request) { Game game = (Game)MemoryCacher.GetValue(request.GameId); MemoryCacher.Replace(game.Id.ToString(), game, DateTimeOffset.UtcNow.AddHours(1)); return(new GameResponse(game)); }
/// <summary> /// Handles the <see cref = "JoinGameRequest" /> to enter a <see cref = "HiveGame" />. /// This method removes the peer from any previously joined room, finds the room intended for join /// and enqueues the operation for it to handle. /// </summary> /// <param name = "operationRequest"> /// The operation request to handle. /// </param> /// <param name = "sendParameters"> /// The send Parameters. /// </param> protected virtual void HandleJoinOperation(OperationRequest operationRequest, SendParameters sendParameters) { if (this.JoinStage != JoinStages.Connected) { this.OnWrongOperationStage(operationRequest, sendParameters); return; } // create join operation var joinRequest = new JoinGameRequest(this.Protocol, operationRequest); if (this.ValidateOperation(joinRequest, sendParameters) == false) { return; } // remove peer from current game this.RemovePeerFromCurrentRoom(LeaveReason.SwitchRoom, "eventual switch from other room."); // get a game reference from the game cache // the game will be created by the cache if it does not exists already var pluginName = joinRequest.Plugins != null && joinRequest.Plugins.Length > 0 ? joinRequest.Plugins[0] : String.Empty; var gameReference = this.GetRoomReference(joinRequest, pluginName); // save the game reference in the peers state this.RoomReference = gameReference; // finally enqueue the operation into game queue gameReference.Room.EnqueueOperation(this, operationRequest, sendParameters); }
public async Task <ActionResult <GameResponse> > JoinGame(string gameCode, JoinGameRequest joinGameRequest) { if (string.IsNullOrEmpty(gameCode)) { return(BadRequest()); } if (string.IsNullOrEmpty(joinGameRequest.PlayerName)) { return(BadRequest()); } var player = await _gameService.CreatePlayer(joinGameRequest.PlayerName); var gameResponse = await _gameService.JoinGame(gameCode, player); if (gameResponse == null) { return(NotFound()); } await SendGameUpdateToClients(gameResponse.GameId, player.Id); Response.Headers.Add("X-CurrentPlayerToken", player.Token.ToString()); return(gameResponse); }
public async Task <JoinGameResult> JoinGame(JoinGameRequest joinGameRequest, string baseApiUrl) { using (var client = new HttpClient()) { var stringifiedObject = _serialization.SerializeToHttpStringContent(joinGameRequest); var uri = new Uri(baseApiUrl + "/game-invitations"); using (var response = await client.PostAsync(uri, stringifiedObject)) { using (var content = response.Content) { var data = await content.ReadAsStringAsync(); Debug.WriteLine($"POST request sent to '{uri.AbsolutePath}' with data: '{await stringifiedObject.ReadAsStringAsync()}'."); Debug.WriteLine($"Got response: '{data}'"); if (data != null && response.IsSuccessStatusCode) { return(_serialization.DeserializeObject <JoinGameResult>(data)); } var requestDataJson = await stringifiedObject.ReadAsStringAsync(); throw new ApiException(uri, HttpMethod.Post, requestDataJson, response.StatusCode, data); } } } }
public JoinGameResponse JoinGame(string gameId, short expectedResult = ErrorCode.Ok) { var joinRequest = new JoinGameRequest { GameId = gameId }; return(this.JoinGame(joinRequest, expectedResult)); }
public void JoinGame(Guid id) { var request = new JoinGameRequest(curUser, id); curGame = id; // TODO: Если добавим в пакет ответа, то это убрать client.Send(AbstractRequest.ToBytes(request)); }
public JoinGameResponse JoinGame(string gameId, Operations.ErrorCode expectedResult) { var joinRequest = new JoinGameRequest { GameId = gameId }; return(JoinGame(joinRequest, expectedResult)); }
private async Task SendJoinRequest() { var joinReq = new JoinGameRequest(); joinReq.GameId = GameId; joinReq.Player = UserDataEditor.Data; await GameClient.SendRequestAsync("JoinGame", joinReq); }
public override void Execute() { JoinGameRequest joinGame = request as JoinGameRequest; gameService.FindGameByID(joinGame.GameID).GameIsWaitMazeEvent += GameService_GameIsWaitMazeEvent; gameService.JoinGame(joinGame.UserID, joinGame.GameID); // Получаем ответ о статусе входа }
/// <summary> /// Handles the <see cref = "JoinGameRequest" /> to enter a <see cref = "HiveGame" />. /// This method removes the peer from any previously joined room, finds the room intended for join /// and enqueues the operation for it to handle. /// </summary> /// <param name = "operationRequest"> /// The operation request to handle. /// </param> /// <param name = "sendParameters"> /// The send Parameters. /// </param> protected virtual void HandleJoinGameOperation(OperationRequest operationRequest, SendParameters sendParameters) { if (this.JoinStage != JoinStages.Connected) { this.OnWrongOperationStage(operationRequest, sendParameters); return; } // create join operation var joinRequest = new JoinGameRequest(this.Protocol, operationRequest); if (this.ValidateOperation(joinRequest, sendParameters) == false) { return; } // remove peer from current game this.RemovePeerFromCurrentRoom(LeaveReason.SwitchRoom, "eventual switch from other room."); // try to get the game reference from the game cache RoomReference gameReference; var pluginTraits = this.GetPluginTraits(); if (joinRequest.JoinMode > 0 || pluginTraits.AllowAsyncJoin) { var pluginName = joinRequest.Plugins != null && joinRequest.Plugins.Length > 0? joinRequest.Plugins[0] : String.Empty; gameReference = this.GetOrCreateRoom(joinRequest.GameId, pluginName); } else { if (this.TryGetRoomReference(joinRequest.GameId, out gameReference) == false) { this.OnRoomNotFound(joinRequest.GameId); var response = new OperationResponse { OperationCode = (byte)OperationCode.JoinGame, ReturnCode = (short)ErrorCode.GameIdNotExists, DebugMessage = HiveErrorMessages.GameIdDoesNotExist, }; this.SendOperationResponse(response, sendParameters); if (log.IsWarnEnabled) { log.WarnFormat("Game '{0}' userId '{1}' failed to join. msg:{2} -- peer:{3}", joinRequest.GameId, this.UserId, HiveErrorMessages.GameIdDoesNotExist, this); } return; } } // save the game reference in the peers state this.RoomReference = gameReference; // finally enqueue the operation into game queue gameReference.Room.EnqueueOperation(this, operationRequest, sendParameters); }
protected override bool ProcessCreateGame(HivePeer peer, JoinGameRequest joinRequest, SendParameters sendParameters) { if (base.ProcessCreateGame(peer, joinRequest, sendParameters)) { // update game state at master server this.UpdateGameStateOnMasterOnCreate(joinRequest, peer); } return(true); }
public async Task JoinGameAsync(JoinGameRequest request, Func <JoinGameResponse, Task> responseHandler) { _logger.LogInformation("JoinGame {}", request); var resp = new JoinGameResponse() { RequestId = request.RequestId }; try { if (!await AcquireGameLock(request.GameId, request.RequestId, TimeSpan.FromSeconds(30))) { resp.ErrorMessage = "Timed out while acquiring game lock"; await responseHandler(resp); return; } var gameState = await _dbContext.GameStates .FirstOrDefaultAsync(x => x.GameId == request.GameId); if (gameState == null) { resp.ErrorMessage = "GameId not found"; await responseHandler(resp); return; } if (gameState.IsFinished) { resp.ErrorMessage = "Game is finished"; await responseHandler(resp); return; } var gameEngine = new GameEngine(_loggerProvider, _dbContext, _cardRepo); gameEngine.GameState = gameState; var playerState = await gameEngine.JoinGameAsync(request); resp.IsSuccess = true; resp.Game = gameEngine.GameState.Game; await responseHandler(resp); InvokeOnPlayerUpdate(MakePlayerUpdateResponse(playerState)); InvokeOnGameUpdate(MakeGameUpdateResponse(gameEngine.GameState)); InvokeOnTradeUpdate(playerState.PlayerId, MakeTradeUpdateResponse(gameEngine.GameState.GameId, gameEngine.GameState.Trades)); } finally { ReleaseGameLock(request.GameId, request.RequestId); } }
protected override bool ProcessBeforeJoinGame(JoinGameRequest joinRequest, SendParameters sendParameters, HivePeer peer) { if (joinRequest.ActorProperties != null && joinRequest.ActorProperties.ContainsKey("ProcessBeforeJoinException")) { peer = null; joinRequest.CacheSlice = 123; } return(base.ProcessBeforeJoinGame(joinRequest, sendParameters, peer)); }
public Task <JoinResponse> JoinGame(JoinGameRequest request) { if (!TryGetViewer(out var user)) { return(null); } return(this.game.JoinAsync(user, request.Name)); }
public JoinGameResponse JoinGame(JoinGameRequest joinRequest, short expectedResult = ErrorCode.Ok) { var request = CreateOperationRequest(OperationCode.JoinGame); JoinRequestToDictionary(joinRequest, request); var operationResponse = this.SendRequestAndWaitForResponse(request, expectedResult); return(GetJoinGameResponse(operationResponse)); }
protected virtual Actor HandleCreateGameOperation(LitePeer peer, JoinGameRequest createRequest, SendParameters sendParameters) { if (!this.ValidateGame(peer, createRequest.OperationRequest, sendParameters)) { return(null); } HandleCreateGameOperationBody(peer, createRequest, sendParameters, false); return(null); }
void Awake() { _instance = this; joinGameRequest = GetComponent <JoinGameRequest>(); createGameRequest = GetComponent <CreateGameRequest>(); teamChooseRequest = GetComponent <TeamChooseRequest>(); sendDamageRequest = GetComponent <SendDamageRequest>(); syncDropWeaponRequest = GetComponent <SyncDropWeaponRequest>(); deleteDropWeaponRequest = GetComponent <DeleteDropWeaponRequest>(); }
public WaitingRoomGamesResponse JoinGame([FromUri] JoinGameRequest request) { WaitingRoom waitingRoom = WaitingRoom.GetWaitingRoom(); waitingRoom.JoinGame(request); waitingRoom.SaveWaitingRoom(); return(new WaitingRoomGamesResponse() { Games = waitingRoom.Games }); }
public JoinGameResponse JoinGame(JoinGameRequest joinRequest, short expectedResult = ErrorCode.Ok) { var request = CreateOperationRequest(OperationCode.JoinGame); JoinRequestToDictionary(joinRequest, request); var operationResponse = this.SendRequestAndWaitForResponse(request, expectedResult); this.authenticationScheme.HandleAuthenticateResponse(this, operationResponse.Parameters); return(GetJoinGameResponse(operationResponse)); }
public async Task <APIGatewayProxyResponse> Post(APIGatewayProxyRequest request, ILambdaContext context) { JoinGameRequest input = JsonSerializer.Deserialize <JoinGameRequest>(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; DescribeGameSessionsResponse gameSession = await amazonClient.DescribeGameSessionsAsync(new DescribeGameSessionsRequest() { GameSessionId = input.gameSessionId }); bool IsPrivate = gameSession.GameSessions[0].GameProperties.Find((GameProperty gp) => gp.Key.Equals("IsPrivate")).Value.Equals("True"); string Password = IsPrivate ? gameSession.GameSessions[0].GameProperties.Find((GameProperty gp) => gp.Key.Equals("Password")).Value : ""; if (!IsPrivate || input.password.Equals(Password)) { CreatePlayerSessionRequest playerSessionRequest = new CreatePlayerSessionRequest(); playerSessionRequest.PlayerId = input.playerId; playerSessionRequest.GameSessionId = input.gameSessionId; CreatePlayerSessionResponse playerSessionResponse = amazonClient.CreatePlayerSessionAsync(playerSessionRequest).Result; JoinGameResponse response = new JoinGameResponse { 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" } } }); } else { return(new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.BadRequest, Body = "Incorrect password for private game", }); } }
public void CannotJoinGameIfFull() { var request = new JoinGameRequest { GameId = "1", ProfileId = "123" }; var game = new PickUpGame(DateTime.Now, new Sport(), new Location()) { MaxPlayers = 0 }; _mockGameRepo.Setup(x => x.GetPickUpGameById(request.GameId)).Returns(game); var handler = new JoinGameRequestHandler(_mockGameRepo.Object); var response = handler.Handle(request); Assert.That(response.Status, Is.EqualTo(ResponseCodes.GameIsFull)); }
protected virtual void JoinGame(string Name, string Password = "") { this.Realm.WriteToLog("Joining Game: " + Name, Color.Orange); this.Realm.WaitForPacket(4); JoinGameRequest packet = new JoinGameRequest(this.ReqID, Name, Password); this.Realm.SendPacket(packet); checked { this.ReqID += 1; } }
public async Task It_Returns_A_400_Bad_Request_If_The_User_Has_Already_Joined_The_Game() { //--arrange var newGame = await CreateValidGameForTesting(TestUserName, 2, 0); var joinGameResult = new JoinGameRequest(newGame.Id, TestUserName); //--act var exception = Assert.ThrowsAsync <ApiException>(async() => await GamesClient.JoinGame(joinGameResult, TestEnvironmentSettings.BaseApiUrl)); //--assert exception.ResponseStatusCode.ShouldBe(HttpStatusCode.BadRequest); }
public async Task It_Returns_A_409_Conflict_If_The_Game_Is_Already_Full() { //--arrange var newGame = await CreateValidGameForTesting(TestUserName, 1, 0); var joinGameResult = new JoinGameRequest(newGame.Id, "some user name"); //--act var exception = Assert.ThrowsAsync <ApiException>(async() => await GamesClient.JoinGame(joinGameResult, TestEnvironmentSettings.BaseApiUrl)); //--assert exception.ResponseStatusCode.ShouldBe(HttpStatusCode.Conflict); }
public void CanJoinGame() { var request = new JoinGameRequest { GameId = "1", ProfileId = "123" }; var game = new PickUpGame(DateTime.Now, new Sport(), new Location()); _mockGameRepo.Setup(x => x.GetPickUpGameById(request.GameId)).Returns(game); var handler = new JoinGameRequestHandler(_mockGameRepo.Object); var response = handler.Handle(request); _mockGameRepo.Verify(x => x.AddPlayerToGame(game.Id, request.ProfileId)); Assert.That(response.Status, Is.EqualTo(ResponseCodes.Success)); }
public void JoinGame(string roomID, string playerName) { if (client == null || !client.IsConnected()) { ConnectPlayer(); } JoinGameRequest request = new JoinGameRequest(); request.PlayerName = playerName; request.RoomID = roomID; client.SendData((int)DataTypes.JoinGameRequest, request); }
private void JoinGameOnGameServer() { if (log.IsDebugEnabled) { log.DebugFormat("GAME: Joining game {0}", this.gameId); } var operation = new JoinGameRequest { GameId = this.gameId }; var request = new OperationRequest((byte)OperationCode.JoinGame, operation); this.gameServerClient.SendOperationRequest(request, new SendParameters()); }
public void JoinGameRequest_Correct_ObjectCreated() { // Arrange var joinGameRequest = new JoinGameRequest() { Player = this.testPlayer, GameName = this.gameName }; // Act // Assert Assert.Equal(this.gameName, joinGameRequest.GameName); Assert.Equal(this.testPlayer, joinGameRequest.Player); }
public async Task JoinGame(JoinGameRequest request) { var result = await _mediator.Send(request); string groupName = result.GameId.ToString(); await Groups.AddToGroupAsync(Context.ConnectionId, groupName); await Clients.Group(groupName).SendAsync("PlayerJoinedGame", result); var availableGamesQuery = new AvailableGamesQuery(); var avGamesResult = await _mediator.Send(availableGamesQuery); await Clients.Group(LOBBY).SendAsync("ListRefreshed", avGamesResult.AvailableGames); }
public bool OnJoinGameRequest(ServerClient client, JoinGameRequest request, out ServerGame game) { if (request.IsPrivate) { string key = request.PrivateKey; if (!PrivateGames.TryGetValue(key, out game)) return false; PrivateGames.Remove(key); } else { string key = request.Owner; if (!PublicGames.TryGetValue(key, out game)) return false; PublicGames.Remove(key); } ActiveGames.Add(game); game.StartDeploymentTimer(); return true; }
protected override RoomReference GetRoomReference(JoinGameRequest joinRequest, params object[] args) { throw new NotSupportedException("Use TryGetRoomReference or TryCreateRoomReference instead."); }
public override void JoinGame(IRpcController controller, JoinGameRequest request, Action<JoinGameResponse> done) { ProtoOutputBuffer.Write(request.GetType(), request.ToString()); }
private void JoinGame(int gameId) { JoinGameRequest jgr = new JoinGameRequest(); jgr.GameId = gameId; _es.Engine.Send(jgr); }
public override void JoinGame(IRpcController controller, JoinGameRequest request, Action<JoinGameResponse> done) { throw new NotImplementedException(); }
public OperationResponse HandleJoinGame(OperationRequest operationRequest, SendParameters sendParameters) { var joinGameRequest = new JoinGameRequest(this.Protocol, operationRequest); OperationResponse response; if (OperationHelper.ValidateOperation(joinGameRequest, log, out response) == false) { return response; } GameState gameState; if (this.Application.TryGetGame(joinGameRequest.GameId, out gameState)) { gameState.Lobby.EnqueueOperation(this, operationRequest, sendParameters); return null; } if (joinGameRequest.JoinMode == JoinModes.JoinOnly && !this.Application.PluginTraits.AllowAsyncJoin) { return new OperationResponse { OperationCode = operationRequest.OperationCode, ReturnCode = (short)ErrorCode.GameIdNotExists, DebugMessage = HiveErrorMessages.GameIdDoesNotExist }; } AppLobby lobby; response = this.TryGetLobby(joinGameRequest.LobbyName, joinGameRequest.LobbyType, operationRequest.OperationCode, out lobby); if (response != null) { return response; } lobby.EnqueueOperation(this, operationRequest, sendParameters); return null; }
private void JoinGameOnGameServer() { if (log.IsDebugEnabled) { log.DebugFormat("GAME: Joining game {0}", this.gameId); } var operation = new JoinGameRequest { GameId = this.gameId }; var request = new OperationRequest((byte)OperationCode.JoinGame, operation); this.gameServerClient.SendOperationRequest(request, new SendParameters()); }