コード例 #1
0
ファイル: WekaPlayer.cs プロジェクト: tansey/evolve_vs_expert
        public void GetAction(HandHistory history, out holdem_engine.Action.ActionTypes action, out double amount)
        {
            var xml = history.ToXmlHand();
            int rIdx = (int)history.CurrentRound - 1;
            int aIdx = xml.Rounds[rIdx].Actions.Length;
            var features = _featureGen.GenerateFeatures(xml, rIdx, aIdx, _instances[rIdx], false);

            var classifier = _models[rIdx];

            int result;
            // Mixed policies take a randomized action based on a probability distribution.
            if (MixedPolicy)
            {
                double[] dist = classifier.distributionForInstance(features);
                result = _rand.SampleFromDistribution(dist);
            }
            else
            {
                // Otherwise, the policy is a pure strategy taking deterministic actions.
                result = (int)classifier.classifyInstance(features);
            }
            if (result == 0)
                action = holdem_engine.Action.ActionTypes.Fold;
            else if (result == 1)
                action = holdem_engine.Action.ActionTypes.Call;
            else if (result == 2)
                action = holdem_engine.Action.ActionTypes.Raise;
            else
                throw new Exception("Unknown class: " + result);
            amount = 0;
        }
コード例 #2
0
        internal static IEnumerable <EquityRangeSelectorItemViewModel> GetHeroRange(HandHistories.Objects.Hand.HandHistory currentHandHistory, HandHistories.Objects.Cards.Street currentStreet)
        {
            if (currentHandHistory.Hero == null)
            {
                return(null);
            }

            if (init)
            {
                TempConfig.Init();
                HandHistory.Init();
                Card.Init();
                init = false;
            }

            var handAnalyzer = new HandAnalyzer();

            var handHistory = new HandHistory();

            handHistory.ConverToEquityCalculatorFormat(currentHandHistory, currentStreet);

            var heroRange = handAnalyzer.BuildPlayerRange(handHistory, currentHandHistory.Hero.PlayerName);

            return(GroupHands(heroRange));
        }
コード例 #3
0
        private static string GetPositionName(string playerName, HandHistory hand)
        {
            var position = Converter.ToPosition(hand, playerName);

            switch (position)
            {
            case EnumPosition.SB:
                return("SB");

            case EnumPosition.BB:
                return("BB");

            case EnumPosition.BTN:
                return("BTN");

            case EnumPosition.CO:
                return("CO");

            case EnumPosition.STRDL:
                return("STRDL");

            default:
                var tableSize = hand.HandActions.Select(x => x.PlayerName).Distinct().Count();

                if (positionTable.ContainsKey(tableSize) && positionTable[tableSize].ContainsKey(position))
                {
                    return(positionTable[tableSize][position]);
                }

                return(position.ToString());
            }
        }
コード例 #4
0
        public HandHistory ParseFullHandHistory(string handText, bool rethrowExceptions = false)
        {
            var JSON = GetJSONObject(handText);

            HandHistory hand = new HandHistory();

            hand.DateOfHandUtc        = ParseDateUtc(JSON);
            hand.DealerButtonPosition = ParseDealerPosition(JSON);
            hand.FullHandHistoryText  = handText;
            hand.HandId           = ParseHandId(JSON);
            hand.NumPlayersSeated = ParseNumPlayers(JSON);
            hand.TableName        = ParseTableName(JSON);
            hand.Players          = ParsePlayers(JSON);
            hand.HandActions      = AdjustHandActions(ParseHandActions(JSON));
            hand.Winners          = ParseWinners(JSON);
            hand.GameDescription  = ParseGameDescriptor(JSON);
            hand.CommunityCards   = ParseCommunityCards(JSON);

            string heroName = ParseHeroName(JSON);

            hand.Hero = hand.Players.FirstOrDefault(p => p.PlayerName == heroName);

            ParseExtraHandInformation(JSON, hand);

            FinalizeHandHistory(hand);

            return(hand);
        }
コード例 #5
0
ファイル: Main.cs プロジェクト: tansey/console_holdem
        public static void Main(string[] args)
        {
            Console.WriteLine("Loading opponents...");
            var seats = new Seat[6];
            seats[0] = new Seat(1, "TeeJayorTJ5", 1000, new WekaPlayer(CLASSIFIER_DIR + "preflop.model",CLASSIFIER_DIR + "flop.model",CLASSIFIER_DIR + "turn.model",CLASSIFIER_DIR + "river.model"));
            seats[1] = new Seat(2, "Dave_Wilkes", 1000, new WekaPlayer(CLASSIFIER_DIR + "preflop.model",CLASSIFIER_DIR + "flop.model",CLASSIFIER_DIR + "turn.model",CLASSIFIER_DIR + "river.model"));
            seats[2] = new Seat(3, "Some_Killa", 1000, new WekaPlayer(CLASSIFIER_DIR + "preflop.model",CLASSIFIER_DIR + "flop.model",CLASSIFIER_DIR + "turn.model",CLASSIFIER_DIR + "river.model"));
            seats[3] = new Seat(4, "Better_Boy", 1000, new WekaPlayer(CLASSIFIER_DIR + "preflop.model",CLASSIFIER_DIR + "flop.model",CLASSIFIER_DIR + "turn.model",CLASSIFIER_DIR + "river.model"));
            seats[4] = new Seat(5, "Kiddo1973", 1000, new WekaPlayer(CLASSIFIER_DIR + "preflop.model",CLASSIFIER_DIR + "flop.model",CLASSIFIER_DIR + "turn.model",CLASSIFIER_DIR + "river.model"));
            seats[5] = new Seat(6, "Human", 1000, new ConsolePlayer());
            var blinds = new double[] { 10, 20 };
            uint handNumber = 0;
            Console.WriteLine("Starting simulation");
            HandEngine engine = new HandEngine();
            while(true)
            {
                HandHistory results = new HandHistory(seats, handNumber, handNumber % (uint)seats.Length + 1, blinds, 0, BettingStructure.Limit);
                //engine.PlayHand(results, cachedHands[(int)handNumber]);
                engine.PlayHand(results);

                Console.WriteLine(results.ToString(true));
                Thread.Sleep(2000);

                foreach(var seat in seats)
                    if(seat.Chips == 0)
                    {
                        Console.WriteLine("{0} rebuys for $1000", seat.Name);
                        seat.Chips = 1000;
                    }

                handNumber++;
            }
        }
コード例 #6
0
        public void PotCalculatorTest_2()
        {
            HandHistory hand = new HandHistory();

            hand.HandActions = new List <HandAction>
            {
                new HandAction("P1", HandActionType.SMALL_BLIND, 0.1m, Objects.Cards.Street.Preflop),
                new HandAction("P2", HandActionType.BIG_BLIND, 0.2m, Objects.Cards.Street.Preflop),
                new HandAction("P1", HandActionType.CALL, 0.1m, Objects.Cards.Street.Preflop),
                new HandAction("P2", HandActionType.CHECK, 0m, Objects.Cards.Street.Preflop),

                new HandAction("P1", HandActionType.CHECK, 0m, Objects.Cards.Street.Flop),
                new HandAction("P2", HandActionType.CHECK, 0m, Objects.Cards.Street.Flop),

                new HandAction("P1", HandActionType.BET, 0.2m, Objects.Cards.Street.Turn),
                new HandAction("P2", HandActionType.CALL, 0.2m, Objects.Cards.Street.Turn),

                new HandAction("P1", HandActionType.CHECK, 0m, Objects.Cards.Street.River),
                new HandAction("P2", HandActionType.CHECK, 0m, Objects.Cards.Street.River),
            };

            hand.Winners = new List <WinningsAction>()
            {
                new WinningsAction("P1", WinningsActionType.WINS, 0.8m, 0),
            };

            TestRakeCalculator(0m, hand);
        }
