public async Task StartGame() { var userMetadata = this.GetUserMetadata(); if (userMetadata == null) { throw new Exception("Game metadata is null"); } GameTableEntity game = GameTable.GetGameObject(userMetadata.GameId); if (game == null) { throw new Exception("Game is null!"); } if (userMetadata.UserId != game.LeaderUserId) { throw new Exception("Only leader can end!"); } await GameTable.StartGame(game); await Clients.Group(userMetadata.GameId).SendAsync("GameMetadataUpdate", JsonConvert.SerializeObject(game)); await Clients.Group(userMetadata.GameId).SendAsync("GameStarted"); }
public async override Task OnDisconnectedAsync(Exception exception) { var userMetadata = this.GetUserMetadata(); Log.Logger.LogError($"The client {JsonConvert.SerializeObject(userMetadata)} disconnected!"); if (userMetadata == null) { // Nothing to do here return; } //await Groups.RemoveFromGroupAsync(Context.ConnectionId, userMetadata.GameId); GameTableEntity game = GameTable.GetGameObject(userMetadata.GameId); if (game == null) { // Nothing to do here return; } // Notify everyone user left await GameTable.RemoveUserFromGame(userMetadata.UserId, game); await Clients.Group(userMetadata.GameId).SendAsync("GameMetadataUpdate", JsonConvert.SerializeObject(game)); }
public async Task CreateOrJoinGame(string gameId, string userId, string userName) { if (string.IsNullOrEmpty(gameId) || string.IsNullOrEmpty(userId)) { throw new Exception("GroupId or user is empty"); } Log.Logger.LogInformation($"User {userId} requesting to join game {gameId}"); GameTableEntity game = GameTable.GetGameObject(gameId); if (game == null) { // Join game as admin game = await GameTable.CreateGame(gameId, userId, userName); } else { // If game has ended or started, there's no join (spectator mode) if (!game.GameEnded && !game.GameStarted) { await GameTable.AddUserToGame(userId, userName, game); } } this.SetGameMetadata(userId, gameId); // Add to group and update game metadata for everyone and send notification await Groups.AddToGroupAsync(Context.ConnectionId, gameId); await Clients.Group(gameId).SendAsync("GameMetadataUpdate", JsonConvert.SerializeObject(game)); await Clients.Group(gameId).SendAsync("PlayerJoined", userId); }