Пример #1
0
        public McDealer(GameDefinition gd, Random underlyingRng)
        {
            List <DealKind> dealPattern = new List <DealKind>();

            for (int r = 0; r < gd.RoundsCount; ++r)
            {
                // Deal player's cards fist by our convention
                int playersCard = gd.PrivateCardsCount[r] + gd.PublicCardsCount[r];
                _playerCardCount += playersCard;
                for (int i = 0; i < playersCard; ++i)
                {
                    dealPattern.Add(DealKind.Player);
                }

                // Deal shared cards after private and public cards
                _sharedCardCount += gd.SharedCardsCount[r];
                for (int i = 0; i < gd.SharedCardsCount[r]; ++i)
                {
                    dealPattern.Add(DealKind.Shared);
                }
            }
            _dealPattern = dealPattern.ToArray();
            _dealer      = new SequenceRng(underlyingRng, gd.DeckDescr.FullDeckIndexes);
            Debug.Assert(_dealPattern.Length == _playerCardCount + _sharedCardCount);
        }
Пример #2
0
 public void DecimalRanges()
 {
     var zeroRng = new StepRng(0)
     {
         Increment = 0
     };                                                                                                  // Generates 0.0
     var     openZeroRng = new SequenceRng(new UInt32[] { 1, 0, 0 });                                    // Generates the lowest non-zero value
     var     openOneRng = new SequenceRng(new UInt32[] { 0x1000_0000, 0x3E25_0261, 0x204F_CE5Du << 2 }); // Generates the value just under 1.0
Пример #3
0
        public void Test_Random()
        {
            int REPETITIONS = 100;

#if DEBUG
            REPETITIONS = 8;
#endif

            int seed = (int)DateTime.Now.Ticks;
            Console.WriteLine("Random seed {0}", seed);
            Random rand = new Random(seed);
            _cardRng = new SequenceRng(seed);
            _cardRng.SetSequence(StdDeck.Descriptor.FullDeckIndexes);
            for (int r = 0; r < REPETITIONS; ++r)
            {
                _enumCount = r % 7;
                int sharedCount = rand.Next(0, StdDeck.Descriptor.Size + 1 - _enumCount);
                int deadCount   = rand.Next(0, StdDeck.Descriptor.Size + 1 - sharedCount - _enumCount);

                _cardRng.Shuffle(sharedCount + deadCount);
                int rc = 0;

                _shared = new CardSet();
                for (int i = 0; i < sharedCount; ++i)
                {
                    _shared |= StdDeck.Descriptor.CardSets[_cardRng.Sequence[rc++]];
                }

                _dead = new CardSet();
                for (int i = 0; i < deadCount; ++i)
                {
                    _dead |= StdDeck.Descriptor.CardSets[_cardRng.Sequence[rc++]];
                }
                Debug.Assert(rc == sharedCount + deadCount);
                Debug.Assert(!_shared.IsIntersectingWith(_dead));

                //Console.WriteLine("B: {0:x16} D:{1:x16}", board, dead);
                _combinationsCount = 0;
                _lastCs            = 0;
                CardEnum.Combin(StdDeck.Descriptor, _enumCount, _shared, _dead, VerifyCombination);
                Assert.AreEqual(EnumAlgos.CountCombin(StdDeck.Descriptor.Size - sharedCount - deadCount, _enumCount), _combinationsCount);

                _combinationsCount1 = 0;
                _lastCs1            = 0;
                CardEnum.Combin(StdDeck.Descriptor, _enumCount, _shared, _dead, VerifyCombinationParam, _combinationsCount);
                Assert.AreEqual(EnumAlgos.CountCombin(StdDeck.Descriptor.Size - sharedCount - deadCount, _enumCount), _combinationsCount1);

                _combinationsCount1 = 0;
                _lastCs1            = 0;
                int[] cards = new int[_enumCount + sharedCount].Fill(-1);
                StdDeck.Descriptor.GetIndexesAscending(_shared).ToArray().CopyTo(cards, 0);
                int[] deadIdx = StdDeck.Descriptor.GetIndexesAscending(_shared | _dead).ToArray();

                CardEnum.Combin(StdDeck.Descriptor, _enumCount, cards, sharedCount, deadIdx, deadIdx.Length, VerifyCombinationParam, _combinationsCount);
                Assert.AreEqual(EnumAlgos.CountCombin(StdDeck.Descriptor.Size - sharedCount - deadCount, _enumCount), _combinationsCount1);
            }
            Console.WriteLine("{0} repetitions done.", REPETITIONS);
        }
Пример #4
0
        public void Test_Showdown()
        {
            int seed = (int)DateTime.Now.Ticks;

            Console.WriteLine("RNG seed {0}", seed);
            SequenceRng dealer = new SequenceRng(seed, StdDeck.Descriptor.FullDeckIndexes);

            HoldemGameRules gr = new HoldemGameRules();

            int[][]  hands = new int[2][];
            UInt32[] ranks = new UInt32[2];
            for (int p = 0; p < 2; ++p)
            {
                hands[p] = new int[7];
            }

            int repCount = 1000000;

            for (int r = 0; r < repCount; ++r)
            {
                dealer.Shuffle(2 + 2 + 5);
                hands[0][0] = dealer.Sequence[0];
                hands[0][1] = dealer.Sequence[1];
                hands[1][0] = dealer.Sequence[2];
                hands[1][1] = dealer.Sequence[3];
                for (int i = 0; i < 5; ++i)
                {
                    hands[0][2 + i] = hands[1][2 + i] = dealer.Sequence[4 + i];
                }
                gr.Showdown(_gd, hands, ranks);
                int actResult = -1;
                if (ranks[0] > ranks[1])
                {
                    actResult = 1;
                }
                else if (ranks[0] == ranks[1])
                {
                    actResult = 0;
                }
                CardSet h0        = _gd.DeckDescr.GetCardSet(hands[0]);
                CardSet h1        = _gd.DeckDescr.GetCardSet(hands[1]);
                UInt32  v0        = CardSetEvaluator.Evaluate(ref h0);
                UInt32  v1        = CardSetEvaluator.Evaluate(ref h1);
                int     expResult = -1;
                if (v0 > v1)
                {
                    expResult = 1;
                }
                else if (v0 == v1)
                {
                    expResult = 0;
                }
                Assert.AreEqual(expResult, actResult);
            }
        }
        void TestSort(int arraySize, int [] partSizes, int inMemSortSize, int rngSeed, int shuffleSize, bool isVerbose)
        {
            string inputDir = Path.Combine(_outDir, "input");

            DirectoryExt.Delete(inputDir);
            Directory.CreateDirectory(inputDir);

            string tempDir = Path.Combine(_outDir, "temp");

            int[] array = new int[arraySize];
            for (int i = 0; i < array.Length; ++i)
            {
                array[i] = i;
            }

            SequenceRng rng = new SequenceRng(rngSeed);

            rng.SetSequenceNoCopy(array);
            rng.Shuffle(shuffleSize);

            TestElement element = new TestElement();

            int begin = 0;

            for (int p = 0; p < partSizes.Length; ++p)
            {
                string fileName = Path.Combine(inputDir, string.Format("{0}.dat", p));
                using (BinaryWriter writer = new BinaryWriter(new FileStream(fileName, FileMode.Create, FileAccess.Write)))
                {
                    for (int i = begin; i < begin + partSizes[p]; ++i)
                    {
                        element.Write(array[i], writer);
                    }
                    begin += partSizes[p];
                }
            }

            Assert.AreEqual(arraySize, begin, "Incorrect part sizes.");

            string resultFile = Path.Combine(_outDir, "result.dat");

            ExternalMergeSort <int> sorter = new ExternalMergeSort <int> {
                IsVerbose = isVerbose
            };

            sorter.Sort(inputDir, tempDir, inMemSortSize, element, resultFile);

            int[] result = ReadToArray(resultFile, element);

            for (int i = 0; i < arraySize; ++i)
            {
                Assert.AreEqual(i, result[i]);
            }
        }
Пример #6
0
        public DealRecord(GameRecord cfg, DeckDescriptor deckDescr, SequenceRng randomDealer)
        {
            _cfg          = cfg;
            _deckDescr    = deckDescr;
            _randomDealer = randomDealer;

            // Loop through actions and
            // - find the fixed cards
            // - count random cards
            // - count enumerated cards

            for (int a = 0; a < _cfg.Actions.Count; ++a)
            {
                PokerAction action = _cfg.Actions[a];
                if (!action.IsDealerAction())
                {
                    continue;
                }
                string[] cards = action.Cards.Split(_separator, StringSplitOptions.RemoveEmptyEntries);
                foreach (string card in cards)
                {
                    if (card == "?")
                    {
                        _randomCount++;
                    }
                    else if (card.Length > 0 && card.Substring(0, 1) == "#")
                    {
                        int idx = int.Parse(card.Substring(1));
                        while (_enumCounts.Count <= idx)
                        {
                            _enumCounts.Add(0);
                            _enumCombosCounts.Add(0);
                            _enumCombos.Add(new List <CardSet>());
                        }
                        _enumCounts[idx]++;
                    }
                    else
                    {
                        _fixedCards.UnionWith(_deckDescr.GetCardSet(card));
                    }
                }
            }

            // Count enumerated combinations.
            int deadCards = _fixedCards.CountCards();

            for (int i = 0; i < _enumCounts.Count; ++i)
            {
                _enumCombosCounts[i] = EnumAlgos.CountCombin(_deckDescr.Size - deadCards, _enumCounts[i]);
                deadCards           += _enumCounts[i];
            }
        }
Пример #7
0
        public void NonZeroBytes()
        {
            var rng  = new SequenceRng(new UInt32[] { 0, 1, 2, 0, 1, 2, 0, 1 });
            var shim = RandomNumberGeneratorShim.Create(rng);

            var buffer = new Byte[35];

            shim.GetNonZeroBytes(buffer);
            Assert.DoesNotContain((Byte)0, buffer);

#if !NET472
            shim.GetNonZeroBytes(buffer.AsSpan());
            Assert.DoesNotContain((Byte)0, buffer);
#endif
        }
Пример #8
0
        public void Test_Shuffle()
        {
            // Make sure that shuffling from some start does not overwrite the beginning of the sequence
            int []      sequence = new int[10].Fill(i => i);
            SequenceRng sr       = new SequenceRng();

            for (int start = 0; start <= sequence.Length; start++)
            {
                sr.SetSequence(sequence);
                sr.Shuffle(start, sequence.Length - start);
                for (int i = 0; i < start; ++i)
                {
                    Assert.AreEqual(i, sr.Sequence[i]);
                }
            }
        }
Пример #9
0
        public void Benchmark(Random underlyingRng)
        {
            int[] array = new int[100].Fill(i => i);

            SequenceRng rng = new SequenceRng(underlyingRng, array);

            int      repCount  = 500000;
            DateTime startTime = DateTime.Now;

            for (int i = 0; i < repCount; ++i)
            {
                rng.Shuffle();
            }
            TimeSpan time          = DateTime.Now - startTime;
            long     totalRepCount = array.Length * repCount;

            Console.Write("{0:#,#} Repetitions done in {1:0.0} s, {2:#,#} shuffles/s",
                          totalRepCount, time.TotalSeconds, totalRepCount / time.TotalSeconds);
        }
Пример #10
0
        void CalculateFastRandomTest(int round, int repCount)
        {
            int rngSeed = (int)DateTime.Now.Ticks;

            Console.WriteLine("CalculateFast random test round {0}, rep count {1}, RNG seed {2}", round, repCount, rngSeed);

            Random      rng        = new Random(rngSeed);
            SequenceRng dealer     = new SequenceRng(rngSeed, StdDeck.Descriptor.FullDeckIndexes);
            int         handLength = HeHelper.RoundToHandSize[round];

            for (int r = 0; r < repCount; ++r)
            {
                dealer.Shuffle(handLength);
                HsSd.SdKind sdKind   = round == 3 ? HsSd.SdKind.Sd3 : (HsSd.SdKind)rng.Next(0, 2);
                int         sdRound  = sdKind == HsSd.SdKind.SdPlus1 ? round + 1 : 3;
                float[]     hssdFast = HsSd.CalculateFast(dealer.Sequence, handLength, sdKind);
                float[]     hssd     = HsSd.Calculate(dealer.Sequence, handLength, sdRound);
                Assert.AreEqual(hssd[0], hssdFast[0], 1e-6);
                Assert.AreEqual(hssd[1], hssdFast[1], 1e-6);
            }
        }
Пример #11
0
        public void Test_SameSeed()
        {
            int[] sequence = (new int[256]).Fill(i => i);

            int         seed = 123;
            SequenceRng rng1;
            SequenceRng rng2;

            // Case 1
            rng1 = new SequenceRng(seed);
            rng2 = new SequenceRng(seed);
            rng1.SetSequence(sequence);
            rng2.SetSequence(sequence);
            rng1.Shuffle();
            rng2.Shuffle();
            Assert.AreEqual(rng1.Sequence, rng2.Sequence);

            // Case 2
            rng1 = new SequenceRng(seed, sequence);
            rng2 = new SequenceRng(seed, sequence);
            rng1.Shuffle();
            rng2.Shuffle();
            Assert.AreEqual(rng1.Sequence, rng2.Sequence);

            // Case 3
            rng1 = new SequenceRng(new Random(seed));
            rng2 = new SequenceRng(new Random(seed));
            rng1.SetSequence(sequence);
            rng2.SetSequence(sequence);
            rng1.Shuffle();
            rng2.Shuffle();
            Assert.AreEqual(rng1.Sequence, rng2.Sequence);

            // Case 4
            rng1 = new SequenceRng(new Random(seed), sequence);
            rng2 = new SequenceRng(new Random(seed), sequence);
            rng1.Shuffle();
            rng2.Shuffle();
            Assert.AreEqual(rng1.Sequence, rng2.Sequence);
        }
Пример #12
0
        McHand[] CreateMcHands(int round, Bucket parentBucket)
        {
            if (parentBucket.Length == 0)
            {
                if (IsVerbose)
                {
                    Console.WriteLine("Empty parent bucket");
                }
                return(new McHand[0]);
            }
            int samplesCount = (SamplesCount[round] / parentBucket.Length + 1) * parentBucket.Length;

            McHand[] hands        = new McHand[samplesCount];
            int      shuffleCount = HeHelper.RoundToHandSize[round] - HeHelper.RoundToHandSize[round - 1];
            int      s            = 0;

            if (IsVerbose)
            {
                Console.WriteLine("Creating random hands: parent hands: {0}, samples: {1}, deal: {2}",
                                  parentBucket.Length, samplesCount, shuffleCount);
            }
            for (int h = 0; h < parentBucket.Length; ++h)
            {
                for (int rep = 0; rep < samplesCount / parentBucket.Length; ++rep)
                {
                    McHand hand = new McHand(parentBucket.Hands[h]);
                    SequenceRng.Shuffle(_rng, hand.Cards, hand.Length, shuffleCount);
                    hand.Length += shuffleCount;
                    hands[s++]   = hand;
                    if (IsVerboseSamples)
                    {
                        Console.WriteLine(StdDeck.Descriptor.GetCardNames(hand.Cards, 0, hand.Length));
                    }
                }
            }
            Debug.Assert(s == samplesCount);
            _totalMcSamples += samplesCount;
            return(hands);
        }
Пример #13
0
        private void RandomTest(int rngSeed, int repCount, int handSizeBegin, int handSizeEnd)
        {
            Random rng = new Random(rngSeed);

            SequenceRng dealer    = new SequenceRng(rngSeed, StdDeck.Descriptor.FullDeckIndexes);
            DateTime    startTime = DateTime.Now;

            for (int r = 0; r < repCount; ++r)
            {
                // Number of cards for the pocket (2) and the board (3-5)
                // Skip preflop because it is very slow.
                int cardsCnt = rng.Next(handSizeBegin, handSizeEnd);
                dealer.Shuffle(cardsCnt);
                int[] hand = dealer.Sequence.Slice(0, cardsCnt);
                float s    = VerifyCalculateFast(hand);
                //Console.WriteLine("Hand {0} has strengths {1}", _deck.GetCardNames(hand), s);
            }
            TimeSpan time = DateTime.Now - startTime;

            Console.WriteLine("{0} Repetitions done in {1:0.0} s, {2:0.0} tests/s",
                              repCount, time.TotalSeconds, repCount / time.TotalSeconds);
        }
Пример #14
0
        void CreateFileForDiehard(Random rng, int approxFileSize)
        {
            int [] sequence = (new int[256]).Fill(i => i);

            string fileName = Path.Combine(_outDir, rng.ToString() + ".dat");

            SequenceRng seqRng = new SequenceRng(rng, sequence);

            int repCount = approxFileSize / sequence.Length + 1;

            using (BinaryWriter wr = new BinaryWriter(File.Open(fileName, FileMode.Create, FileAccess.Write)))
            {
                for (int r = 0; r < repCount; ++r)
                {
                    seqRng.Shuffle();
                    for (int i = 0; i < seqRng.Sequence.Length; ++i)
                    {
                        byte b = (byte)seqRng.Sequence[i];
                        wr.Write(b);
                    }
                }
            }
        }
Пример #15
0
        static public void InitHe(Algo algo, int bucketsCount, bool shuffle)
        {
            algo.Buckets = new Bucket[bucketsCount].Fill(i => new Bucket());

            SequenceRng shuffler = new SequenceRng();

            shuffler.SetSequence(169);
            if (shuffle)
            {
                shuffler.Shuffle();
            }

            double handsInBucket = HePocket.Count / bucketsCount;

            for (int p = 0; p < HePocket.Count; ++p)
            {
                int b = (int)(p / handsInBucket);
                if (b >= bucketsCount)
                {
                    b = bucketsCount - 1;
                }
                algo.Buckets[b].Cards.Add(shuffler.Sequence[p]);
            }
        }
Пример #16
0
 public RandomHandGenerator(int seed)
 {
     _cardRng = new SequenceRng(seed, StdDeck.Descriptor.FullDeckIndexes);
 }
Пример #17
0
        /// <summary>
        /// Plays a ring game session or one subsession of seat-permutation session.
        /// </summary>
        void PlaySimpleSession(int rngSeed)
        {
            _dealer = new SequenceRng(CreateUnderlyingRng(rngSeed), _gameDef.DeckDescr.FullDeckIndexes);
            int gamesCount = _sessionCfg.GamesCount;

            if (IsReplaying())
            {
                _dealLog.Clear();
                GameLogParser gameLogParser = new GameLogParser();
                gameLogParser.OnGameRecord += new GameLogParser.OnGameRecordHandler(gameLogParser_OnGameRecord);
                gameLogParser.OnError      += new GameLogParser.OnErrorHandler(gameLogParser_OnError);

                gameLogParser.ParsePath(_sessionCfg.ReplayFrom.Get(Props.Global));
                gamesCount = Math.Min(_sessionCfg.GamesCount, _dealLog.Count);
            }

            for (int gameNumber = 0; gameNumber < gamesCount; gameNumber++)
            {
                if (_sessionCfg.Kind == SessionKind.RingGame && QuitAtNextPossiblePoint)
                {
                    break;
                }

                GameRecord dealRecord;

                if (IsReplaying())
                {
                    dealRecord = _dealLog[gameNumber];
                    for (int a = 0; a < dealRecord.Actions.Count;)
                    {
                        switch (dealRecord.Actions[a].Kind)
                        {
                        case Ak.d:
                            // Keep these actions.
                            ++a;
                            break;

                        default:
                            // Remove these actions
                            dealRecord.Actions.RemoveAt(a);
                            break;
                        }
                    }
                }
                else
                {
                    dealRecord    = DealCards();
                    dealRecord.Id = gameNumber.ToString();
                }

                GameRunner game            = new GameRunner(_gameDef, _sessionPlayers, dealRecord);
                GameRecord finalGameRecord = game.Run();

                if (IsLoggingEnabled)
                {
                    _gameLog.WriteLine(finalGameRecord.ToString());
                    _gameLog.Flush();
                }

                if (OnGameEnd != null)
                {
                    OnGameEnd(finalGameRecord);
                }

                if (!_sessionCfg.FixButton)
                {
                    // Move button: [0, 1, 2] -> [1, 2, 0]
                    _sessionPlayers.RotateMinCopy(_sessionPlayers.Count - 1);
                }
            }
        }