public CorrectViewModelTest()
        {
            _teams = GenerateTeamList();
            _enabledTeams = new Teams();

            foreach(Team team in _teams)
            {
                if (team.TeamEnabled)
                {
                    _enabledTeams.Add(team);
                }
            }

            _quizzes = GenerateQuizzesList();
            _rounds = _quizzes.Where(q => q.QuizEnabled).FirstOrDefault().QuizRounds;

            _teamServiceMock = new Mock<ITeamService>();
            _teamServiceMock.Setup(tS => tS.GetAllTeams()).ReturnsAsync(_teams);
            _teamServiceMock.Setup(tS => tS.PatchTeamScore(It.IsAny<int>(), It.IsAny<int>())).ReturnsAsync(true);
            _roundServiceMock = new Mock<IRoundService>();
            _roundServiceMock.Setup(rS => rS.GetAllRoundsByEnabledQuiz()).ReturnsAsync(_rounds);
            _navigationServiceExMock = new Mock<INavigationServiceEx>();

            _sut = new CorrectViewModel(_teamServiceMock.Object, _roundServiceMock.Object, _navigationServiceExMock.Object);
        }
Beispiel #2
0
        public int Throw(int number = 10)
        {
            Round last = Rounds.Last();

            if (last.FirstThrow == 0)
            {
                last.FirstThrow = number;
                Sum            += number;
            }
            else
            {
                if (number == 10)
                {
                    last.IsStrike    = true;
                    last.SecondThrow = 0;
                }
                else
                {
                    last.SecondThrow = number;
                    Sum += number;
                }
                if (last.FirstThrow + last.SecondThrow == 10 && last.IsStrike == false)
                {
                    last.IsSpare = true;
                }
                last.RoundPoints = last.FirstThrow + last.SecondThrow;
                AddSpareBonus();
                AddStrikeBonus();
                Rounds.Add(new Round());
            }

            return(number);
        }
Beispiel #3
0
 public void AddRound_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         if (r_Count > 5)
         {
             throw new Exception();
         }
         {
             Warning2.Visibility = Visibility.Collapsed;
             TextBox t = new TextBox();
             t.Name                = "Round" + r_Count;
             t.PlaceholderText     = "Round " + r_Count;
             t.HorizontalAlignment = HorizontalAlignment.Stretch;
             t.VerticalAlignment   = VerticalAlignment.Stretch;
             t.Height              = 100;
             t.TextWrapping        = TextWrapping.Wrap;
             t.Margin              = new Thickness(0, 10, 0, 0);
             t.Foreground          = TextBox1.Foreground;
             Rounds.Children.Add(t);
             Rounds.UpdateLayout();
             r_Count++;
         }
     }
     catch (Exception)
     {
         Warning2.Text       = "Can not add more than 5 rounds";
         Warning2.Visibility = Visibility.Visible;
     }
 }
        /// <summary>
        /// Add a given Poker round to the Player
        /// </summary>
        /// <param name="convertedRound">
        /// The converted Round.
        /// </param>
        public IConvertedPokerPlayer Add(IConvertedPokerRound convertedRound)
        {
            try
            {
                if (convertedRound == null)
                {
                    throw new ArgumentNullException("convertedRound");
                }

                if (Rounds.Count < 4)
                {
                    Rounds.Add(convertedRound);
                }
                else
                {
                    throw new ArgumentOutOfRangeException("convertedRound");
                }
            }
            catch (Exception excep)
            {
                Log.Error("Unexpected", excep);
            }

            return(this);
        }
Beispiel #5
0
        public Round Run(IEnumerable <UserInGame> userGames)
        {
            if (!_gameStarted)
            {
                throw new GameNotStartedException();
            }

            if (TotalRounds == CurrentRound)
            {
                throw new GameOverException();
            }

            var randomNumber = _randomGenerator.Generate(_maxGuessNo);

            var winner = userGames
                         .Select(u =>
                                 new
            {
                Id   = u.UserId,
                Diff = Math.Abs(u.Number - randomNumber)
            })
                         .OrderBy(a => a.Diff)
                         .First();

            CurrentRound++;

            RoundsLeft--;
            var lastRound = TotalRounds == CurrentRound;

            var newRound = new Round(Id, randomNumber, winner.Id, CurrentRound, lastRound);

            Rounds.Add(newRound);

            return(newRound);
        }
