/// <summary> /// Establishes a connection with database to register a new account. /// </summary> /// <param name="account">Account to register</param> /// <returns>True if account was registered successfully; False if not</returns> public bool SignUp(Account account) { try { using (DostDatabase db = new DostDatabase()) { if (db.Account.ToList().Find(accountRegistered => accountRegistered.email == account.Email) != null) { return(false); } var validationCode = Engine.HashWithSHA256(account.Username + DateTime.Now); db.Account.Add(new DataAccess.Account { username = account.Username, password = Engine.HashWithSHA256(account.Password), email = account.Email, coins = 0, creationDate = DateTime.Now, isVerified = 0, validationCode = validationCode }); if (db.SaveChanges() != 0) { SendSignUpEmail(account.Email, validationCode); return(true); } } } catch (DbUpdateException dbUpdateException) { Console.WriteLine("DbUpdateException -> " + dbUpdateException.Message); } catch (Exception exception) { Console.WriteLine("Exception -> " + exception.Message); } return(false); }
/// <summary> /// Establishes a connection with database to try to get all the best scores. /// </summary> /// <returns>List with best scores</returns> public List <UserScore> GetBestScores() { List <UserScore> bestScoresList = new List <UserScore>(); try { using (DostDatabase db = new DostDatabase()) { var players = (from player in db.Player where player.Game.round == 5 group player by player.Account.username into playerGroup let totalScore = playerGroup.Sum(playerInGroup => playerInGroup.score) orderby totalScore descending select new { User = playerGroup.Key, TotalScore = totalScore }).ToList(); for (int pos = 0; pos < players.Count; pos++) { bestScoresList.Add(new UserScore { Ranking = pos + 1, Username = players[pos].User, Score = players[pos].TotalScore }); } } } catch (Exception exception) { Console.WriteLine("Exception -> " + exception.Message); } return(bestScoresList); }
/// <summary> /// Gets a player in a game from database. /// </summary> /// <param name="idaccount">Account identifier</param> /// <param name="idgame">Game identifier</param> /// <returns>A game player</returns> public Player GetPlayer(int idaccount, int idgame) { Player player = new Player(); try { using (DostDatabase db = new DostDatabase()) { var playerDb = db.Player.ToList().Find( playerList => playerList.idgame == idgame && playerList.idaccount == idaccount ); if (playerDb != null) { player.Id = playerDb.idplayer; player.Account = new Account( playerDb.Account.idaccount, playerDb.Account.username, playerDb.Account.password, playerDb.Account.email, playerDb.Account.coins, playerDb.Account.creationDate, playerDb.Account.isVerified == 1, playerDb.Account.validationCode ); player.Score = playerDb.score; player.IsHost = playerDb.isHost == 1; player.Game = null; } } } catch (Exception exception) { Console.WriteLine("Exception -> " + exception.Message); } return(player); }
/// <summary> /// Gets a list of all players in a game stored in database. /// </summary> /// <param name="idgame">Game identifier</param> /// <returns>List of players</returns> public List <Player> GetPlayersList(int idgame) { List <Player> playersList = new List <Player>(); try { using (DostDatabase db = new DostDatabase()) { var playersListDb = (from player in db.Player where player.idgame == idgame select player).ToList(); playersListDb.ForEach( player => playersList.Add(new Player( player.idplayer, new Account( player.Account.idaccount, player.Account.username, player.Account.password, player.Account.email, player.Account.coins, player.Account.creationDate, player.Account.isVerified == 1, player.Account.validationCode ), null, player.score, player.isHost == 1 )) ); } } catch (Exception exception) { Console.WriteLine("Exception -> " + exception.Message); } return(playersList); }
/// <summary> /// Reduces the timer time of an ingame environment. /// </summary> /// <param name="guidGame">Game global unique identifier</param> /// <param name="guidPlayer">Player global unique identifier</param> public void ReduceTime(string guidGame, string guidPlayer) { if (!gamesClients.ContainsKey(guidGame)) { return; } if (!gamesClients[guidGame].ContainsKey(guidPlayer)) { return; } var game = GameService.ActiveGames.Find(playerInGame => playerInGame.ActiveGameGuid == guidGame); if (game == null) { return; } var player = game.Players.Find(playerInGame => playerInGame.ActivePlayerGuid == guidPlayer); if (player == null) { return; } if (!GameService.GamesTimer.ContainsKey(game.ActiveGameGuid)) { return; } using (DostDatabase db = new DostDatabase()) { var account = db.Account.Find(player.Account.Id); if (account == null) { return; } if (account.coins < GameService.ROUND_REDUCE_TIME_COST) { return; } account.coins -= GameService.ROUND_REDUCE_TIME_COST; if (db.SaveChanges() != 1) { return; } } GameService.GamesTimer[game.ActiveGameGuid] = GameService.GamesTimer[game.ActiveGameGuid].AddSeconds(-GameService.ROUND_REDUCE_TIME_SECONDS); foreach (var playerInGame in gamesClients[guidGame]) { playerInGame.Value.ReduceTime(guidGame); } }
/// <summary> /// Gets all game categories from a game stored in database. /// </summary> /// <param name="idgame">Game identifier</param> /// <returns>List of game categories</returns> public List <GameCategory> GetCategoriesList(int idgame) { List <GameCategory> categoriesList = new List <GameCategory>(); try { using (DostDatabase db = new DostDatabase()) { var categories = (from category in db.GameCategory where category.idgame == idgame select category).ToList(); categories.ForEach(category => categoriesList.Add( new GameCategory(category.idcategory, null, category.name) )); } } catch (Exception exception) { Console.WriteLine("Exception -> " + exception.Message); } return(categoriesList); }
/// <summary> /// Creates and initializes a new instance with identifier given and establishes a connection with /// database to try to load the account data. /// </summary> /// <param name="id">Account identifier</param> public Account(int id) { this.id = id; try { using (DostDatabase db = new DostDatabase()) { var accountDb = db.Account.ToList().Find(account => account.idaccount == id); if (accountDb != null) { username = accountDb.username; password = accountDb.password; email = accountDb.email; coins = accountDb.coins; creationDate = accountDb.creationDate; isVerified = accountDb.isVerified == 1; validationCode = accountDb.validationCode; } } } catch (Exception exception) { Console.WriteLine("Exception (Account) -> " + exception.Message); } }
/// <summary> /// Establishes a connection with database to try to get the account rank by identifier given. /// </summary> /// <param name="idaccount">Account identifier</param> /// <returns>Rank with prefix #, or an empty string if couldn't find the account or games played.</returns> public string GetRank(int idaccount) { string rank = ""; try { using (DostDatabase db = new DostDatabase()) { var account = db.Account.ToList().Find(accountList => accountList.idaccount == idaccount); if (account != null) { var player = GetBestScores().Find(userScore => userScore.Username == account.username); if (player != null) { rank = "#" + player.Ranking; } } } } catch (Exception exception) { Console.WriteLine("Exception -> " + exception.Message); } return(rank); }
/// <summary> /// Adds a player to an active game. /// </summary> /// <param name="idaccount">Account identifier</param> /// <param name="guidGame">Game global unique identifier</param> /// <param name="asHost">True if his rol is to be a host; False if not</param> /// <param name="guidPlayer">Player global unique identifier generated</param> /// <returns>True if player was added successfully; False if not</returns> public bool AddPlayer(int idaccount, string guidGame, bool asHost, out string guidPlayer) { guidPlayer = string.Empty; try { var foundGame = activeGames.Find(game => game.ActiveGameGuid == guidGame); if (foundGame == null) { return(false); } if (foundGame.Players.Count >= MAX_PLAYERS_IN_GAME) { return(false); } using (DostDatabase db = new DostDatabase()) { var newPlayerAccount = db.Account.Find(idaccount); if (newPlayerAccount == null) { return(false); } guidPlayer = Guid.NewGuid().ToString(); foundGame.Players.Add(new Player { Account = new Account( newPlayerAccount.idaccount, newPlayerAccount.username, newPlayerAccount.password, newPlayerAccount.email, newPlayerAccount.coins, newPlayerAccount.creationDate, newPlayerAccount.isVerified == 1, newPlayerAccount.validationCode ), Game = null, IsHost = asHost, Score = 0, ActivePlayerGuid = guidPlayer }); return(true); } } catch (Exception exception) { Console.WriteLine("Exception -> " + exception.Message); } return(false); }
/// <summary> /// Establishes a connection with database to try to find an account with username and password given. /// If exists and is not verified, tries to verify it with webpage. /// </summary> /// <param name="username">Account username</param> /// <param name="password">Account password</param> /// <returns>Account found in database</returns> public Account TryLogin(string username, string password) { string hashedPassword = Engine.HashWithSHA256(password); Account account = new Account(); try { using (DostDatabase db = new DostDatabase()) { var accountDb = db.Account.ToList().Find( accountInList => accountInList.username == username && accountInList.password == hashedPassword ); if (accountDb != null) { account.Id = accountDb.idaccount; account.Username = accountDb.username; account.Password = accountDb.password; account.Email = accountDb.email; account.Coins = accountDb.coins; account.CreationDate = accountDb.creationDate; account.IsVerified = accountDb.isVerified == 1; account.ValidationCode = accountDb.validationCode; if (!account.IsVerified && TryValidateAccount(account.ValidationCode)) { accountDb.isVerified = 1; if (db.SaveChanges() != 0) { account.IsVerified = true; } } } } } catch (DbUpdateException dbUpdateException) { Console.WriteLine("DbUpdateException -> " + dbUpdateException.Message); } catch (Exception exception) { Console.WriteLine("Exception -> " + exception.Message); } return(account); }
/// <summary> /// Establishes a connection with database to try to get account data by identifier given. /// </summary> /// <param name="idaccount">Account identifier</param> /// <returns>Account found</returns> public Account GetAccount(int idaccount) { Account account = new Account(); try { using (DostDatabase db = new DostDatabase()) { var accountDb = db.Account.Find(idaccount); if (accountDb != null) { account.Id = accountDb.idaccount; account.Username = accountDb.username; account.Password = accountDb.password; account.Email = accountDb.email; account.Coins = accountDb.coins; account.CreationDate = accountDb.creationDate; account.IsVerified = accountDb.isVerified == 1; account.ValidationCode = accountDb.validationCode; } } } catch (Exception exception) { Console.WriteLine("Exception -> " + exception.Message); } return(account); }
/// <summary> /// Ends the game in an ingame environment. /// </summary> /// <param name="guidGame">Game global unique identifier</param> public void EndGame(string guidGame) { if (!gamesClients.ContainsKey(guidGame)) { return; } var game = GameService.ActiveGames.Find(activeGame => activeGame.ActiveGameGuid == guidGame); if (game == null) { return; } using (DostDatabase db = new DostDatabase()) { var newGame = new DataAccess.Game { date = game.Date, round = game.Round }; db.Game.Add(newGame); if (db.SaveChanges() == 0) { return; } game.Players.ForEach(player => { newGame.Player.Add(new DataAccess.Player { idaccount = player.Account.Id, idgame = newGame.idgame, isHost = player.IsHost ? 1 : 0, score = player.Score }); }); if (db.SaveChanges() == 0) { return; } game.GameCategories.ForEach(category => { var newCategory = new DataAccess.GameCategory { idgame = newGame.idgame, name = category.Name }; newGame.GameCategory.Add(newCategory); newGame.Player.ToList().ForEach(player => { var playerCategoryAnswers = category.CategoryPlayerAnswer.Where(categoryAnswer => categoryAnswer.Player.Account.Id == player.idaccount).ToList(); playerCategoryAnswers.ForEach(categoryAnswer => { newCategory.CategoryPlayerAnswer.Add(new DataAccess.CategoryPlayerAnswer { idcategory = newCategory.idcategory, idplayer = player.idplayer, answer = categoryAnswer.Answer, round = categoryAnswer.Round }); }); }); }); var playerPlaces = game.Players.ToList(); playerPlaces = playerPlaces.OrderBy(playerPlace => playerPlace.Score).ToList(); for (int index = 0; index < playerPlaces.Count; index++) { db.Account.Find(playerPlaces[index].Account.Id).coins += GameService.MAX_COINS_PER_GAME_WIN / (index + 1); } if (db.SaveChanges() == 0) { return; } } foreach (var player in gamesClients[guidGame]) { player.Value.EndGame(guidGame); } System.Threading.Thread.Sleep(2000); gamesClients.Remove(guidGame); }
/// <summary> /// Sets a new letter for an active game. /// </summary> /// <param name="guidGame">Game global unique identifier</param> /// <param name="idaccount">Account identifier of letter selector</param> /// <param name="selectRandomLetter">True if letter should be selected randomly; False if not</param> /// <param name="letter">Letter to be selected if selectRandomLetter parameter has false value</param> /// <returns>True if letter was set successfully; False if not</returns> public bool SetGameLetter(string guidGame, int idaccount, bool selectRandomLetter, string letter = null) { var findGame = activeGames.Find(game => game.ActiveGameGuid == guidGame); if (findGame == null) { return(false); } else if (!selectRandomLetter && string.IsNullOrWhiteSpace(letter)) { return(false); } else if (!selectRandomLetter) { using (DostDatabase db = new DostDatabase()) { var account = db.Account.Find(idaccount); if (account == null || account.coins < ROUND_LETTER_SELECTION_COST) { return(false); } account.coins -= ROUND_LETTER_SELECTION_COST; if (db.SaveChanges() != 1) { return(false); } } } int asciiLetterA = 65; int asciiLetterZ = 90; int roundTimeInSeconds = ROUND_TIME + 3; findGame.LetterSelected = selectRandomLetter ? Convert.ToChar(new Random().Next(asciiLetterA, asciiLetterZ)).ToString() : letter; findGame.RoundStartingTime = DateTime.Now.Ticks; Task.Run(() => { if (!GamesTimer.ContainsKey(findGame.ActiveGameGuid)) { GamesTimer.Add(findGame.ActiveGameGuid, new DateTime(findGame.RoundStartingTime).AddSeconds(roundTimeInSeconds)); } else { GamesTimer[findGame.ActiveGameGuid] = new DateTime(findGame.RoundStartingTime).AddSeconds(roundTimeInSeconds); } while (true) { if (!(GamesTimer[findGame.ActiveGameGuid] > DateTime.Now)) { break; } } var gamesClients = InGameService.GamesClients; if (!gamesClients.ContainsKey(guidGame)) { return; } foreach (var gameClient in gamesClients[guidGame]) { gameClient.Value.EndRound(guidGame); } }); return(true); }