/// <summary> /// Verify the player's guess /// </summary> /// <param name="playerId"></param> /// <param name="gameId"></param> /// <param name="sequence">the player's guess</param> /// <returns>Game info</returns> public async Task <Game> Guess(Guid playerId, Guid gameId, string sequence) { using (IDbContextScope contextScope = _dbContextFactory.Create()) { var game = await _gameService.GetAsync(gameId); //check if game exists if (game == null) { throw new ApplicationException("Invalid game"); } //check if player belongs to the game if (!game.Players.Any(p => p.Id == playerId)) { throw new ApplicationException("Player dont belong to this game"); } var playerGuesses = game.Players.First(p => p.Id == playerId).Guesses; if (game.Guesses.Count() > 0) { //check if there are players that didnt play if (game.Players.Select(p => p.Guesses.Count).Min() < playerGuesses.Count()) { throw new ApplicationException("Wait for other players guess"); } //check if the game is finished if (game.Players.Select(p => p.Guesses.Count).Min() == game.Players.Select(p => p.Guesses.Count).Max() && game.Status == 2) { throw new ApplicationException("Game is finished"); } } var guess = new Guess() { GameId = gameId, PlayerId = playerId, Sequence = sequence }; //check the guess hits guess.CheckHits(game.Sequence); //if the player founds the sequence, change game status if (guess.ExactCount == game.SequenceLength) { game.Status = 2; game.Players.First(p => p.Id == playerId).Winner = true; } //add guess to game game.Guesses.Add(guess); game.PlayerId = playerId; _gameService.Update(game); contextScope.SaveChanges(); return(game); } }