Beispiel #6
0
        private bool ManageRoundRemoval(RoundBase round)
        {
            bool containsSoughtRound = Rounds.Contains(round);

            if (containsSoughtRound)
            {
                bool removalSuccessful = Rounds.Remove(round);

                if (removalSuccessful)
                {
                    round.MarkForDeletion();

                    bool stillContainsRounds = Rounds.Count > 0;
                    if (stillContainsRounds)
                    {
                        GetFirstRound().Construct();
                    }

                    FindIssues();
                    return(true);
                }
            }

            return(false);
        }
Beispiel #7
0
    private void handleGamble(RaycastHit hit)
    {
        // Do Gamble
        tankClicked = hit.transform.gameObject;
        CoordinateSet currentTankCoordinates = new CoordinateSet((int)tankClicked.transform.position.x, (int)tankClicked.transform.position.z);
        Tank          currentTank            = gs.getPlayerTank(playerTurn, currentTankCoordinates);

        // If the player didn't choose one of their own tanks, or if that tank is dead, just ignore
        if (currentTank.isDead() || currentTank.getPlayer().getPlayerColor() != playerTurn)
        {
            tankClicked = null;
            return;
        }

        string powerup = gs.playerGamble(playerTurn, currentTankCoordinates);

        // Print log message
        Debug.Log("Player " + playerTurn + "'s gamble results in: " + powerup);

        // Update the state
        tankClicked = null;
        round       = Rounds.Move;
        changeTurns();
        printTurn();
        gs.updatePlayerHealthBars(hpController);
        updateTooltips("Move1");
        numGambles++;
        gs.toggleTankRings(redTanks, new CoordinateSet(-1, -1), false);
        gs.toggleTankRings(blueTanks, new CoordinateSet(-1, -1), false);
    }
Beispiel #8
0
        public void ThrowRound(int number = 10)
        {
            Round round = new Round();

            AddStrikeBonus();

            int firtsThrow = Throw(number);
            int secondThrow;

            AddSpareBonus();

            if (firtsThrow == 10)
            {
                round.IsStrike = true;
                secondThrow    = 0;
            }
            else
            {
                secondThrow = Throw(firtsThrow);
            }

            if (firtsThrow + secondThrow == 10 && round.IsStrike == false)
            {
                round.IsSpare = true;
            }

            round.FirstThrow  = firtsThrow;
            round.SecondThrow = secondThrow;
            round.RoundPoints = firtsThrow + secondThrow;

            Rounds.Add(round);
        }
Beispiel #9
0
 public CcjRound GetCurrentInputRegisterableRound()
 {
     using (RoundsListLock.Lock())
     {
         return(Rounds.First(x => x.Status == CcjRoundStatus.Running && x.Phase == CcjRoundPhase.InputRegistration));                // not FirstOrDefault, it must always exist
     }
 }
Beispiel #10
0
 public IEnumerable <CcjRound> GetRunningRounds()
 {
     using (RoundsListLock.Lock())
     {
         return(Rounds.Where(x => x.Status == CcjRoundStatus.Running).ToArray());
     }
 }
Beispiel #11
0
        public async Task <ActionResult> Post([FromBody] Rounds round)
        {
            context.Round.Add(round);
            await context.SaveChangesAsync();

            return(new CreatedAtRouteResult("GetRound", new { id = round.Id }, round));
        }
Beispiel #12
0
        public void StartNewRound()
        {
            var newRound = new Round();

            Rounds.Add(newRound);
            _currentRound = newRound;
        }
        public void LockPlayerList()
        {
            if (Players.Count % 2 != 0)
            {
                throw new InvalidOperationException("No se puede bloquear la lista de jugadores con un número impar.");
            }
            if (Players.Count == 0)
            {
                throw new InvalidOperationException("No se puede bloquear la lista de jugadores sin tener al menos uno.");
            }

            SaveWithBackup("prelock");

            PlayerListLocked = true;
            Rounds.ToList().ForEach((round) =>
            {
                round.Active = false;
                round.OnPropertyChanged("Active");
            });
            Rounds.First().Active = true;
            Rounds.First().OnPropertyChanged("Active");

            OnPropertyChanged("PlayerListLocked");

            Save();
        }
