Ejemplo n.º 1
0
        public static void CheckPossibleSelfKong(Round round, RoundPlayer player)
        {
            var unopenTiles = round.RoundTiles.Where(t => string.IsNullOrEmpty(t.Owner));

            if (unopenTiles.Count() == 0)
            {
                return;
            }

            var playerTiles       = round.RoundTiles.Where(rt => rt.Owner == player.GamePlayer.Player.UserName && rt.TileSetGroup != TileSetGroup.Kong && rt.TileSetGroup != TileSetGroup.Chow);
            int possibleKongCount = playerTiles
                                    .GroupBy(t => new { t.Tile.TileType, t.Tile.TileValue })
                                    .Where(grp => grp.Count() == 4)
                                    .Count();;

            if (possibleKongCount > 0)
            {
                for (int i = 0; i < possibleKongCount; i++)
                {
                    player.RoundPlayerActions.Add(new RoundPlayerAction {
                        ActionType = ActionType.SelfKong
                    });
                }
            }
        }
Ejemplo n.º 2
0
        private void UpdateRounds(List <RoundPlayer> roundPlayers)
        {
            RoundPlayer dealer = roundPlayers
                                 .Where(roundPlayer => roundPlayer.Player.Type == PlayerType.Dealer)
                                 .First();

            roundPlayers.Remove(dealer);

            foreach (var roundPlayer in roundPlayers)
            {
                int score = CalculateCardScore(roundPlayer.Cards.Select(roundPlayerCard => GetCardById(roundPlayerCard.CardId)));
                if (score > Constants.BlackJackValue)
                {
                    roundPlayer.State = RoundPlayerState.Lose;
                }
            }

            int dealerScore = CalculateCardScore(dealer.Cards.Select(roundPlayerCard => GetCardById(roundPlayerCard.CardId)));

            if (dealerScore > Constants.BlackJackValue)
            {
                SetWinners(roundPlayers);
            }
            if (dealerScore <= Constants.BlackJackValue)
            {
                CheckStates(roundPlayers, dealerScore);
            }
            _roundPlayerRepository.Update(roundPlayers);
        }
Ejemplo n.º 3
0
        public void Step()
        {
            Game game = _gameRepository.GetContinueableGame(_userId);

            if (game == null)
            {
                throw new InvalidOperationException("Game is not found");
            }
            RoundPlayer user       = _roundPlayerRepository.GetLastRoundPlayerInfo(game.Id, _userId);
            List <Card> roundCards = _cardRepository.GetLastRoundCards(game.Id).ToList();

            if (user.State != RoundPlayerState.None)
            {
                throw new InvalidOperationException("Player can\'t to step when RoundState != None");
            }
            List <long> shuffledCards   = GetShuffledCards(roundCards);
            var         roundPlayerCard = new RoundPlayerCard {
                RoundPlayerId = user.Id, CardId = shuffledCards[0]
            };

            _roundPlayerCardRepository.Add(roundPlayerCard);
            if (!IsStepPossible(game))
            {
                Skip();
            }
        }
Ejemplo n.º 4
0
        private void CreateRound(Game game, int neededBotCount)
        {
            IEnumerable <Player> bots = _playerRepository.GetBots(neededBotCount);

            RoundPlayer user = new RoundPlayer {
                GameId = game.Id, PlayerId = _userId
            };
            var roundPlayers = new List <RoundPlayer> {
                user
            };

            foreach (var bot in bots)
            {
                RoundPlayer botRound = new RoundPlayer {
                    GameId = game.Id, PlayerId = bot.Id
                };
                roundPlayers.Add(botRound);
            }
            RoundPlayer dealer = new RoundPlayer {
                GameId = game.Id, PlayerId = Constants.DealerId
            };

            roundPlayers.Add(dealer);
            _roundPlayerRepository.Add(roundPlayers);

            CreateCards(roundPlayers);

            if (!IsStepPossible(game))
            {
                Skip();
            }
        }
