public async Task <FullGameStateOutVM> PlayCard([FromBody] PlayCardInVM move, [FromRoute] int id) { var userID = _contextService.UserID; var game = await _gameService.Play(move, id, userID); return(game); }
public async Task <FullGameStateOutVM> Play(PlayCardInVM move, int gameID, int playerID) { using var transaction = await _transactionManager.BeginTransactionAsync(); Game game = await _gameManagementService.GetPlayableGame(gameID, playerID); FullGameStateOutVM output = await InternalPlayCard(move, game, playerID); await transaction.CommitAsync(); return(output); }
private async Task <FullGameStateOutVM> InternalPlayCard(PlayCardInVM move, Game game, int playerID) { var playerState = game.State.Single(state => state.PlayerID == playerID); var otherPlayerState = game.State.Where(s => s.PlayerID != playerID).Single(); var handCards = _cardSerializer.DeserializeCards(playerState.Hand).ToList(); var currentQueues = _mapper.GetQueues(playerState.Table); var otherQueues = _mapper.GetQueues(otherPlayerState.Table); var playedCard = _mapper.MapCard(move.Hand); // new Card { Suit = move.Hand.Suit, Value = move.Hand.Value, De }; List <Card> newHand = RemoveCardFromHand(handCards, playedCard); if (move.ToQueue.HasValue) { var queue = (move.ToOtherPlayer ? otherQueues : currentQueues)[move.ToQueue.Value]; var existingSuits = currentQueues.Concat(otherQueues).SelectMany(q => q.Where(e => !e.IsJoker)).Select(e => e.Suit).ToHashSet(); var availableSuits = new[] { Suit.Clubs, Suit.Diamonds, Suit.Hearts, Suit.Spades }.Where(s => !existingSuits.Contains(s)).ToList(); PlaceCardInQueue(queue, move.ReplacingJoker, playedCard, newHand, availableSuits); if (newHand.Count == 0) { throw new BadRequestException("Cannot play your last card, must discard"); } playerState.Table = _mapper.SerializeQueues(currentQueues); otherPlayerState.Table = _mapper.SerializeQueues(otherQueues); if (IsQueueWon(queue)) { game.GameOverAt = DateTime.UtcNow; game.WinnerID = move.ToOtherPlayer ? otherPlayerState.PlayerID : playerID; } } else { //discard if (PlayerCanDraw(game, playerID)) { throw new BadRequestException("Cannot discard if you have to draw"); } var discards = _cardSerializer.DeserializeCards(game.Discarded); discards = discards.Append(playedCard); game.Discarded = _cardSerializer.SerializeCards(discards); game.NextPlayerID = otherPlayerState.PlayerID; } playerState.Hand = _cardSerializer.SerializeCards(newHand); UpdateLastMove(game); await _context.SaveChangesAsync(); var output = _mapper.MapFullGameState(game); return(output); }