Beispiel #14
0
 public CcjRound TryGetRound(string roundHash)
 {
     using (RoundsListLock.Lock())
     {
         return(Rounds.SingleOrDefault(x => x.RoundHash == roundHash));
     }
 }
Beispiel #15
0
        private void OnRoundsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            RaisePropertyChanged(() => MostDamageWeapon);
            RaisePropertyChanged(() => WinStatus);

            ClutchWonCount  = Players.Sum(p => p.ClutchWonCount);
            ClutchCount     = Players.Sum(p => p.ClutchCount);
            ClutchLostCount = Players.Sum(p => p.ClutchLostCount);

            if (Rounds.Any())
            {
                KillPerRound   = GetKillPerRound();
                DeathPerRound  = GetKillPerRound();
                AssistPerRound = GetAssistPerRound();
                MvpCount       = Players.Sum(p => p.RoundMvpCount);
                DeathPerRound  = Math.Round((double)DeathCount / Rounds.Count, 2);
            }

            if (Players.Any())
            {
                float totalHltv = Players.Sum(player => player.RatingHltv);
                AverageHltvRating = totalHltv / Players.Count;
                decimal totalEseaRws = Players.Sum(player => player.EseaRws);
                AverageEseaRws = Math.Round(totalEseaRws / Players.Count, 2);
            }
        }
Beispiel #16
0
 public IEnumerable <Money> GetAllQueuedCoinAmounts()
 {
     lock (StateLock)
     {
         return(WaitingList.Keys.Concat(Rounds.SelectMany(x => x.CoinsRegistered)).Select(x => x.Amount).ToArray());
     }
 }
Beispiel #17
0
    void Update()
    {
        if (round == Rounds.Startup)
        {
            if (gamepad1.GetButtonDown("Start") || gamepad2.GetButtonDown("Start"))
            {
                round        = Rounds.Wait;
                roundCorWait = StartCoroutine(WaitCor());
            }
        }

        if (round == Rounds.Fight)
        {
            if (health1 == 0)
            {
                round = Rounds.End;
                StartCoroutine(EndGame(player2));
            }

            if (health2 == 0)
            {
                round = Rounds.End;
                StartCoroutine(EndGame(player1));
            }
        }

        ElevatorFeedback();
    }
Beispiel #18
0
 public CcjRound TryGetRound(long roundId)
 {
     using (RoundsListLock.Lock())
     {
         return(Rounds.SingleOrDefault(x => x.RoundId == roundId));
     }
 }
Beispiel #19
0
 public IEnumerable <OutPoint> GetSpentCoins()
 {
     lock (StateLock)
     {
         return(WaitingList.Keys.Concat(Rounds.SelectMany(x => x.CoinsRegistered)).Where(x => x.IsSpent()).Select(x => x.OutPoint).ToArray());
     }
 }
Beispiel #20
0
 public bool Contains(SmartCoin coin)
 {
     lock (StateLock)
     {
         return(WaitingList.ContainsKey(coin) || Rounds.Any(x => x.CoinsRegistered.Contains(coin)));
     }
 }
Beispiel #21
0
    public static void highlightValidTiles(ArrayList listOfTileCoordinates, Rounds round)
    {
        GameObject    grid = GameObject.FindGameObjectWithTag("Grid");
        GameObject    child;
        MeshRenderer  meshRenderer;
        CoordinateSet currentCoordinates;

        for (int i = 0; i < grid.transform.childCount; i++)
        {
            child        = grid.transform.GetChild(i).gameObject;
            meshRenderer = child.GetComponent <MeshRenderer>();

            for (int j = 0; j < listOfTileCoordinates.Count; j++)
            {
                currentCoordinates = (CoordinateSet)listOfTileCoordinates[j];

                if ((int)child.transform.position.x == currentCoordinates.getX() && (int)child.transform.position.z == currentCoordinates.getY())
                {
                    if (round == Rounds.Move)
                    {
                        meshRenderer.material.color = Color.gray;
                    }
                    else if (round == Rounds.Attack)
                    {
                        meshRenderer.material.color = Color.red;
                    }
                }
            }
        }
    }
Beispiel #22
0
 public IEnumerable <OutPoint> GetAllRegisteredCoins()
 {
     lock (StateLock)
     {
         return(Rounds.SelectMany(x => x.CoinsRegistered).Select(x => x.OutPoint).ToArray());
     }
 }