Ejemplo n.º 5
0
        public ICollection <RoundTileDto> Resolve(RoundPlayer source, RoundPlayerDto destination, ICollection <RoundTileDto> destMember, ResolutionContext context)
        {
            var roundId          = source.RoundId;
            var RoundPlayerTiles = _context.RoundTiles.Where(rt => rt.RoundId == roundId && rt.Owner == source.GamePlayer.Player.UserName);

            return(_mapper.Map <ICollection <RoundTile>, ICollection <RoundTileDto> >(RoundPlayerTiles.ToList()));
        }
Ejemplo n.º 6
0
        public ICollection <RoundPlayerActionDto> Resolve(RoundPlayer source, RoundPlayerDto destination, ICollection <RoundPlayerActionDto> destMember, ResolutionContext context)
        {
            var roundId       = source.RoundId;
            var activeActions = source.RoundPlayerActions.Where(a => a.ActionStatus == ActionStatus.Active);
            var dtoresult     = _mapper.Map <ICollection <RoundPlayerAction>, ICollection <RoundPlayerActionDto> >(activeActions.ToList());

            return(dtoresult);
        }
        public int Create(Models.RoundPlayer item)
        {
            RoundPlayer roundPlayer = Mapper.ToEntity(item);

            _context.RoundPlayers.Add(roundPlayer);
            _context.SaveChanges();
            return(roundPlayer.Id);
        }
Ejemplo n.º 8
0
        private void OnPlayerChat(RoundPlayer roundplayer, string message)
        {
            PlayerBase p  = roundplayer.PlayerBase;
            IPlayer    pp = (IPlayer)roundplayer;

            //pp.Hurt(50f);

            Puts(p.Health.ToString() + " " + roundplayer.WeaponHolder.CanJump.ToString());
            Puts(message);
        }
Ejemplo n.º 9
0
        public static bool DetermineIfUserCanWin(Round round, RoundPlayer player, IPointsCalculator pointCalculator)
        {
            HandWorth handWorth = pointCalculator.Calculate(round, player.GamePlayer.Player.UserName);

            if (handWorth == null)
            {
                return(false);
            }
            return(handWorth.Points >= round.Game.MinPoint);
        }
        public void Delete(int id)
        {
            RoundPlayer item = _context.RoundPlayers.Find(id);

            if (item != null)
            {
                _context.RoundPlayers.Remove(item);
                _context.SaveChanges();
            }
        }
Ejemplo n.º 11
0
 public static DAL.Entities.RoundPlayer ToEntity(RoundPlayer roundPlayer)
 {
     DAL.Entities.RoundPlayer roundPlayerOut = new DAL.Entities.RoundPlayer
     {
         Id       = roundPlayer.Id,
         PlayerId = roundPlayer.PlayerId,
         RoundId  = roundPlayer.RoundId,
         IsWin    = roundPlayer.IsWin
     };
     return(roundPlayerOut);
 }
Ejemplo n.º 12
0
        public static void CheckSelfAction(Round round, RoundPlayer roundPlayer, IPointsCalculator pointsCalculator)
        {
            if (DetermineIfUserCanWin(round, roundPlayer, pointsCalculator))
            {
                roundPlayer.RoundPlayerActions.Add(new RoundPlayerAction {
                    ActionType = ActionType.SelfWin
                });
            }

            CheckPossibleSelfKong(round, roundPlayer);
        }
Ejemplo n.º 13
0
        public static RoundPlayer ToModel(DAL.Entities.RoundPlayer roundPlayer)
        {
            RoundPlayer roundPlayerOut = new RoundPlayer
            {
                Id       = roundPlayer.Id,
                PlayerId = roundPlayer.PlayerId,
                RoundId  = roundPlayer.RoundId,
                IsWin    = roundPlayer.IsWin
            };

            return(roundPlayerOut);
        }