コード例 #7
0
        public void TryBuildTest(string testFolder)
        {
            HandHistory actual = null;

            using (ShimsContext.Create())
            {
                ShimDateTime.UtcNowGet = () => handDate;

                var packages = ReadPackages(testFolder);

                CollectionAssert.IsNotEmpty(packages, $"Packages collection must be not empty for {testFolder}");

                var handBuilder = new Adda52HandBuilder();

                foreach (var package in packages)
                {
                    if (handBuilder.TryBuild(package, out actual))
                    {
                        break;
                    }
                }
            }

            Assert.IsNotNull(actual, $"Actual HandHistory must be not null for {testFolder}");

            var expected = ReadExpectedHandHistory(testFolder);

            Assert.IsNotNull(expected, $"Expected HandHistory must be not null for {testFolder}");

            AssertionUtils.AssertHandHistory(actual, expected);
        }
コード例 #8
0
 private void ProcessShowHandRSP(ShowHandRSP message, ClientRecord record, HandHistory history)
 {
     foreach (var handInfo in message.Info)
     {
         AddShowCardsAction(history, GetPlayer(history, handInfo.SeatID + 1), GetCards(handInfo));
     }
 }
コード例 #9
0
        private void ProcessAnte(Ante ante, HandHistory handHistory)
        {
            var anteAmount = (decimal)ante.Amount / handHistory.Players.Count;

            handHistory.GameDescription.Limit.Ante        = anteAmount;
            handHistory.GameDescription.Limit.IsAnteTable = true;

            var sbAction = handHistory.HandActions.FirstOrDefault(x => x.HandActionType == HandActionType.SMALL_BLIND);

            IEnumerable <Player> players;

            if (sbAction != null)
            {
                players = handHistory.Players
                          .SkipWhile(x => x.PlayerName != sbAction.PlayerName)
                          .Concat(handHistory.Players.TakeWhile(x => x.PlayerName != sbAction.PlayerName))
                          .Reverse();
            }
            else
            {
                players = handHistory.Players.Reverse();
            }

            foreach (var player in players)
            {
                var anteAction = new HandAction(player.PlayerName,
                                                HandActionType.ANTE,
                                                anteAmount,
                                                Street.Preflop);

                handHistory.HandActions.Insert(0, anteAction);
            }
        }
コード例 #10
0
        public void TableDescriptionIsParsedTest(string handHistoryFile, TableTypeDescription tableDescription)
        {
            var parser = new Poker888FastParserImpl();

            string rawHands = File.ReadAllText(handHistoryFile);
            var    hands    = parser.SplitUpMultipleHands(rawHands).ToArray();

            var succeded = 0;
            var total    = hands.Count();

            for (int i = 0; i < total; i++)
            {
                HandHistory hand = parser.ParseFullHandHistory(hands[i], true);
                var         tableTypeDescription = hand.GameDescription.TableType.FirstOrDefault();

                if (tableTypeDescription == tableDescription)
                {
                    succeded++;
                }
            }

            Assert.AreEqual(total, succeded);

            Debug.WriteLine("Processed hands: {0}/{1}", succeded, total);
        }
コード例 #11
0
        public void IsTournamentTest(string handHistoryFile, bool mustBeTournamet = true)
        {
            var parser = new Poker888FastParserImpl();

            string rawHands = File.ReadAllText(handHistoryFile);
            var    hands    = parser.SplitUpMultipleHands(rawHands).ToArray();

            List <bool> allIsTournaments = new List <bool>();

            for (int i = 0; i < hands.Count(); i++)
            {
                HandHistory hand = parser.ParseFullHandHistory(hands[i], true);

                if (hand.GameDescription.IsTournament)
                {
                    allIsTournaments.Add(true);
                }
                else
                {
                    allIsTournaments.Add(false);
                }
            }

            Assert.True(mustBeTournamet ? !allIsTournaments.Contains(false) : !allIsTournaments.Contains(true));
        }
コード例 #12
0
        private void AdjustHandHistory(HandHistory handHistory)
        {
            if (handHistory == null)
            {
                return;
            }

            HandHistoryUtils.UpdateAllInActions(handHistory);
            HandHistoryUtils.CalculateBets(handHistory);
            HandHistoryUtils.CalculateTotalPot(handHistory);
            HandHistoryUtils.RemoveSittingOutPlayers(handHistory);

            foreach (var player in handHistory.Players)
            {
                handHistory.HandActions
                .Where(x => x.PlayerName == player.PlayerName)
                .ForEach(x => x.PlayerName = player.PlayerNick);

                if (handHistory.HeroName == player.PlayerName)
                {
                    handHistory.HeroName = player.PlayerNick;
                }

                player.PlayerName = player.PlayerNick;
                player.PlayerNick = null;
            }
        }
コード例 #13
0
        public void GetAction(HandHistory history, out holdem_engine.Action.ActionTypes type, out double amount)
        {
            PokerHandHistory.PokerHand xml = history.ToXmlHand();

            PokerHandHistory.PokerHandXML hands = new PokerHandHistory.PokerHandXML()
            {
                Hands = new PokerHandHistory.PokerHand[] { xml }
            };

            StringBuilder sb = new StringBuilder();

            using (TextWriter writer = new StringWriter(sb))
            {
                XmlSerializer ser = new XmlSerializer(typeof(PokerHandHistory.PokerHandXML));
                ser.Serialize(writer, hands);
            }

            Console.WriteLine(sb.ToString());
            if (actions != null && curAction < actions.Length)
            {
                holdem_engine.Action action = actions[curAction++];
                type   = action.ActionType;
                amount = action.Amount;
            }
            else
            {
                type   = holdem_engine.Action.ActionTypes.Fold;
                amount = 0;
            }
        }
コード例 #14
0
ファイル: PKHandBuilder.cs プロジェクト: Michael-Z/DriveHud
        private void ProcessNoticeResetGame(NoticeResetGame noticeResetGame, HandHistory handHistory)
        {
            if (!long.TryParse(noticeResetGame.GameId, out long handId))
            {
                throw new DHInternalException(new NonLocalizableString($"Failed to parse hand id from '{noticeResetGame.GameId}'."));
            }

            var players = noticeResetGame.Players ?? throw new HandBuilderException(handId, "NoticeResetGame.Players must be not null.");

            handHistory.HandId = handId;

            foreach (var playerInfo in players)
            {
                var player = new Player
                {
                    PlayerName    = playerInfo.Playerid.ToString(),
                    PlayerNick    = playerInfo.Name,
                    StartingStack = playerInfo.Stake,
                    SeatNumber    = playerInfo.Seatid + 1,
                    IsSittingOut  = !playerInfo.InGame
                };

                handHistory.Players.Add(player);
            }
        }
コード例 #15
0
        private void CalculateEvDiffByPot(EquityPot pot, HandHistory handHistory, List <int> winnersBySeat)
        {
            if (winnersBySeat.Count == 0)
            {
                LogProvider.Log.Error($"Could not find a winner of pot #{pot.Index} hand #{handHistory.HandId}");
                return;
            }

            foreach (var player in pot.Players)
            {
                if (!pot.PlayersPutInPot.ContainsKey(player))
                {
                    continue;
                }

                var netWonPerWinner = (pot.Pot - pot.Rake) / winnersBySeat.Count - pot.PlayersPutInPot[player];

                var ev = (pot.Pot - pot.Rake) * player.Equity[pot.Index] - pot.PlayersPutInPot[player];

                if (winnersBySeat.Contains(player.Seat))
                {
                    player.EvDiff += ev - netWonPerWinner;
                    continue;
                }

                player.EvDiff += ev + pot.PlayersPutInPot[player];
            }
        }