Beispiel #23
0
 public Money SumAllQueuedCoinAmounts()
 {
     lock (StateLock)
     {
         return(WaitingList.Keys.Concat(Rounds.SelectMany(x => x.CoinsRegistered)).Sum(x => x.Amount));
     }
 }
Beispiel #24
0
 public int CountAllQueuedCoins()
 {
     lock (StateLock)
     {
         return(WaitingList.Count + Rounds.Sum(x => x.CoinsRegistered.Count()));
     }
 }
Beispiel #25
0
 public async Task <RoundState[]> GetStatusAsync(CancellationToken cancellationToken)
 {
     using (await AsyncLock.LockAsync(cancellationToken).ConfigureAwait(false))
     {
         return(Rounds.Select(x => RoundState.FromRound(x)).ToArray());
     }
 }
Beispiel #26
0
 public SmartCoin GetSingleOrDefaultCoin(OutPoint coinReference)
 {
     lock (StateLock)
     {
         return(WaitingList.Keys.Concat(Rounds.SelectMany(x => x.CoinsRegistered)).SingleOrDefault(x => x.OutPoint == coinReference));
     }
 }
Beispiel #27
0
            public static void Prefix(UnitEntityData initiator, BlueprintUnit blueprint, Vector3 position, ref Rounds duration, ref int level, RuleSummonUnit __instance)
            {
                Mod.Debug($"old duration: {duration} level: {level} \n mult: {settings.summonDurationMultiplier1} levelInc: {settings.summonLevelModifier1}\n initiatior: {initiator} tweakTarget: {settings.summonTweakTarget1} shouldTweak: {UnitEntityDataUtils.CheckUnitEntityData(initiator, settings.summonTweakTarget1)}");
                if (UnitEntityDataUtils.CheckUnitEntityData(initiator, settings.summonTweakTarget1))
                {
                    if (settings.summonDurationMultiplier1 != 1)
                    {
                        duration = new Rounds(Convert.ToInt32(duration.Value * settings.summonDurationMultiplier1));
                    }
                    if (settings.summonLevelModifier1 != 0)
                    {
                        level = Math.Max(0, Math.Min(level + (int)settings.summonLevelModifier1, 20));
                    }
                }
                else if (UnitEntityDataUtils.CheckUnitEntityData(initiator, settings.summonTweakTarget2))
                {
                    if (settings.summonDurationMultiplier2 != 1)
                    {
                        duration = new Rounds(Convert.ToInt32(duration.Value * settings.summonDurationMultiplier2));
                    }
                    if (settings.summonLevelModifier2 >= 0)
                    {
                        level = Math.Max(0, Math.Min(level + (int)settings.summonLevelModifier1, 20));
                    }
                }
                Mod.Debug($"new duration: {duration} level: {level}");

                if (settings.toggleMakeSummmonsControllable)
                {
                    SummonedByPlayerFaction = initiator.IsPlayerFaction;
                }
                Mod.Debug("Initiator: " + initiator.CharacterName + $"(PlayerFaction : {initiator.IsPlayerFaction})" + "\nBlueprint: " + blueprint.CharacterName + "\nDuration: " + duration.Value);
            }
Beispiel #28
0
        public async Task MakeSureTwoRunningRoundsAsync()
        {
            using (await RoundsListLock.LockAsync())
            {
                int runningRoundCount = Rounds.Count(x => x.Status == CcjRoundStatus.Running);
                if (runningRoundCount == 0)
                {
                    var round = new CcjRound(RpcClient, UtxoReferee, RoundConfig);
                    round.CoinJoinBroadcasted += Round_CoinJoinBroadcasted;
                    round.StatusChanged       += Round_StatusChangedAsync;
                    await round.ExecuteNextPhaseAsync(CcjRoundPhase.InputRegistration);

                    Rounds.Add(round);

                    var round2 = new CcjRound(RpcClient, UtxoReferee, RoundConfig);
                    round2.StatusChanged       += Round_StatusChangedAsync;
                    round2.CoinJoinBroadcasted += Round_CoinJoinBroadcasted;
                    await round2.ExecuteNextPhaseAsync(CcjRoundPhase.InputRegistration);

                    Rounds.Add(round2);
                }
                else if (runningRoundCount == 1)
                {
                    var round = new CcjRound(RpcClient, UtxoReferee, RoundConfig);
                    round.StatusChanged       += Round_StatusChangedAsync;
                    round.CoinJoinBroadcasted += Round_CoinJoinBroadcasted;
                    await round.ExecuteNextPhaseAsync(CcjRoundPhase.InputRegistration);

                    Rounds.Add(round);
                }
            }
        }