Ejemplo n.º 14
0
        public static RoundPlayerServiceViewModel Map(RoundPlayer entity)
        {
            var viewModel = new RoundPlayerServiceViewModel()
            {
                Id       = entity.Id.ToString(),
                RoundId  = entity.RoundId.ToString(),
                PlayerId = entity.PlayerId.ToString(),
                Bet      = entity.Bet,
                Cards    = entity.Cards
            };

            return(viewModel);
        }
Ejemplo n.º 15
0
            static bool Prefix(string entryText, RoundPlayer player, out bool __result)
            {
                string    text;
                bool      flag2;
                Exception ex;
                string    input = null;

                foreach (AdminMessage processor in adminMessageDelegate.GetInvocationList())
                {
                    input = processor(entryText);
                    if (input != null)
                    {
                        ServerComponentReferenceManager.ServerInstance.console
                        .ExecuteInput(input, player.NetworkPlayerID, out text, out flag2, out ex, true);
                        break;
                    }
                }
                __result = input != null;
                return(input == null);
            }
Ejemplo n.º 16
0
        public void StartFirstRound(int gameId, IEnumerable <int> playersId)
        {
            int   number = _roundRepository.GetCountRoundsByGame(gameId);
            Round round  = new Round
            {
                GameId      = gameId,
                NumberRound = number + 1,
                IsCompleted = false
            };

            round.Id = _roundRepository.Create(round);
            foreach (int id in playersId)
            {
                RoundPlayer roundPlayer = new RoundPlayer
                {
                    RoundId  = round.Id,
                    PlayerId = id
                };
                _roundPlayerRepository.Create(roundPlayer);
            }
        }
Ejemplo n.º 17
0
        public static RoundPlayer Map(RoundPlayerServiceViewModel viewModel)
        {
            if (Guid.TryParse(viewModel.Id, out Guid id) && Guid.TryParse(viewModel.RoundId, out Guid roundId) && Guid.TryParse(viewModel.PlayerId, out Guid playerId))
            {
                var entity = new RoundPlayer()
                {
                    Id       = id,
                    RoundId  = roundId,
                    PlayerId = playerId,
                    Bet      = viewModel.Bet,
                    Cards    = viewModel.Cards
                };

                return(entity);
            }

            return(new RoundPlayer {
                Id = Guid.Empty,
                PlayerId = Guid.Empty,
                RoundId = Guid.Empty
            });
        }
Ejemplo n.º 18
0
        private List <RoundPlayerCard> DoPlayBot(RoundPlayer roundPlayer, List <long> shuffledCards)
        {
            if (roundPlayer.Player.Type == PlayerType.User)
            {
                return(Enumerable.Empty <RoundPlayerCard>().ToList());
            }
            var roundCards    = new List <RoundPlayerCard>();
            int gotCardsCount = 0;
            int score         = CalculateCardScore(roundPlayer.Cards.Select(roundPlayerCard => roundPlayerCard.Card));

            while (score < Constants.DealerStopValue)
            {
                Card card      = GetCardById(shuffledCards[gotCardsCount]);
                var  roundCard = new RoundPlayerCard {
                    CardId = card.Id, RoundPlayerId = roundPlayer.Id
                };
                gotCardsCount++;
                roundCards.Add(roundCard);
                roundPlayer.Cards.Add(roundCard);
                score = CalculateCardScore(roundPlayer.Cards.Select(roundPlayerCard => GetCardById(roundPlayerCard.CardId)));
            }
            return(roundCards);
        }