コード例 #16
0
        public void GetAction(HandHistory history, out holdem_engine.Action.ActionTypes action, out double amount)
        {
            var xml = history.ToXmlHand();
            int rIdx = (int)history.CurrentRound - 1;
            int aIdx = xml.Rounds[rIdx].Actions.Length;
            var features = _featureGen.GenerateMonolithicNeuralNetworkFeatures(xml, rIdx, aIdx, false);

            for(int i = 0; i < features.Length; i++)
            {
                var feature = features[i];
                if(feature < 0 || feature > 1)
                {
                    _featureGen.PrintFeatureList();
                    throw new Exception(string.Format("Feature {0}: {1}", i, feature));
                }
            }

            //			Console.WriteLine("{0} features", features.Length);
            //			Console.WriteLine("Features: {0}", features.Flatten());
            var probs = _network.Activate(features);
            //Console.WriteLine("Raw Probs: {0}", probs.Flatten());
            probs.Normalize();
            //Console.WriteLine("Normalized: {0}", probs.Flatten());
            int result = _rand.SampleFromDistribution(probs);

            if (result == 0)
                action = holdem_engine.Action.ActionTypes.Fold;
            else if (result == 1)
                action = holdem_engine.Action.ActionTypes.Call;
            else if (result == 2)
                action = holdem_engine.Action.ActionTypes.Raise;
            else
                throw new Exception("Unknown class: " + result);
            amount = 0;
        }
コード例 #17
0
        private static string ConvertGameType(HandHistory handHistory)
        {
            switch (handHistory.GameDescription.GameType)
            {
            case GameType.FixedLimitHoldem:
                return("FL Holdem");

            case GameType.FixedLimitOmaha:
                return("FL Omaha");

            case GameType.FixedLimitOmahaHiLo:
                return("FL Omaha HiLo");

            case GameType.NoLimitOmaha:
                return("NL Omaha");

            case GameType.NoLimitOmahaHiLo:
                return("NL Omaha HiLo");

            case GameType.PotLimitHoldem:
                return("PL Holdem");

            case GameType.CapPotLimitOmaha:
            case GameType.FiveCardPotLimitOmaha:
            case GameType.PotLimitOmaha:
                return("PL Omaha");

            case GameType.FiveCardPotLimitOmahaHiLo:
            case GameType.PotLimitOmahaHiLo:
                return("PL Omaha HiLo");

            default:
                return("NL Holdem");
            }
        }
コード例 #18
0
        /// <summary>
        /// Adjusts seat types of the specified <see cref="HandHistory"/>
        /// </summary>
        /// <param name="handHistory"><see cref="HandHistory"/> to adjust</param>
        protected override void AdjustSeatTypes(HandHistory handHistory)
        {
            if (!handHistory.GameDescription.SeatType.IsUnknown)
            {
                return;
            }

            var maxSeatNumber = handHistory.Players.MaxOrDefault(x => x.SeatNumber);

            if (maxSeatNumber > 9)
            {
                handHistory.GameDescription.SeatType = SeatType.FromMaxPlayers(10);
            }
            else if (maxSeatNumber > 8)
            {
                handHistory.GameDescription.SeatType = SeatType.FromMaxPlayers(9);
            }
            else if (maxSeatNumber > 6)
            {
                handHistory.GameDescription.SeatType = SeatType.FromMaxPlayers(8);
            }
            else if (maxSeatNumber > 3)
            {
                handHistory.GameDescription.SeatType = SeatType.FromMaxPlayers(6);
            }
            else if (maxSeatNumber > 2 && handHistory.GameDescription.IsTournament)
            {
                handHistory.GameDescription.SeatType = SeatType.FromMaxPlayers(3);
            }
            else
            {
                handHistory.GameDescription.SeatType = SeatType.FromMaxPlayers(2);
            }
        }
コード例 #19
0
        public void GetAction(HandHistory history,
		                      out holdem_engine.Action.ActionTypes type, out double amount)
        {
            PokerHandHistory.PokerHand xml = history.ToXmlHand();

            PokerHandHistory.PokerHandXML hands = new PokerHandHistory.PokerHandXML(){
                Hands = new PokerHandHistory.PokerHand[] { xml }
            };

            StringBuilder sb = new StringBuilder();
            using(TextWriter writer = new StringWriter(sb))
            {
                XmlSerializer ser = new XmlSerializer(typeof(PokerHandHistory.PokerHandXML));
                ser.Serialize(writer, hands);
            }

            Console.WriteLine(sb.ToString());
            if (actions != null && curAction < actions.Length)
            {
                holdem_engine.Action action = actions[curAction++];
                type = action.ActionType;
                amount = action.Amount;
            }
            else
            {
                type = holdem_engine.Action.ActionTypes.Fold;
                amount = 0;
            }
        }
コード例 #20
0
    public HandHistory ParseHand(List <string> rawHand)
    {
        List <string> lines = rawHand;

        HandHistory hh = new HandHistory(rawHand);

        // Get hand history, game type and game stakes
        hh.HandNumber = GetHandNumber(lines[0]);
        hh.GameType   = GetGameType(lines[0]);
        hh.Stakes     = GetGameStakes(lines[0]);

        hh.FlopTurnRiverCards = GetFlopTurnRiverCards(lines);

        hh.PlayerHandHistories = GetPlayerHandHistories(rawHand);
        hh.Rake     = GetRake(rawHand);
        hh.TotalPot = GetTotalPot(rawHand);

        IntegrityChecks(hh);

        //Actions = GetActions(lines);
        // Get Hero starting amount
        //HeroStartMoney = GetHeroStartMoney(lines);
        //HeroEndMoney = GetHeroEndMoney(lines);

        // = new Hand(GetHeroHand(lines));

        // Position = GetHeroPosition(lines);

        return(hh);
    }
コード例 #21
0
        public bool CheckHand(HandHistory handHistory)
        {
            var registeredLicenses = licenseService.LicenseInfos.Where(x => x.IsRegistered).ToArray();

            // if any license is not trial
            if (registeredLicenses.Any(x => !x.IsTrial))
            {
                registeredLicenses = registeredLicenses.Where(x => !x.IsTrial).ToArray();
            }

            if (registeredLicenses.Length == 0)
            {
                return(false);
            }

            if (handHistory.GameDescription.IsTournament)
            {
                var tournamentLimit = registeredLicenses.Max(x => x.TournamentLimit);
                return(handHistory.GameDescription.Tournament.BuyIn.PrizePoolValue <= tournamentLimit);
            }

            var cashLimit = registeredLicenses.Max(x => x.CashLimit);

            var limit = handHistory.GameDescription.Limit.BigBlind;

            if (handHistory.GameDescription.IsStraddle)
            {
                limit *= 2;
            }

            return(limit <= cashLimit);
        }
コード例 #22
0
        public void Evaluate(List <IPlayer> players, Settings settings, bool champions, int games)
        {
            ResetScores(players);

            var seats = CreateSeats(players, settings.BigBlind * settings.StackSize);

            HandEngine engine = new HandEngine()
            {
                AnalyzeHands = true
            };

            for (int i = 0, handsThisTourney = 0;
                 seats.Count > 3 && handsThisTourney < settings.MaxHandsPerTourney;
                 i = (i + 1) % seats.Count, handsThisTourney++)
            {
                ulong handNumber;
                handNumber = GamesPlayed++;

                HandHistory history = new HandHistory(seats.ToArray(), GamesPlayed, (uint)seats[i].SeatNumber,
                                                      new double[] { settings.SmallBlind, settings.BigBlind },
                                                      0, BettingStructure.Limit);
                engine.PlayHand(history);

                if (champions)
                {
                    LogHand(settings, history, handNumber > 1);
                }

                RemoveBrokePlayers(settings, seats);
            }

            ScorePlayers(seats);
        }