Beispiel #29
0
        // load rounds for compo
        public async Task ExecuteLoadRoundsCommand()
        {
            if (IsBusy)
            {
                return;
            }

            IsBusy = true;

            //DoStuff
            Rounds = await azureService.GetRoundsForCompetition(SelectedCompetition?.CompetitionId);

            IsBusy = false;

            if (Rounds.Count > 0)
            {
                // set round pref on dropdown
                string roundId = Preferences.Get("RoundId", null);
                if (roundId != null)
                {
                    var round = Rounds.FirstOrDefault(o => o.RoundId == roundId);
                    if (round != null)
                    {
                        SelectedRound = round;
                        Debug.WriteLine("Set SelectedRound to " + round.CourseName);
                    }
                }
            }
        }
Beispiel #30
0
        public async Task MakeSureTwoRunningRoundsAsync(Money feePerInputs = null, Money feePerOutputs = null)
        {
            using (await RoundsListLock.LockAsync())
            {
                int runningRoundCount = Rounds.Count(x => x.Status == CcjRoundStatus.Running);

                int confirmationTarget = await AdjustConfirmationTargetAsync(lockCoinJoins : true);

                if (runningRoundCount == 0)
                {
                    var round = new CcjRound(RpcClient, UtxoReferee, RoundConfig, confirmationTarget, RoundConfig.ConfirmationTarget.Value, RoundConfig.ConfirmationTargetReductionRate.Value);
                    round.CoinJoinBroadcasted += Round_CoinJoinBroadcasted;
                    round.StatusChanged       += Round_StatusChangedAsync;
                    await round.ExecuteNextPhaseAsync(CcjRoundPhase.InputRegistration, feePerInputs, feePerOutputs);

                    Rounds.Add(round);

                    var round2 = new CcjRound(RpcClient, UtxoReferee, RoundConfig, confirmationTarget, RoundConfig.ConfirmationTarget.Value, RoundConfig.ConfirmationTargetReductionRate.Value);
                    round2.StatusChanged       += Round_StatusChangedAsync;
                    round2.CoinJoinBroadcasted += Round_CoinJoinBroadcasted;
                    await round2.ExecuteNextPhaseAsync(CcjRoundPhase.InputRegistration, feePerInputs, feePerOutputs);

                    Rounds.Add(round2);
                }
                else if (runningRoundCount == 1)
                {
                    var round = new CcjRound(RpcClient, UtxoReferee, RoundConfig, confirmationTarget, RoundConfig.ConfirmationTarget.Value, RoundConfig.ConfirmationTargetReductionRate.Value);
                    round.StatusChanged       += Round_StatusChangedAsync;
                    round.CoinJoinBroadcasted += Round_CoinJoinBroadcasted;
                    await round.ExecuteNextPhaseAsync(CcjRoundPhase.InputRegistration, feePerInputs, feePerOutputs);

                    Rounds.Add(round);
                }
            }
        }
 public static PokerHandHistory.Card[] Board(this PokerHand hand, Rounds round)
 {
     switch (round)
     {
         case Rounds.PREFLOP: return new PokerHandHistory.Card[0];
         case Rounds.FLOP: return new PokerHandHistory.Card[] { hand.Flop.CommunityCards[0], hand.Flop.CommunityCards[1], hand.Flop.CommunityCards[2] };
         case Rounds.TURN: return new PokerHandHistory.Card[] { hand.Flop.CommunityCards[0], hand.Flop.CommunityCards[1], hand.Flop.CommunityCards[2], hand.Turn.CommunityCards[0] };
         case Rounds.RIVER: return new PokerHandHistory.Card[] { hand.Flop.CommunityCards[0], hand.Flop.CommunityCards[1], hand.Flop.CommunityCards[2], hand.Turn.CommunityCards[0], hand.River.CommunityCards[0] };
         default: throw new Exception("Unknown round: " + round.ToString());
     }
 }