Ejemplo n.º 19
0
            private IEnumerable <RoundPlayer> GetNewUserRounds(IEnumerable <RoundPlayer> userRounds, bool sameRound, WindDirection windOfDealer)
            {
                List <RoundPlayer> ret = new List <RoundPlayer>();

                foreach (var lur in userRounds)
                {
                    var userWind = sameRound ? lur.Wind : NextWindAntiClockwise(lur.Wind);
                    var ur       = new RoundPlayer
                    {
                        GamePlayerId    = lur.GamePlayerId,
                        GamePlayer      = lur.GamePlayer,
                        IsInitialDealer = lur.IsInitialDealer,
                        IsDealer        = lur.Wind == windOfDealer,
                        IsMyTurn        = lur.Wind == windOfDealer,
                        MustThrow       = lur.Wind == windOfDealer,
                        Points          = lur.Points,
                        Wind            = userWind
                    };
                    ret.Add(ur);
                }

                return(ret);
            }
Ejemplo n.º 20
0
            public async Task <IEnumerable <RoundDto> > Handle(Command request, CancellationToken cancellationToken)
            {
                var game = await _context.Games.FirstOrDefaultAsync(x => x.Code == request.GameCode.ToUpper());

                if (game == null)
                {
                    throw new RestException(HttpStatusCode.NotFound, new { Game = "Could not find game" });
                }

                var round = game.Rounds.FirstOrDefault(r => r.Id == request.RoundId);

                if (round == null)
                {
                    throw new RestException(HttpStatusCode.NotFound, new { Round = "Could not find round" });
                }

                RoundPlayer roundPlayerWinner = round.RoundPlayers.FirstOrDefault(u => u.GamePlayer.Player.UserName == request.UserName);

                if (roundPlayerWinner == null)
                {
                    throw new RestException(HttpStatusCode.NotFound, new { Player = "Could not find player" });
                }

                //check for valid win:
                HandWorth handWorth = _pointCalculator.Calculate(round, request.UserName);

                if (handWorth == null)
                {
                    throw new RestException(HttpStatusCode.BadRequest, new { Win = "Invalid combination hand" });
                }

                if (handWorth.Points >= game.MinPoint)
                {
                    var winAction = roundPlayerWinner.RoundPlayerActions.FirstOrDefault(a => a.ActionType == ActionType.Win);
                    if (winAction != null)
                    {
                        winAction.ActionStatus = ActionStatus.Activated;
                    }

                    bool isSelfPick = false;

                    //set the game as over if all win action is settled
                    var playerWithUnsettledWin = round.RoundPlayers.Where(p => p.RoundPlayerActions.Any(pa => pa.ActionType == ActionType.Win && pa.ActionStatus == ActionStatus.Active));

                    if (playerWithUnsettledWin.Count() == 0)
                    {
                        round.IsOver   = true;
                        round.IsEnding = false;
                    }

                    //create the result and record who win and who lost
                    RoundResult winnerResult = new RoundResult
                    {
                        Player     = roundPlayerWinner.GamePlayer.Player,
                        PlayResult = PlayResult.Win,
                    };

                    if (round.RoundResults == null)
                    {
                        round.RoundResults = new List <RoundResult>();
                    }

                    //record hand type and extra points
                    foreach (var h in handWorth.HandTypes)
                    {
                        var point = _pointCalculator.HandTypeLookup[h];
                        winnerResult.RoundResultHands.Add(new RoundResultHand {
                            HandType = h, Point = point, Name = h.ToString()
                        });
                    }

                    foreach (var e in handWorth.ExtraPoints)
                    {
                        if (e == ExtraPoint.SelfPick)
                        {
                            isSelfPick = true;
                        }

                        var point = _pointCalculator.ExtraPointLookup[e];
                        winnerResult.RoundResultExtraPoints.Add(new RoundResultExtraPoint {
                            ExtraPoint = e, Point = point, Name = e.ToString()
                        });
                    }

                    //now that we have the winner hand type and extra point recorded, let's calculate the points

                    //if the handworth exceed game max point, cap the point to game's max point
                    var cappedPoint = handWorth.Points > game.MaxPoint ? game.MaxPoint : handWorth.Points;
                    var losingPoint = cappedPoint * -1;

                    if (isSelfPick)
                    {
                        //check if "bao"
                        //if there is AllOneSuit or SmallDragon or BigDragon or smallFourWind or bigFourWind
                        //then the one that "bao" will be the only one that pays to the winner

                        bool   isLoserBao        = false;
                        string baoPlayerUserName = string.Empty;
                        //check for allonesuit
                        var winnerTiles = round.RoundTiles.Where(t => t.Owner == roundPlayerWinner.GamePlayer.Player.UserName);
                        if (handWorth.HandTypes.Contains(HandType.AllOneSuit) ||
                            handWorth.HandTypes.Contains(HandType.SmallFourWind) ||
                            handWorth.HandTypes.Contains(HandType.BigFourWind))
                        {
                            //check if the 4th tilesetgroupindex has thrownby value
                            var fourthGroupTileIndex = winnerTiles.FirstOrDefault(t => t.TileSetGroupIndex == 4 && !string.IsNullOrEmpty(t.ThrownBy));
                            if (fourthGroupTileIndex != null)
                            {
                                isLoserBao        = true;
                                baoPlayerUserName = fourthGroupTileIndex.ThrownBy;
                            }
                        }

                        //check for dragon
                        if (handWorth.HandTypes.Contains(HandType.SmallDragon) || handWorth.HandTypes.Contains(HandType.BigDragon))
                        {
                            //find the index of first pong dragon
                            var pongOrKongDragons = winnerTiles.Where(t => (t.TileSetGroup == TileSetGroup.Pong || t.TileSetGroup == TileSetGroup.Kong) &&
                                                                      t.Tile.TileType == TileType.Dragon && !string.IsNullOrEmpty(t.ThrownBy));

                            //if there is 3rd set of dragon pong/kong, then its not a bao
                            //weird rule ever
                            //then find the index of second pong dragon and check thrown by
                            if (pongOrKongDragons.Count() == 2)
                            {
                                isLoserBao        = true;
                                baoPlayerUserName = pongOrKongDragons.OrderBy(t => t.TileSetGroupIndex).Last().ThrownBy;
                            }
                        }

                        if (isLoserBao)
                        {
                            //the loser that bao will pay the winning point times three
                            var winningPoint = cappedPoint * 3;
                            roundPlayerWinner.Points += winningPoint;
                            winnerResult.Points       = winningPoint;

                            RoundPlayer roundPlayerloser = round.RoundPlayers.FirstOrDefault(p => p.GamePlayer.Player.UserName == baoPlayerUserName);
                            roundPlayerloser.Points -= winningPoint;
                            round.RoundResults.Add(new RoundResult {
                                PlayResult = PlayResult.LostWithPenalty, Player = roundPlayerloser.GamePlayer.Player, Points = losingPoint * 3
                            });

                            //record users that are tied
                            var tiedPlayers = round.RoundPlayers.Where(p => p.GamePlayer.Player.UserName != baoPlayerUserName && p.GamePlayer.Player.UserName != roundPlayerWinner.GamePlayer.Player.UserName);
                            tiedPlayers.ForEach(tp =>
                            {
                                round.RoundResults.Add(new RoundResult {
                                    PlayResult = PlayResult.Tie, Player = tp.GamePlayer.Player, Points = 0
                                });
                            });
                        }
                        else
                        {
                            //if its self pick, and no bao, then all 3 other players needs to record the loss
                            var losers = round.RoundPlayers.Where(u => u.GamePlayer.Player.UserName != request.UserName);

                            //points will be times 3
                            var winningPoint = cappedPoint * 3;
                            roundPlayerWinner.Points += winningPoint;
                            winnerResult.Points       = winningPoint;

                            losers.ForEach(l =>
                            {
                                l.Points -= cappedPoint;
                                round.RoundResults.Add(new RoundResult {
                                    PlayResult = PlayResult.Lost, Player = l.GamePlayer.Player, Points = losingPoint
                                });
                            });
                        }
                    }
                    else
                    {
                        //otherwise there is only one loser that throw the tile to board
                        roundPlayerWinner.Points += cappedPoint;
                        winnerResult.Points       = cappedPoint;

                        var boardTile = round.RoundTiles.First(t => t.Owner == DefaultValue.board && t.Status == TileStatus.BoardActive);
                        var loser     = round.RoundPlayers.First(u => u.GamePlayer.Player.UserName == boardTile.ThrownBy);
                        loser.Points -= cappedPoint;
                        round.RoundResults.Add(new RoundResult {
                            PlayResult = PlayResult.Lost, Player = loser.GamePlayer.Player, Points = losingPoint
                        });

                        //check for multiple winners. If player has a valid win and already recorded as tie
                        var tieResultCouldWin = round.RoundResults.FirstOrDefault(rr => rr.PlayResult == PlayResult.Tie && rr.Player.UserName == roundPlayerWinner.GamePlayer.Player.UserName);

                        if (tieResultCouldWin != null)
                        {
                            //remove record that the player tie
                            round.RoundResults.Remove(tieResultCouldWin);
                        }
                        else
                        {
                            //record users that are tied
                            var tiedPlayers = round.RoundPlayers.Where(p => p.GamePlayer.Player.UserName != loser.GamePlayer.Player.UserName && p.GamePlayer.Player.UserName != roundPlayerWinner.GamePlayer.Player.UserName);
                            tiedPlayers.ForEach(tp =>
                            {
                                round.RoundResults.Add(new RoundResult {
                                    PlayResult = PlayResult.Tie, Player = tp.GamePlayer.Player, Points = 0
                                });
                            });
                        }
                    }
                    round.RoundResults.Add(winnerResult);

                    //tally the point in gameplayer
                    round.RoundPlayers.ForEach(rp =>
                    {
                        rp.GamePlayer.Points = rp.Points;
                    });

                    var success = await _context.SaveChangesAsync() > 0;

                    if (success)
                    {
                        List <RoundDto> results = new List <RoundDto>();

                        foreach (var p in round.RoundPlayers)
                        {
                            results.Add(_mapper.Map <Round, RoundDto>(round, opt => opt.Items["MainRoundPlayer"] = p));
                        }
                        return(results);
                    }
                }
                else
                {
                    throw new RestException(HttpStatusCode.BadRequest, new { Win = "Not enough point to win with this hand" });
                }

                throw new Exception("Problem calling win");
            }