コード例 #23
0
        public static void Main()
        {
            ParserExample parser = new ParserExample();

            try
            {
                int parsedHands    = 0;
                int thrownOutHands = 0;
                // Open the text file using a stream reader.
                //using (StreamReader sr = new StreamReader("C:\\Users\\rcotter\\Downloads\\PS-2009-07-01_2009-07-23_1000NLH_OBFU\\10\\ps NLH handhq_1-OBFUSCATED.txt"))
                {
                    SiteName site       = SiteName.PokerStars;
                    string   folderPath = " C:\\Users\\rcotter\\Downloads\\PS-2009-07-01_2009-07-23_1000NLH_OBFU\\10\\";
                    foreach (string file in Directory.EnumerateFiles(folderPath, "*.txt"))
                    {
                        string contents = File.ReadAllText(file);

                        HandHistory hand = parser.ParseHand(site, contents, ref parsedHands, ref thrownOutHands);
                    }
                    // Read the stream to a string, and write the string to the console.
                    //String line = sr.ReadToEnd();
                    Console.WriteLine("Number of parsed hands:" + parsedHands);
                    Console.WriteLine("Number of thrown hands:" + thrownOutHands);
                    Console.Read();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
            }
        }
コード例 #24
0
        public void TryBuildTest(string testFolder)
        {
            var packages = ReadPackages(testFolder);

            CollectionAssert.IsNotEmpty(packages, $"Packages collection must be not empty for {testFolder}");

            var handBuilder = new PPPHandBuilder();

            HandHistory actual = null;

            if (testFolder == NlheSngTest)
            {
                using (ShimsContext.Create())
                {
                    ShimDateTime.UtcNowGet = () => new DateTime(2018, 10, 11, 17, 07, 14);

                    Build(handBuilder, packages, out actual);
                }
            }
            else
            {
                Build(handBuilder, packages, out actual);
            }


            Assert.IsNotNull(actual, $"Actual HandHistory must be not null for {testFolder}");

            var expected = ReadExpectedHandHistory(testFolder);

            Assert.IsNotNull(expected, $"Expected HandHistory must be not null for {testFolder}");

            AssertionUtils.AssertHandHistory(actual, expected);
        }
コード例 #25
0
        public override double[] GetInputs(HandHistory history)
        {
            double[] inputs = new double[INPUT_NODE_COUNT];

            int index = 0;

            index = Util.AddPlayersAsSingleNode(history, inputs, index); //1 node
            index = Util.AddRoundAsSingleNode(history, inputs, index);   //1 node
            //index = Util.AddCardsAsSingleNodes(history, inputs, index);//14 nodes
            //index = Util.AddBetsAsSingleNodes(history, 6, inputs, index);//16 nodes
            index = Util.AddBetsDecisionInfoAndPositionAsSingleNodes(history, inputs, index); //5 nodes
            index = Util.AddProbabilitiesAsSingleNodes(history, inputs, index);               //4 nodes
            //index = Util.AddAnalysisAsSingleNodes(history, inputs, index);//10 nodes

            //lock (DebugLock)
            //{
            //    debugPrint(history, inputs);
            //    Console.ReadKey(false);
            //}
            if (index != INPUT_NODE_COUNT)
            {
                throw new Exception("Wrong: " + index);
            }

            return(inputs);
        }
コード例 #26
0
        private void ProcessSeatInfo(RoomSeatInfo seatInfo, HandHistory handHistory)
        {
            if (handHistory.Players.Count > 0)
            {
                return;
            }

            if (seatInfo.SeatInfo == null || seatInfo.SeatInfo.Seats == null)
            {
                throw new HandBuilderException("RoomSeatInfo.SeatInfo must be not null");
            }

            foreach (var seat in seatInfo.SeatInfo.Seats)
            {
                if (seat.PlayerId <= 0)
                {
                    continue;
                }

                var player = new Player
                {
                    PlayerName    = seat.PlayerId.ToString(),
                    PlayerNick    = seat.PlayerName,
                    SeatNumber    = seat.SeatId,
                    StartingStack = seat.Chips
                };

                handHistory.Players.Add(player);
            }
        }
コード例 #27
0
ファイル: HandBuilder.cs プロジェクト: Michael-Z/DriveHud
        private Player AddOrUpdatePlayer(UserGameInfoNet userGameInfo, int seat, HandHistory handHistory, long heroId)
        {
            var player = handHistory.Players[userGameInfo.UserInfo.ShowID];

            if (player == null)
            {
                player = new Player(userGameInfo.UserInfo.ShowID, 0, seat)
                {
                    PlayerNick = userGameInfo.UserInfo.Nick
                };

                handHistory.Players.Add(player);

                if (heroId == userGameInfo.UserInfo.Uuid)
                {
                    handHistory.Hero = player;
                }
            }

            if (userGameInfo.CurrentHands == null || player.hasHoleCards)
            {
                return(player);
            }

            handHistory.Players[userGameInfo.UserInfo.ShowID].HoleCards = HoleCards.FromCards(userGameInfo.UserInfo.ShowID,
                                                                                              userGameInfo.CurrentHands.Select(c => Card.GetPMCardFromIntValue(c)).ToArray());

            return(player);
        }
コード例 #28
0
 public void SetUp()
 {
     _handHistory = new HandHistory()
     {
         ComumnityCards =
             BoardCards.ForFlop(Card.GetCardFromIntValue(5), Card.GetCardFromIntValue(14),
                                Card.GetCardFromIntValue(40)),
         DateOfHandUtc        = new DateTime(2012, 3, 20, 12, 30, 44),
         DealerButtonPosition = 5,
         FullHandHistoryText  = "some hand text",
         GameDescription      =
             new GameDescriptor(PokerFormat.CashGame,
                                SiteName.PartyPoker,
                                GameType.NoLimitHoldem,
                                Limit.FromSmallBlindBigBlind(10, 20, Currency.USD),
                                TableType.FromTableTypeDescriptions(TableTypeDescription.Regular),
                                SeatType.FromMaxPlayers(6)),
         HandActions = new List <HandAction>()
         {
             new HandAction("Player1", HandActionType.POSTS, 0.25m, Street.Preflop)
         },
         HandId           = 141234124,
         NumPlayersSeated = 2,
         Players          = new PlayerList()
         {
             new Player("Player1", 1000, 1),
             new Player("Player2", 300, 5),
         },
         TableName = "Test Table",
     };
 }
コード例 #29
0
ファイル: Adda52Importer.cs プロジェクト: Michael-Z/DriveHud
        protected override PlayerList GetPlayerList(HandHistory handHistory, GameInfo gameInfo)
        {
            var playerList = handHistory.Players;

            var maxPlayers = handHistory.GameDescription.SeatType.MaxPlayers;

            var heroSeat = handHistory.Hero != null ? handHistory.Hero.SeatNumber : 0;

            if (heroSeat != 0)
            {
                var preferredSeats = ServiceLocator.Current.GetInstance <ISettingsService>().GetSettings().
                                     SiteSettings.SitesModelList.FirstOrDefault(x => x.PokerSite == Site)?.PrefferedSeats;

                var prefferedSeat = preferredSeats?.FirstOrDefault(x => (int)x.TableType == maxPlayers && x.IsPreferredSeatEnabled);

                if (prefferedSeat != null && prefferedSeat.PreferredSeat > 0)
                {
                    var shift = (prefferedSeat.PreferredSeat - heroSeat) % maxPlayers;

                    foreach (var player in playerList)
                    {
                        player.SeatNumber = GeneralHelpers.ShiftPlayerSeat(player.SeatNumber, shift, maxPlayers);
                    }
                }
            }

            return(playerList);
        }
コード例 #30
0
        public void HandIdIsParsedTest(string handHistoryFile, long[] handsId)
        {
            var parser = new Poker888FastParserImpl();

            string rawHands = File.ReadAllText(handHistoryFile);
            var    hands    = parser.SplitUpMultipleHands(rawHands).ToArray();

            if (handsId.Length != hands.Count())
            {
                throw new InvalidDataException(hands.Count() > handsId.Length
                    ? "Too many hands."
                    : "Too many ids.");
            }

            var succeded = 0;
            var total    = hands.Count();

            for (int i = 0; i < total; i++)
            {
                HandHistory hand = parser.ParseFullHandHistory(hands[i], true);

                if (hand.HandId == handsId[i])
                {
                    succeded++;
                }
            }

            Assert.AreEqual(total, succeded);

            Debug.WriteLine("Processed hands: {0}/{1}", succeded, total);
        }
コード例 #31
0
        void TestRakeCalculator(decimal ExpectedRake, HandHistory hand)
        {
            hand.TotalPot = PotCalculator.CalculateTotalPot(hand);
            var calculatedRake = PotCalculator.CalculateRake(hand);

            Assert.AreEqual(ExpectedRake, calculatedRake);
        }
コード例 #32
0
        public void TryBuildTest(string testFolder, uint heroId)
        {
            var packages = ReadPackages(testFolder);

            CollectionAssert.IsNotEmpty(packages, $"Packages collection must be not empty for {testFolder}");

            var handBuilder = new PKHandBuilder();

            HandHistory actual = null;

            foreach (var package in packages)
            {
                package.UserId = heroId;

                if (handBuilder.TryBuild(package, identifier, out actual))
                {
                    break;
                }
            }

            Assert.IsNotNull(actual, $"Actual HandHistory must be not null for {testFolder}");

            var expected = ReadExpectedHandHistory(testFolder);

            Assert.IsNotNull(expected, $"Expected HandHistory must be not null for {testFolder}");

            AssertionUtils.AssertHandHistory(actual, expected);
        }
コード例 #33
0
        public void Evaluate(List<IPlayer> players, Settings settings, bool champions, int games)
        {
            ResetScores(players);

            var seats = CreateSeats(players, settings.BigBlind * settings.StackSize);

            HandEngine engine = new HandEngine() { AnalyzeHands = true };

            for (int i = 0, handsThisTourney = 0;
                seats.Count > 3 && handsThisTourney < settings.MaxHandsPerTourney;
                i = (i + 1) % seats.Count, handsThisTourney++)
            {
                ulong handNumber;
                handNumber = GamesPlayed++;

                HandHistory history = new HandHistory(seats.ToArray(), GamesPlayed, (uint)seats[i].SeatNumber,
                                                        new double[] { settings.SmallBlind, settings.BigBlind },
                                                        0, BettingStructure.Limit);
                engine.PlayHand(history);

                if (champions)
                    LogHand(settings, history, handNumber > 1);

                RemoveBrokePlayers(settings, seats);
            }

            ScorePlayers(seats);
        }
コード例 #34
0
        public void TryBuildTest(string testFolder)
        {
            var packages = ReadPackages(testFolder);

            CollectionAssert.IsNotEmpty(packages, $"Packages collection must be not empty for {testFolder}");

            var handBuilder = new PokerBaaziHandBuilder();

            HandHistory actual = null;

            foreach (var package in packages.Where(x => x.PackageType != PokerBaaziPackageType.Unknown))
            {
                if (handBuilder.TryBuild(package, out actual, out PokerBaaziHandBuilderError error))
                {
                    break;
                }
            }

            Assert.IsNotNull(actual, $"Actual HandHistory must be not null for {testFolder}");

            var expected = ReadExpectedHandHistory(testFolder);

            Assert.IsNotNull(expected, $"Expected HandHistory must be not null for {testFolder}");

            AssertionUtils.AssertHandHistory(actual, expected);
        }
コード例 #35
0
        private IntPtr FindTournamentTableHandle(HandHistory handHistory)
        {
            var handle = handHistory.GameDescription.Tournament.TournamentsTags == TournamentsTags.STT ?
                         FindSttTableHandle(handHistory) : FindMttTableHandle(handHistory);

            return(handle);
        }
コード例 #36
0
ファイル: WekaPlayer.cs プロジェクト: tansey/console_holdem
        public void GetAction(HandHistory history, out holdem_engine.Action.ActionTypes action, out double amount)
        {
            //			Console.WriteLine(history.ToString());
            //			Console.WriteLine();
            //			Console.WriteLine();

            var xml = history.ToXmlHand();
            int rIdx = (int)history.CurrentRound - 1;
            int aIdx = xml.Rounds[rIdx].Actions.Length;

            //			Console.WriteLine("rIdx: {0} aIdx: {1}", rIdx, aIdx);
            //			StringBuilder sb = new StringBuilder();
            //			using(TextWriter writer = new StringWriter(sb))
            //			{
            //				XmlSerializer ser = new XmlSerializer(typeof(PokerHandHistory.PokerHand));
            //				ser.Serialize(writer, xml);
            //			}
            //			Console.WriteLine(sb.ToString());

            var features = _featureGen.GenerateFeatures(xml, rIdx, aIdx, _instances[rIdx], false);

            var classifier = _models[rIdx];

            int result;
            // Mixed policies take a randomized action based on a probability distribution.
            if(MixedPolicy)
            {
                double[] dist = classifier.distributionForInstance(features);
                double prev = 0;
                double sample = _rand.NextDouble();
                result = -1;
                for(int i = 0; i < dist.Length; i++)
                {
                    double val = prev + dist[i];
                    if(val < sample)
                    {
                        result = i;
                        break;
                    }
                }

            }
            else
            {
                // Otherwise, the policy is a pure strategy taking deterministic actions.
                result = (int)classifier.classifyInstance(features);
            }
            if(result == 0)
                action = holdem_engine.Action.ActionTypes.Fold;
            else if(result == 1)
                action = holdem_engine.Action.ActionTypes.Call;
            else if (result == 2)
                action = holdem_engine.Action.ActionTypes.Raise;
            else
                throw new Exception("Unknown class: " + result);
            amount = 0;
        }
コード例 #37
0
 private void LogHand(Settings settings, HandHistory history, bool append)
 {
     lock(LogLock)
         using (TextWriter writer = new StreamWriter(settings.LogFile + Generation + ".txt", append))
         {
             writer.WriteLine(history.ToString());
             writer.WriteLine();
         }
 }
コード例 #38
0
 public void GetAction(HandHistory history, out FastPokerEngine.Action.ActionTypes action, out double amount)
 {
     double[] inputs = GetInputs(history);
     if (ThreadSafe)
     {
         lock (Network)
             RunNetwork(inputs, out action, out amount);
     }
     else
         RunNetwork(inputs, out action, out amount);
 }
コード例 #39
0
        private void debugPrint(HandHistory history, double[] inputs)
        {
            Console.WriteLine();
            Console.WriteLine(history.ToString());
            Console.WriteLine();
            Console.WriteLine("HoleCards: {0}",
                                HoldemHand.Hand.MaskToString(history.HoleCards[history.Hero]));
            Console.WriteLine("INPUTS:");
            for (var i = 0; i < inputs.Length; i++)
                Console.WriteLine("{0}: {1}", i, inputs[i]);

            Console.WriteLine();
        }
コード例 #40
0
        public void Evaluate(List<IPlayer> players, Settings settings, bool champions, int games)
        {
            ResetScores(players);
            int[] handsPlayed = new int[players.Count];
            List<int> availablePlayers = new List<int>();
            for (int i = 0; i < players.Count; i++)
                availablePlayers.Add(i);

            double startingChips = settings.BigBlind * settings.StackSize;

            HandEngine engine = new HandEngine() { AnalyzeHands = false };

            int handsThisGeneration = 0;
            while(availablePlayers.Count >= settings.PlayersPerGame)
            {
                ulong handNumber = GamesPlayed++;

                List<int> playerIndices = champions ?
                                            CreateShuffledChampionsList(settings) :
                                            availablePlayers.RandomSubset(settings.PlayersPerGame, random);
                var seats = CreateSeats(players, startingChips, playerIndices);

                HandHistory history = new HandHistory(seats, GamesPlayed, (uint)settings.PlayersPerGame,
                                                        new double[] { settings.SmallBlind, settings.BigBlind },
                                                        0, BettingStructure.Limit);
                engine.PlayHand(history);
                handsThisGeneration++;

                if (champions)
                    LogHand(settings, history, handNumber > 1);

                if (handNumber % 100000 == 0)
                    lock(LogLock)
                        Console.WriteLine("Hand: {0}", handNumber);

                AddScores(startingChips, playerIndices, seats);
                IncrementHandsPlayedAndRemoveDone(games, handsPlayed, availablePlayers, playerIndices, champions);
            }

            //normalize win rates
            for (int i = 0; i < Scores.Count; i++)
            {
                Scores[i] /= (double)handsPlayed[i];
                Scores[i] /= settings.BigBlind;
                if (Scores[i] > 2)
                    Scores[i] = 2;
                else if (Scores[i] < -5)
                    Scores[i] = -5;
            }
        }
コード例 #41
0
ファイル: SequencePlayer.cs プロジェクト: tansey/poker
 public void GetAction(HandHistory history,
                         out FastPokerEngine.Action.ActionTypes type, out double amount)
 {
     if (actions != null && curAction < actions.Length)
     {
         FastPokerEngine.Action action = actions[curAction++];
         type = action.ActionType;
         amount = action.Amount;
     }
     else
     {
         type = FastPokerEngine.Action.ActionTypes.Fold;
         amount = 0;
     }
 }
コード例 #42
0
        public override double[] GetInputs(HandHistory history)
        {
            double[] inputs = new double[INPUT_NODE_COUNT];

            int index = 0;
            index = Util.AddPlayersAsSeparateNodes(history, inputs, index);//6 nodes
            index = Util.AddRoundAsSingleNode(history, inputs, index);//1 node
            index = Util.AddBetsDecisionInfoAsSingleNodes(history, inputs, index);//3 nodes
            index = Util.AddPreviousRoundBetInfo(history, inputs, index);//2 nodes
            index = Util.AddCurrentAndPreviousProbabilities(history, inputs, index);//5 nodes

            //lock (DebugLock)
            //{
            //    debugPrint(history, inputs);
            //    Console.ReadKey(false);
            //}
            if (index != INPUT_NODE_COUNT)
                throw new Exception("Wrong: " + index);

            return inputs;
        }
コード例 #43
0
ファイル: Program.cs プロジェクト: tansey/poker
        static void Main(string[] args)
        {
            HandEngine engine = new HandEngine();

            Console.WriteLine("Loading cached hands");
            List<CachedHand> cachedHands;
            XmlSerializer ser = new XmlSerializer(typeof(CachedHands));
            using (TextReader txt = new StreamReader("test.xml"))
                cachedHands = ((CachedHands)ser.Deserialize(txt)).Hands;

            var seats = new Seat[6];
            seats[0] = new Seat(1, "AlwaysRaise", 100000, new AlwaysRaisePlayer());
            seats[1] = new Seat(2, "AwaysCall", 100000, new AlwaysCallPlayer());
            seats[2] = new Seat(3, "AwaysCall2", 100000, new AlwaysCallPlayer());
            seats[3] = new Seat(4, "AwaysCall3", 100000, new AlwaysCallPlayer());
            seats[4] = new Seat(5, "AwaysCall4", 100000, new AlwaysCallPlayer());
            seats[5] = new Seat(6, "AwaysCall5", 100000, new AlwaysCallPlayer());
            var blinds = new double[] { 1, 2 };
            uint handNumber = 0;
            double maxDifference = 0;
            Console.WriteLine("Starting simulation");
            DateTime start = DateTime.Now;
            for (; handNumber < 100; handNumber++)
            {
                HandHistory results = new HandHistory(seats, handNumber, handNumber % (uint)seats.Length + 1, blinds, 0, BettingStructure.NoLimit);
                engine.PlayHand(results, cachedHands[(int)handNumber]);
                double difference = Math.Abs(seats[0].Chips - seats[1].Chips);
                if (difference > maxDifference)
                    maxDifference = difference;
                if (seats[0].Chips == 0 || seats[1].Chips == 0)
                    break;
            }
            int time = DateTime.Now.Subtract(start).Milliseconds;
            Console.WriteLine("Time: {0}", time);
            Console.WriteLine("Hands: {0}", handNumber);
            Console.WriteLine("AlwaysRaise Bankroll: {0}", seats[0].Chips);
            Console.WriteLine("AlwaysCall Bankroll: {0}", seats[1].Chips);
            Console.WriteLine("Max Difference: {0}", maxDifference);
        }
コード例 #44
0
        public override double[] GetInputs(HandHistory history)
        {
            double[] inputs = new double[INPUT_NODE_COUNT];

            int index = 0;
            index = Util.AddPlayersAsSingleNode(history, inputs, index);//1 node
            index = Util.AddRoundAsSingleNode(history, inputs, index);//1 node
            //index = Util.AddCardsAsSingleNodes(history, inputs, index);//14 nodes
            //index = Util.AddBetsAsSingleNodes(history, 6, inputs, index);//16 nodes
            index = Util.AddBetsDecisionInfoAndPositionAsSingleNodes(history, inputs, index);//5 nodes
            index = Util.AddProbabilitiesAsSingleNodes(history, inputs, index);//4 nodes
            //index = Util.AddAnalysisAsSingleNodes(history, inputs, index);//10 nodes

            //lock (DebugLock)
            //{
            //    debugPrint(history, inputs);
            //    Console.ReadKey(false);
            //}
            if (index != INPUT_NODE_COUNT)
                throw new Exception("Wrong: " + index);

            return inputs;
        }
コード例 #45
0
ファイル: Util.cs プロジェクト: tansey/poker
 public static int AddRoundAsSeparateNodes(HandHistory history, double[] inputs, int index)
 {
     switch (history.CurrentRound)
     {
         case Round.Preflop:
             inputs[index] = 1;
             break;
         case Round.Flop:
             inputs[index + 1] = 1;
             break;
         case Round.Turn:
             inputs[index + 2] = 1;
             break;
         case Round.River:
             inputs[index + 3] = 1;
             break;
         default:
             break;
     }
     return index + 4;
 }
コード例 #46
0
ファイル: AlwaysRaisePlayer.cs プロジェクト: tansey/poker
 public void GetAction(HandHistory history, out FastPokerEngine.Action.ActionTypes action, out double amount)
 {
     action = FastPokerEngine.Action.ActionTypes.Raise;
     amount = 0;
 }
コード例 #47
0
ファイル: Util.cs プロジェクト: tansey/poker
        public static int AddCardsAsSeparateNodes(HandHistory history, double[] inputs, int index)
        {
            //13 different ranks
            //4 different suits
            //2 hole cards and 5 board cards = 7 total cards
            int endIndex = 13* 7 + 4 * 7 + index;
            addCards(history.HoleCards[history.Hero], inputs, ref index);

            if (history.CurrentRound >= Round.Flop)
                addCards(history.Flop, inputs, ref index);
            if (history.CurrentRound >= Round.Turn)
                addCards(history.Turn, inputs, ref index);
            if (history.CurrentRound >= Round.River)
                addCards(history.River, inputs, ref index);

            return endIndex;
        }
コード例 #48
0
ファイル: Util.cs プロジェクト: tansey/poker
        public static int AddPlayersAsSeparateNodes(HandHistory history, double[] inputs, int index)
        {
            for (int i = 0; i < history.Players.Length; i++)
                if (i == history.Hero)
                    inputs[index + i] = 1;
                else if (!history.Folded[i])
                    inputs[index + i] = -1;

            return index + history.Players.Length;
        }
コード例 #49
0
ファイル: Util.cs プロジェクト: tansey/poker
        public static int AddCardsAsSingleNodes(HandHistory history, double[] inputs, int index)
        {
            //Each card has a rank and a suit
            //2 hole cards and 5 board cards = 7 total cards
            int endIndex = 2 * 7 + index;
            addCardsAsSingleNodes(history.HoleCards[history.Hero], inputs, ref index);

            if (history.CurrentRound >= Round.Flop)
                addCardsAsSingleNodes(history.Flop, inputs, ref index);
            if (history.CurrentRound >= Round.Turn)
                addCardsAsSingleNodes(history.Turn, inputs, ref index);
            if (history.CurrentRound >= Round.River)
                addCardsAsSingleNodes(history.River, inputs, ref index);

            return endIndex;
        }
コード例 #50
0
ファイル: Util.cs プロジェクト: tansey/poker
        public static int AddPreviousRoundBetInfo(HandHistory history, double[] inputs, int index)
        {
            int endIndex = index + 2;
            if (history.CurrentRound == Round.Preflop)
                return endIndex;

            string hero = history.Players[history.Hero].Name;
            List<PokerAction> actions = null;
            switch (history.CurrentRound)
            {
                case Round.Flop:
                    actions = new List<PokerAction>();
                    foreach (PokerAction action in history.PredealActions)
                        actions.Add(action);
                    foreach (PokerAction action in history.PreflopActions)
                        actions.Add(action);
                    break;
                case Round.Turn: actions = history.FlopActions; break;
                case Round.River: actions = history.TurnActions; break;
            }

            int aggressor = 0;
            int betLevel = 0;
            foreach(PokerAction action in actions)
                switch (action.ActionType)
                {
                    case FastPokerEngine.Action.ActionTypes.PostBigBlind: betLevel++; break;
                    case FastPokerEngine.Action.ActionTypes.Bet:
                    case FastPokerEngine.Action.ActionTypes.Raise:
                        betLevel++;
                        if (action.Name == hero)
                            aggressor = 1;
                        else
                            aggressor = -1;
                        break;
                    default:
                        break;
                }

            inputs[index] = betLevel / 4.0;
            inputs[index + 1] = aggressor;
            return endIndex;
        }
コード例 #51
0
ファイル: Util.cs プロジェクト: tansey/poker
 public static int AddPlayersAsSingleNode(HandHistory history, double[] inputs, int index)
 {
     inputs[index] = (double)history.Players.Length / 10.0;
     return index + 1;
 }
コード例 #52
0
ファイル: AlwaysRaisePlayer.cs プロジェクト: tansey/poker
 public void NewHand(HandHistory history)
 {
 }
コード例 #53
0
ファイル: Util.cs プロジェクト: tansey/poker
        public static int AddBetsAsSeparateNodes(HandHistory history, int maxPlayers, double[] inputs, int index)
        {
            Dictionary<string, SeatInfo> bets = new Dictionary<string, SeatInfo>();
            for (int i = ((int)history.Button + 1) % history.Players.Length, nodeIdx = 0;
                bets.Count < history.Players.Length;
                i = (i + 1) % history.Players.Length, nodeIdx++)
                bets.Add(history.Players[i].Name, new SeatInfo() { BetLevel = 0, Index = nodeIdx });

            //Each bet is one of 3 actions (fold/call/raise).
            //Each player can act up to 5 times per round.
            //There are 4 rounds of betting.
            //There are maxPlayers players
            int endIdx = 3 * 5 * 4 * maxPlayers + index;

            ulong hc = history.HoleCards[history.Hero];
            addBetsAsSeparateNodes(history.PreflopActions, inputs, bets,maxPlayers, ref index);

            if (history.CurrentRound >= Round.Flop)
                addBetsAsSeparateNodes(history.FlopActions, inputs, bets,maxPlayers, ref index);

            if (history.CurrentRound >= Round.Turn)
                addBetsAsSeparateNodes(history.TurnActions, inputs, bets,maxPlayers, ref index);

            if (history.CurrentRound >= Round.River)
                addBetsAsSeparateNodes(history.RiverActions, inputs, bets, maxPlayers, ref index);

            return endIdx;
        }
コード例 #54
0
        public void SetUp()
        {
            engine = new HandEngine();

            #region Setup the actions
            Action[] jcloub = new Action[]{
                new Action("jcloub", Action.ActionTypes.Raise, 15),
                new Action("jcloub", Action.ActionTypes.Bet, 10),
                new Action("jcloub", Action.ActionTypes.Bet, 20),
                new Action("jcloub", Action.ActionTypes.Bet, 20),
            };

            Action[] makelgrus = new Action[]{
                new Action("MakelGrus", Action.ActionTypes.Call, 10),
                new Action("MakelGrus", Action.ActionTypes.Call, 10),
                new Action("MakelGrus", Action.ActionTypes.Call, 20),
                new Action("MakelGrus", Action.ActionTypes.Fold),
            };

            Action[] hustler_ed = new Action[]{
                new Action("Hustler_Ed", Action.ActionTypes.Call, 10),
                new Action("Hustler_Ed", Action.ActionTypes.Call, 10),
                new Action("Hustler_Ed", Action.ActionTypes.Call, 10),
                new Action("Hustler_Ed", Action.ActionTypes.Call, 20),
                new Action("Hustler_Ed", Action.ActionTypes.Fold),
            };

            Action[] shammybaby = new Action[]{
                new Action("Shammybaby", Action.ActionTypes.Fold),
            };

            Action[] marine0193 = new Action[]{
                new Action("marine0193", Action.ActionTypes.Fold),
            };

            Action[] teejayortj5 = new Action[]{
                new Action("TeeJayorTJ5", Action.ActionTypes.Fold),
            };
            #endregion

            #region Setup players
            SequencePlayer[] brains = new SequencePlayer[]{
                new SequencePlayer(jcloub),
                new SequencePlayer(makelgrus),
                new SequencePlayer(hustler_ed),
                new SequencePlayer(shammybaby),
                new SequencePlayer(marine0193),
                new SequencePlayer(teejayortj5)
            };

            var seqPlayers = new Seat[]{
                new Seat(1, "jcloub", 2044.5, brains[0]),
                new Seat(3, "MakelGrus", 498, brains[1]),
                new Seat(5, "Hustler_Ed", 470, brains[2]),
                new Seat(6, "Shammybaby", 551, brains[3]),
                new Seat(8, "marine0193", 538, brains[4]),
                new Seat(10, "TeeJayorTJ5", 484, brains[5])
            };
            #endregion

            var blinds = new double[] { 5, 10 };

            engine = new HandEngine();
            hist = new HandHistory(seqPlayers, 1, 10, blinds, 0, BettingStructure.Limit);
            engine.PlayHand(hist);
        }
コード例 #55
0
ファイル: Util.cs プロジェクト: tansey/poker
 public static int AddRoundAsSingleNode(HandHistory history, double[] inputs, int index)
 {
     switch (history.CurrentRound)
     {
         case Round.Preflop:
             inputs[index] = 0.25;
             break;
         case Round.Flop:
             inputs[index] = 0.5;
             break;
         case Round.Turn:
             inputs[index] = 0.75;
             break;
         case Round.River:
             inputs[index] = 1;
             break;
         default:
             break;
     }
     return index + 1;
 }
コード例 #56
0
ファイル: HandEngine.cs プロジェクト: tansey/holdem_engine
        /// <summary>
        /// Plays a hand from the start. Note that this method will <b>not</b> resume a game from a saved hand _history.
        /// </summary>
        /// <param name="handHistory">An new hand _history with the list of players and the game parameters.</param>
        public void PlayHand(HandHistory handHistory)
        {
            #region Hand Setup
            _seats = handHistory.Players;
            handHistory.HoleCards = new ulong[_seats.Length];
            handHistory.DealtCards = 0UL;
            handHistory.Flop = 0UL;
            handHistory.Turn = 0UL;
            handHistory.River = 0UL;

            //Setup the hand _history
            this._history = handHistory;

            //Create a new map from player names to player chips for the BetManager
            Dictionary<string, double> namesToChips = new Dictionary<string, double>();

            //Create a new list of players for the PlayerManager
            _playerIndices = new CircularList<int>();
            _playerIndices.Loop = true;

            for (int i = 0; i < _seats.Length; i++)
            {
                namesToChips[_seats[i].Name] = _seats[i].Chips;
                if (_seats[i].SeatNumber == _history.Button)
                {
                    _buttonIdx = i;
                    _utgIdx = (i + 1) % _seats.Length;
                }
            }
            for (int i = (_buttonIdx + 1) % _seats.Length; _playerIndices.Count < _seats.Length;)
            {
                _playerIndices.Add(i);
                i = (i + 1) % _seats.Length;
            }

            _betManager = new BetManager(namesToChips, _history.BettingStructure, _history.AllBlinds, _history.Ante);
            _potManager = new PotManager(_seats);
            #endregion

            if (_betManager.In > 1)
            {
                GetBlinds();
                DealHoleCards();
            }

            _history.CurrentRound = Round.Preflop;

            if (_betManager.CanStillBet > 1)
            {
                GetBets(_history.PreflopActions);
            }
            if (_betManager.In <= 1)
            {
                payWinners();
                return;
            }

            DealFlop();
            _history.CurrentRound = Round.Flop;

            if (_betManager.CanStillBet > 1)
            {
                GetBets(_history.FlopActions);
            }
            if (_betManager.In <= 1)
            {
                payWinners();
                return;
            }

            DealTurn();
            _history.CurrentRound = Round.Turn;

            if (_betManager.CanStillBet > 1)
            {
                GetBets(_history.TurnActions);
            }
            if (_betManager.In <= 1)
            {
                payWinners();
                return;
            }

            DealRiver();
            _history.CurrentRound = Round.River;

            if (_betManager.CanStillBet > 1)
            {
                GetBets(_history.RiverActions);
            }
            if (_betManager.In <= 1)
            {
                payWinners();
                return;
            }

            payWinners();
            _history.ShowDown = true;
            _history.CurrentRound = Round.Over;
        }
コード例 #57
0
ファイル: HandEngine.cs プロジェクト: tansey/holdem_engine
 /// <summary>
 /// Plays a hand from the start. Note that this method will <b>not</b> resume a game from a saved hand _history.
 /// </summary>
 /// <param name="handHistory">An new hand _history with the list of players and the game parameters.</param>
 /// <param name="cachedHand">The cached deck to use.</param>
 public void PlayHand(HandHistory handHistory, CachedHand cachedHand)
 {
     _cache = cachedHand;
     PlayHand(handHistory);
 }
コード例 #58
0
ファイル: Util.cs プロジェクト: tansey/poker
        public static int AddAnalysisAsSingleNodes(HandHistory history, double[] inputs, int index)
        {
            ulong hand = history.HoleCards[history.Hero];
            ulong board = history.Board;
            int endIndex = index + 10;

            inputs[index++] = KeithRuleHand.IsConnected(hand) ? 1 : 0;
            inputs[index++] = KeithRuleHand.IsSuited(hand) ? 1 : 0;

            if (history.CurrentRound > Round.Preflop)
            {
                switch (KeithRuleHand.EvaluateType(hand | board))
                {
                    case HoldemHand.Hand.HandTypes.StraightFlush: inputs[index++] = 8.0 / 8.0;
                        break;
                    case HoldemHand.Hand.HandTypes.FourOfAKind: inputs[index++] = 7.0 / 8.0;
                        break;
                    case HoldemHand.Hand.HandTypes.FullHouse: inputs[index++] = 6.0 / 8.0;
                        break;
                    case HoldemHand.Hand.HandTypes.Flush: inputs[index++] = 5.0 / 8.0;
                        break;
                    case HoldemHand.Hand.HandTypes.Straight: inputs[index++] = 4.0 / 8.0;
                        break;
                    case HoldemHand.Hand.HandTypes.Trips: inputs[index++] = 3.0 / 8.0;
                        break;
                    case HoldemHand.Hand.HandTypes.TwoPair: inputs[index++] = 2.0 / 8.0;
                        break;
                    case HoldemHand.Hand.HandTypes.Pair: inputs[index++] = 1.0 / 8.0;
                        break;
                    case HoldemHand.Hand.HandTypes.HighCard: inputs[index++] = 0.0 / 8.0;
                        break;
                    default:
                        break;
                };

                if (history.CurrentRound < Round.River)
                {
                    inputs[index++] = Math.Min(KeithRuleHand.StraightDrawCount(hand, board, 0UL) / 8.0, 1);
                    inputs[index++] = Math.Min(KeithRuleHand.Outs(hand, board) / 15.0, 1);
                    inputs[index++] = Math.Min(KeithRuleHand.OutsDiscounted(hand, board) / 15.0, 1);
                    inputs[index++] = KeithRuleHand.IsBackdoorFlushDraw(hand, board, 0UL) ? 1 : 0;
                    inputs[index++] = KeithRuleHand.IsFlushDraw(hand, board, 0UL) ? 1 : 0;
                    inputs[index++] = KeithRuleHand.IsGutShotStraightDraw(hand, board, 0UL) ? 1 : 0;
                    inputs[index++] = KeithRuleHand.IsOpenEndedStraightDraw(hand, board, 0UL) ? 1 : 0;
                }
            }
            else
            {
                //just check quickly if it's a pair
                IEnumerable<string> cards = KeithRuleHand.Cards(hand);
                inputs[index] = cards.ElementAt(0)[0] == cards.ElementAt(1)[0] ? 1.0 / 8.0 : 0;
            }

            return endIndex;
        }
コード例 #59
0
ファイル: Util.cs プロジェクト: tansey/poker
        public static int AddProbabilitiesAsSingleNodes(HandHistory history, double[] inputs, int index)
        {
            int endIndex = index + 4;

            int numOpponents = -1;
            foreach (bool folded in history.Folded)
                if (!folded)
                    numOpponents++;

            ulong hc = history.HoleCards[history.Hero];

            switch (history.CurrentRound)
            {
                case Round.Preflop:
                    //Console.WriteLine("Preflop: {0} {1}", numOpponents, (int)Hand.PocketHand169Type(hc));
                    double[] probs = PreflopTables[numOpponents - 1][(int)Hand.PocketHand169Type(hc)];
                    inputs[index] = probs[0];
                    inputs[index+1] = probs[1];
                    inputs[index+2] = probs[2];
                    inputs[index+3] = probs[3];
                    break;
                case Round.Flop:
                    //Console.WriteLine("Flop: {0}", numOpponents);
                    float ppot, npot, hs, wp;
                    FlopTables[numOpponents - 1].GetProbabilities(hc, history.Board,
                        out ppot, out npot, out hs, out wp);
                    inputs[index] = ppot;
                    inputs[index+1] = npot;
                    inputs[index+2] = wp;
                   inputs[index+3] = hs;
                    break;
                case Round.Turn:
                    //Console.WriteLine("Turn: {0}", numOpponents);
                    if (TurnTables.Length >= numOpponents)
                    {
                        TurnTables[numOpponents - 1].GetProbabilities(hc, history.Board,
                            out ppot, out npot, out hs, out wp);

                        inputs[index] = ppot;
                        inputs[index+1] = npot;
                        inputs[index+2] = wp;
                        inputs[index+3] = hs;
                    }
                    else
                    {
                        Hand.HandPotential(hc, history.Board, out inputs[index], out inputs[index+1], numOpponents, 0, 100);
                        inputs[index+2] = Hand.HandStrength(hc, history.Board, numOpponents, 0, 100);
                        inputs[index+3] = Hand.WinOdds(hc, history.Board, 0UL, numOpponents, 0, 100);
                    }

                    break;
                case Round.River:
                    //Console.WriteLine("River: {0}", numOpponents);
                    inputs[index] = 0;
                    inputs[index + 1] = 0;
                    inputs[index + 2] = Math.Pow(Hand.HandStrength(hc, history.Board), numOpponents);
                    inputs[index + 3] = inputs[index + 2];//on the river, hs and wp are equivalent
                    break;
                default: throw new Exception("Must be a bettable round.");
            }

            return endIndex;
        }
コード例 #60
0
ファイル: Util.cs プロジェクト: tansey/poker
        public static int AddBetsAsSingleNodes(HandHistory history,int maxPlayers, double[] inputs, int index)
        {
            //Each round has:
            //1) number of players in
            //2) bet level
            //3) relative position
            //4) flag if you are the aggressor
            //There are 4 rounds of betting
            int endIndex = 4 * 4 + index;
            ulong hc = history.HoleCards[history.Hero];
            string heroName = history.Players[history.Hero].Name;
            int playersIn = history.Players.Length;

            var temp = new List<PokerAction>();
            foreach (PokerAction action in history.PredealActions)
                temp.Add(action);
            foreach (PokerAction action in history.PreflopActions)
                temp.Add(action);
            addBetsAsSingleNodes(heroName, temp, maxPlayers, ref playersIn, inputs, ref index);

            if (history.CurrentRound >= Round.Flop)
                addBetsAsSingleNodes(heroName, history.FlopActions,maxPlayers, ref playersIn, inputs, ref index);

            if (history.CurrentRound >= Round.Turn)
                addBetsAsSingleNodes(heroName, history.TurnActions,maxPlayers, ref playersIn, inputs, ref index);

            if (history.CurrentRound >= Round.River)
                addBetsAsSingleNodes(heroName, history.RiverActions,maxPlayers, ref playersIn, inputs, ref index);

            return endIndex;
        }