Beispiel #32
0
        public void Parse(string response)
        {
            XmlDocument xml = new XmlDocument(); //* create an xml document object.
            XmlTextReader xmlTextReader = new XmlTextReader(new StringReader(response));
            xml.Load(xmlTextReader);

            try
            {
                XmlNodeList xmlRounds = xml.SelectNodes("GetLeagueRounds/Rounds/Round");
                rounds = RoundParsing.ParseRounds(xmlRounds);
            }
            catch
            {
                throw new InvalidStateException("Answer from the server is not well-formed.");
            }
        }
Beispiel #33
0
        public static Rounds ParseRounds(XmlNodeList roundsNodeList)
        {
            Rounds rounds = new Rounds();

            if (roundsNodeList.Count > 0)
            {
                foreach (XmlNode round in roundsNodeList)
                {
                    int roundID = int.Parse(round["ID"].InnerText);

                    TimeSpan bestTime;

                    if (!TimeSpan.TryParse(round["BestTime"].InnerText, out bestTime))
                    {
                        bestTime = TimeSpan.Zero;
                    }

                    rounds.Add(new Round(roundID, round["Name"].InnerText, round["Variant"].InnerText, bestTime));
                }
            }

            return rounds;
        }
 /// <summary>
 /// Converts the board cards to a ulong mask for analysis.
 /// </summary>
 /// <param name="hand">The hand to convert.</param>
 /// <param name="round">The maximum round to include in the board mask.</param>
 /// <returns>A ulong mask for use in analysis.</returns>
 public static ulong BoardMask(this PokerHand hand, Rounds round)
 {
     ulong result = 0UL;
     for (int i = 1; i <= (int)round; i++)
         result |= hand.Rounds[i].CommunityCards.ToMask();
     return result;
 }
        public weka.core.Instances[] GenerateFeatures(IEnumerable<PokerHand> hands, Rounds roundFilter = Rounds.NONE, bool regression = false)
        {
            weka.core.Instances[] data = regression ? GenerateRegressionInstances((int)roundFilter)
                                                    : new weka.core.Instances[] { GenerateClassifierInstances((int)roundFilter) };

            foreach(var hand in hands)
            {
                for (int rIdx = 0; rIdx < hand.Rounds.Length; rIdx++)
                {
                    // Optionally filter out rounds
                    if (roundFilter != Rounds.NONE && roundFilter != (Rounds)rIdx)
                        continue;

                    if(hand.Rounds[rIdx] == null || hand.Rounds[rIdx].Actions == null)
                        continue;

                    for (int aIdx = 0; aIdx < hand.Rounds[rIdx].Actions.Length; aIdx++)
                        if (hand.Rounds[rIdx].Actions[aIdx].Player == hand.Hero)
                            for(int dIdx = 0; dIdx < data.Length; dIdx++)
                            {
                                var inst = GenerateFeatures(hand, rIdx, aIdx, data[dIdx], !regression);
                                if(regression)
                                {
                                    switch (hand.Rounds[rIdx].Actions[aIdx].Type)
                                    {
                                        case ActionType.Bet:
                                        case ActionType.Raise: inst.setClassValue(dIdx == 2 ? 1 : 0);
                                        break;
                                        case ActionType.Call:
                                        case ActionType.Check: inst.setClassValue(dIdx == 1 ? 1 : 0);
                                        break;
                                        case ActionType.Fold: inst.setClassValue(dIdx == 0 ? 1 : 0);
                                        break;
                                        default:
                                        break;
                                    }
                                }
                                data[dIdx].add(inst);
                            }

                }
            }

            return data;
        }
        public weka.core.Instances GenerateClassifierFeatures(IEnumerable<PokerHand> hands, Rounds roundFilter = Rounds.NONE)
        {
            var data = GenerateClassifierInstances((int)roundFilter);

            foreach(var hand in hands)
            {
                for (int rIdx = 0; rIdx < hand.Rounds.Length; rIdx++)
                {
                    // Optionally filter out rounds
                    if (roundFilter != Rounds.NONE && roundFilter != (Rounds)rIdx)
                        continue;

                    if(hand.Rounds[rIdx] == null || hand.Rounds[rIdx].Actions == null)
                        continue;

                    for (int aIdx = 0; aIdx < hand.Rounds[rIdx].Actions.Length; aIdx++)
                        if (hand.Rounds[rIdx].Actions[aIdx].Player == hand.Hero)
                            data.add(GenerateFeatures(hand, rIdx, aIdx, data));
                }
            }

            return data;
        }