Ejemplo n.º 21
0
            public async Task <IEnumerable <RoundDto> > Handle(Command request, CancellationToken cancellationToken)
            {
                var game = await _context.Games.FirstOrDefaultAsync(x => x.Code == request.GameCode.ToUpper());

                if (game == null)
                {
                    throw new RestException(HttpStatusCode.BadRequest, new { Game = "Game does not exist" });
                }

                Round lastRound = game.Rounds.OrderByDescending(r => r.DateCreated).FirstOrDefault();

                if (lastRound != null && !lastRound.IsOver)
                {
                    throw new RestException(HttpStatusCode.BadRequest, new { Round = "Last round is not over" });
                }

                var newRound = new Round
                {
                    GameId       = game.Id,
                    DateCreated  = DateTime.Now,
                    RoundTiles   = RoundTileHelper.CreateTiles(_context).Shuffle(),
                    RoundPlayers = new List <RoundPlayer>(),
                    RoundResults = new List <RoundResult>()
                };

                List <RoundPlayer> roundPlayers = new List <RoundPlayer>();

                if (lastRound == null)
                {
                    game.Status = GameStatus.Playing;
                    Player firstDealer = game.GamePlayers.First(u => u.InitialSeatWind == WindDirection.East).Player;
                    newRound.Wind         = WindDirection.East;
                    newRound.RoundCounter = 1;
                    foreach (var gp in game.GamePlayers)
                    {
                        var rp = new RoundPlayer {
                            GamePlayerId = gp.Id, GamePlayer = gp, Round = newRound, Wind = gp.InitialSeatWind.Value, Points = gp.Points
                        };
                        if (gp.PlayerId == firstDealer.Id)
                        {
                            rp.IsInitialDealer = true;
                            rp.IsDealer        = true;
                            rp.IsMyTurn        = true;
                            rp.MustThrow       = true;
                        }
                        roundPlayers.Add(rp);
                    }
                }
                else
                {
                    newRound.RoundCounter = lastRound.RoundCounter + 1;
                    var lastRoundDealer = lastRound.RoundPlayers.First(u => u.IsDealer);

                    //if this is not the first round
                    //last round check
                    //1.) if the winner of last round == dealer then no wind change
                    //2.) if last round "IsTied" set to true then no wind change
                    if (lastRound.IsTied)
                    {
                        newRound.Wind = lastRound.Wind;
                        roundPlayers.AddRange(GetNewUserRounds(lastRound.RoundPlayers, sameRound: true, lastRoundDealer.Wind));
                    }
                    else
                    {
                        //if last game is not tied, then there gotta be a winner here
                        //could be more than one winners here
                        var lastRoundWinners   = lastRound.RoundResults.Where(x => x.PlayResult == PlayResult.Win);
                        var dealerWonLastRound = lastRoundWinners.Any(x => x.PlayerId == lastRoundDealer.GamePlayer.Player.Id);

                        if (dealerWonLastRound)
                        {
                            newRound.Wind = lastRound.Wind;
                            roundPlayers.AddRange(GetNewUserRounds(lastRound.RoundPlayers, sameRound: true, lastRoundDealer.Wind));
                        }
                        else
                        {
                            //determine nextdealer
                            var windOfNextDealer = NextWindClockWise(lastRoundDealer.Wind);
                            roundPlayers.AddRange(GetNewUserRounds(lastRound.RoundPlayers, sameRound: false, windOfNextDealer));
                            var roundWindChanged = roundPlayers.Any(p => p.IsDealer == true && p.IsInitialDealer == true);
                            newRound.Wind = roundWindChanged ? NextWindClockWise(lastRound.Wind) : lastRound.Wind;
                        }
                    }
                }

                foreach (var ur in roundPlayers)
                {
                    newRound.RoundPlayers.Add(ur);
                }

                var theDealer = roundPlayers.First(u => u.IsDealer);

                var dealerId = theDealer.GamePlayerId;

                //for debugging
                //RoundTileHelper.SetupForWinPongChowPriority(newRound.RoundTiles);

                //tiles assignment and sorting
                foreach (var gamePlayer in game.GamePlayers)
                {
                    if (gamePlayer.Id == dealerId)
                    {
                        RoundTileHelper.AssignTilesToUser(14, gamePlayer.Player.UserName, newRound.RoundTiles);
                        //set one tile status to be justpicked
                        newRound.RoundTiles.First(rt => rt.Owner == gamePlayer.Player.UserName && rt.Tile.TileType != TileType.Flower).Status = TileStatus.UserJustPicked;
                        var playerTiles = newRound.RoundTiles.Where(rt => rt.Owner == gamePlayer.Player.UserName && (rt.Status == TileStatus.UserActive || rt.Status == TileStatus.UserJustPicked)).ToList();
                        RoundTileHelper.AssignAliveTileCounter(playerTiles);
                    }
                    else
                    {
                        RoundTileHelper.AssignTilesToUser(13, gamePlayer.Player.UserName, newRound.RoundTiles);
                        var playerTiles = newRound.RoundTiles.Where(rt => rt.Owner == gamePlayer.Player.UserName && rt.Status == TileStatus.UserActive).ToList();
                        RoundTileHelper.AssignAliveTileCounter(playerTiles);
                    }
                }

                _context.Rounds.Add(newRound);

                var success = await _context.SaveChangesAsync() > 0;

                List <RoundDto> results = new List <RoundDto>();

                foreach (var p in newRound.RoundPlayers)
                {
                    results.Add(_mapper.Map <Round, RoundDto>(newRound, opt => opt.Items["MainRoundPlayer"] = p));
                }

                if (success)
                {
                    return(results);
                }

                throw new Exception("Problem creating a new round");
            }