Beispiel #37
0
        private void recursiveBuildTree(Node root, int player, Rounds round,
                                        double pot, int[] bets, Dictionary<string, int> indexes)
        {
            if (root.terminal)
                return;

            _playerStates.Add(root.playerView());

            List<Node> children = new List<Node>();
            int pIdx = player - 1;
            int nextPlayer = player == 1 ? 2 : 1;

            // Can we raise?
            if (bets.Max() < _maxBetLevel[(int)round])
            {
                var betNode = new Node()
                {
                    action = Actions.Raise,
                    board = root.board,
                    hole1 = root.hole1,
                    hole2 = root.hole2,
                    round = round,
                    terminal = false,
                    isAction = true,
                    player = nextPlayer,
                    sequence = root.sequence + 'r'
                };
                SetNodeIndex(betNode, root, indexes);
                int prevBets = bets[pIdx];
                int betsToAdd = bets.Max() - prevBets + 1;//may need to add either 1 or 2 bets
                bets[pIdx] = bets.Max() + 1;
                recursiveBuildTree(betNode, player == 1 ? 2 : 1, round, pot + _betSize[(int)round] * betsToAdd, bets, indexes);
                bets[pIdx] = prevBets;

                children.Add(betNode);
            }

            // Can we fold?
            if(bets.Max() > 0)
            {
                var foldNode = new Node()
                {
                    action = Actions.Fold,
                    board = root.board,
                    hole1 = root.hole1,
                    hole2 = root.hole2,
                    round = round,
                    // take back the uncalled bet and return the payoff as half the pot
                    payoff = (pot - _betSize[(int)round]) / (player == 1 ? -2.0 : 2.0),
                    terminal = true,
                    isAction = true,
                    player = nextPlayer,
                    sequence = root.sequence + 'f'
                };
                SetNodeIndex(foldNode, root, indexes);
                children.Add(foldNode);
            }

            // If we call, is the round over?
            var callNode = new Node()
            {
                action = Actions.Call,
                board = root.board,
                hole1 = root.hole1,
                hole2 = root.hole2,
                round = round,
                isAction = true,
                player = nextPlayer,
                sequence = root.sequence + 'c'
            };
            if (bets.Max() == 0 && player == 1)// first to act in a round can check
            {
                callNode.terminal = false;
                recursiveBuildTree(callNode, 2, round, pot, bets, indexes);
            }
            else if (round == Rounds.Preflop) // calling a bet preflop
            {
                callNode.sequence += '/';
                callNode.round = Rounds.Flop;
                callNode.player = 1;
                int callAmt = root.action == Actions.Raise ? _betSize[0] : 0;
                recursiveBuildTree(callNode, 1, Rounds.Flop, pot + callAmt, new int[] { 0, 0 }, indexes);
            }
            else // calling a flop bet and seeing a showdown
            {
                callNode.terminal = true;
                double finalPot = (bets.Max() == 0 ? pot : pot + _betSize[1]) / 2.0;
                if (callNode.hole1 == callNode.hole2) // draw
                    callNode.payoff = 0;
                else if (callNode.hole1 == callNode.board) // p1 pair
                    callNode.payoff = finalPot;
                else if (callNode.hole2 == callNode.board) // p2 pair
                    callNode.payoff = -finalPot;
                else if(callNode.hole1 > callNode.hole2) // p1 high card with no pairs on board
                    callNode.payoff = finalPot;
                else // p2 high card with no pairs on board
                    callNode.payoff = -finalPot;
            }
            SetNodeIndex(callNode, root, indexes);
            children.Add(callNode);

            root.children = children.ToArray();
        }
Beispiel #38
0
        static void Main(string[] args)
        {
            //			Console.WriteLine("**** WARNING: HARD CODED PARAMETERS IN USE ****");
            //			args= @"/Users/wesley/Dropbox/Public/hands.xml /Users/wesley/poker/classifiers/datasets/river.arff -round river -regression".Split();

            #region Validate parameters
            if (args.Length < 2)
            {
                Console.WriteLine("Format: HoldemFeatures.exe <input> <output> [-option1 ...]");
                Console.WriteLine("Options:");

                // Delimiter
                Console.WriteLine("[d, delim, delimiter] <arg1>".PadRight(30) + "Sets the delimiter character for the output file.");
                Console.WriteLine("".PadRight(30) + "Setting arg1 to tab or \t will set the delimiter as tabs.");
                Console.WriteLine("".PadRight(30) + "Default: ,");

                // Round
                Console.WriteLine("[r, round] <arg1>".PadRight(30) + "Filters the actions to only those in the given round.");
                Console.WriteLine("".PadRight(30) + "Options: preflop, flop, turn, river, none");
                Console.WriteLine("".PadRight(30) + "Default: none (all rounds)");

                // Convert features to numeric values
                Console.WriteLine("[num, numeric]".PadRight(30) + "Automatically converts all features to numeric values.");
                Console.WriteLine("Default: disabled.".PadLeft(30));

                // Convert features to numeric values
                Console.WriteLine("[format] <arg1>".PadRight(30) + "Sets the file format to save to.");
                Console.WriteLine("".PadRight(30) + "Options: arff, csv");
                Console.WriteLine("Default: arff.".PadLeft(30));

                Console.WriteLine("[regress, regression]".PadRight(30) + "Generates datasets for regression rather than classification.");
                Console.WriteLine("Default: disabled (classification)".PadLeft(30));
                return;
            }

            for (int i = 2; i < args.Length; i++)
            {
                if (args[i][0] != '-')
                    continue;

                string flag = args[i].Substring(1).ToLower();
                switch (flag)
                {
                    case "delim":
                    case "d":
                    case "delimiter": DELIMITER = args[++i];
                        string delim = DELIMITER.ToLower();
                        if (delim == "tab" || delim == "tabs" || delim == "\\t")
                            DELIMITER = "\t";
                        break;
                    case "round":
                    case "r": ROUND_FILTER = (Rounds)Enum.Parse(typeof(Rounds), args[++i], true);
                        featureGen.SkipMissingFeatures = true;
                        break;
                    case "num":
                    case "numeric": featureGen.ConvertFeaturesToNumeric = true;
                        break;
                    case "format": FILE_FORMAT = args[++i].ToLower();
                    if(FILE_FORMAT != "csv" && FILE_FORMAT != "arff")
                    {
                        Console.WriteLine("Unknown file format: {0}. Options are csv or arff", FILE_FORMAT);
                        return;
                    }
                    break;
                    case "regression":
                    case "regress": REGRESSION = true;
                    break;
                    default:
                        Console.WriteLine("Unknown flag: {0}", flag);
                        return;
                }
            }

            string inFilename = args[0];
            if (!File.Exists(inFilename))
            {
                Console.WriteLine("No input file found at {0}", inFilename);
                return;
            }
            #endregion

            #region Read in all hands
            Console.Write("Loading hand histories... ");
            PokerHandXML hands;
            using (TextReader reader = new StreamReader(inFilename))
            {
                XmlSerializer ser = new XmlSerializer(typeof(PokerHandXML));
                hands = (PokerHandXML)ser.Deserialize(reader);
            }
            Console.WriteLine("done.");
            Console.WriteLine("Loaded {0} hand{1}.", hands.Hands.Length, hands.Hands.Length == 1 ? "" : "s");
            #endregion

            #region Iterate over every hero action and generate features
            Console.WriteLine("Generating features...");
            weka.core.Instances[] features = featureGen.GenerateFeatures(hands.Hands, ROUND_FILTER, REGRESSION);
            Console.WriteLine("done.");
            Console.WriteLine("Generated {0} features for {1} decision{2}", features[0].numAttributes(), features[0].numInstances(), features[0].numInstances() == 1 ? "" : "s");
            #endregion

            #region Write the results to a delimited file
            Console.Write("Writing results to file... ");
            if(REGRESSION)
            {
                string filename = args[1].Insert(args[1].IndexOf('.'), "_{0}");
                writeFile(features[0], string.Format(filename, "fold"));
                writeFile(features[1], string.Format(filename, "call"));
                writeFile(features[2], string.Format(filename, "raise"));
            }
            else
                writeFile(features[0], args[1]);
               			Console.WriteLine("done.");
            #endregion
        }