Ejemplo n.º 22
0
 internal void PlayerDisconnected(RoundPlayer player) => connectedPlayers.Remove(player.NetworkPlayerID.ToString());
Ejemplo n.º 23
0
 internal void PlayerConnected(RoundPlayer player)
 {
     allPlayers[player.NetworkPlayerID.ToString()]       = new HoldfastPlayer(player);
     connectedPlayers[player.NetworkPlayerID.ToString()] = new HoldfastPlayer(player);
 }
Ejemplo n.º 24
0
 internal HoldfastPlayer(RoundPlayer player)
 {
     this.player = player;
 }
Ejemplo n.º 25
0
 private void OnPlayerDisconnected(RoundPlayer roundPlayer) => Puts($"{roundPlayer.PlayerBase.name} Disconnected");
Ejemplo n.º 26
0
            private bool AssignPlayerActions(Round round, RoundPlayer throwerPlayer)
            {
                //TODO: Support multiple winner
                bool foundActionForUser = false;
                var  roundTiles         = round.RoundTiles;

                //there will be action except for the player that throw the tile
                var players = round.RoundPlayers.Where(rp => rp.GamePlayer.Player.UserName != throwerPlayer.GamePlayer.Player.UserName);

                var boardActiveTile = roundTiles.FirstOrDefault(rt => rt.Status == TileStatus.BoardActive);

                if (boardActiveTile == null)
                {
                    throw new RestException(HttpStatusCode.NotFound, new { Round = "Could not find active board tile" });
                }

                var nextPlayer = RoundHelper.GetNextPlayer(round.RoundPlayers, throwerPlayer.Wind);

                //there could be more than one possible action given user's turn  and the tile's thrown
                foreach (var player in players)
                {
                    var userTiles = roundTiles.Where(rt => rt.Owner == player.GamePlayer.Player.UserName);
                    List <RoundPlayerAction> rpas = new List <RoundPlayerAction>();

                    if (RoundHelper.DetermineIfUserCanWin(round, player, _pointCalculator))
                    {
                        rpas.Add(new RoundPlayerAction {
                            ActionType = ActionType.Win, ActionStatus = ActionStatus.Inactive
                        });
                    }

                    if (DetermineIfUserCanKongFromBoard(userTiles, boardActiveTile))
                    {
                        rpas.Add(new RoundPlayerAction {
                            ActionType = ActionType.Kong, ActionStatus = ActionStatus.Inactive
                        });
                    }

                    if (DetermineIfUserCanPong(userTiles, boardActiveTile))
                    {
                        rpas.Add(new RoundPlayerAction {
                            ActionType = ActionType.Pong, ActionStatus = ActionStatus.Inactive
                        });
                    }

                    if (player.GamePlayer.Player.UserName == nextPlayer.GamePlayer.Player.UserName)
                    {
                        var nextPlayerTiles = round.RoundTiles.Where(rt => rt.Owner == nextPlayer.GamePlayer.Player.UserName);
                        if (DetermineIfUserCanChow(nextPlayerTiles, boardActiveTile))
                        {
                            rpas.Add(new RoundPlayerAction {
                                ActionType = ActionType.Chow, ActionStatus = ActionStatus.Inactive
                            });
                        }
                    }

                    if (rpas.Count() > 0)
                    {
                        foundActionForUser = true;
                        foreach (var pa in rpas)
                        {
                            player.RoundPlayerActions.Add(pa);
                        }
                    }
                }

                return(foundActionForUser);
            }