示例#1
0
        public void PokerHandDetectorShouldDetectCombination(DetectHandTestCase testCase)
        {
            var detector = new PokerHandDetector();

            var hand = detector.DetectTopPokerHand(CardParser.ParseCards(testCase.Cards).ToHashSet());

            Assert.AreEqual(
                expected: testCase.ExpectedCombinationKind,
                actual: hand.CardCombination.Kind);

            var cardCombnation = hand.CardCombination as CardCombination;

            CollectionAssert.AreEquivalent(
                expected: CardParser.ParseCards(testCase.ExpectedCombinationCards),
                actual: cardCombnation.Cards);

            var expectedKickers = CardParser.ParseCards(testCase.ExpectedKickers).ToList();
            var actualKickers   = hand.Kickers
                                  .OrderByDescending(k => k.Value)
                                  .ThenByDescending(k => k.Suit) // added to define ordering in test as it matters
                                  .ToList();

            CollectionAssert.AreEqual(
                expected: expectedKickers,
                actual: actualKickers
                );
        }
示例#2
0
    public void addCardToDiscard(string cardName)
    {
        GameObject newCard = CardPooler.instance.PopCard(cardName, discardTransform);

        newCard.GetComponent <CardButton>().enabled = false;

        if (cardInDiscard)
        {
            previousCard = CardParser.deparseCard(cardInDiscard.GetComponent <CardButton>().myCard);
            cardInDiscard.GetComponent <CardButton>().enabled = true;
            CardPooler.instance.PushCard(cardInDiscard);
            cardInDiscard = null;
        }
        else
        {
            previousCard = "";
        }

        // notification
        var notification = new Notification($"Discarded {newCard.GetComponent<CardButton>().myCard.ToString()}", 3, true, Color.black);

        NotificationManager.instance.addNotification(notification);

        cardInDiscard = newCard;
    }
示例#3
0
        public void CardParserLoadsCsv()
        {
            var sut   = new CardParser();
            var lines = sut.LoadInput("DoD");

            Assert.IsTrue(lines > 0);
            sut.DisplayCode();
        }
示例#4
0
        public RoundLine(string line)
        {
            Cards = new BoardCards();

            if (line.Contains("HOLE CARDS"))
            {
                Round = HandRound.HoleCards;
            }
            else if (line.Contains("FLOP"))
            {
                Round = HandRound.Flop;
            }
            else if (line.Contains("TURN"))
            {
                Round = HandRound.Turn;
            }
            else if (line.Contains("RIVER"))
            {
                Round = HandRound.River;
            }
            else if (line.Contains("SHOWDOWN"))
            {
                Round = HandRound.Showdown;
            }
            else if (line.Contains("SUMMARY"))
            {
                Round = HandRound.Summary;
            }

            switch (Round)
            {
            case HandRound.Flop:
            {
                IList <CardModel> cards = CardParser.ParseCards(line.Substring(line.LastIndexOf("***") + 3).Trim());
                Cards = new BoardCards(cards);
                break;
            }

            case HandRound.Turn:
            {
                IList <CardModel> cards = CardParser.ParseCards(line.Substring(line.LastIndexOf("***") + 3).Trim());
                Cards.Turn = cards[3];
                break;
            }

            case HandRound.River:
            {
                IList <CardModel> cards = CardParser.ParseCards(line.Substring(line.LastIndexOf("***") + 3).Trim());
                Cards.River = cards[4];
                break;
            }

            default:
            {
                break;
            }
            }
        }
示例#5
0
 public new string ToString()
 {
     if (suit == Suit.Joker)
     {
         return(suit.ToString());
     }
     else if (number == 10)
     {
         return("10 of " + suit.ToString() + "s");
     }
     return(CardParser.valueToChar(number) + " of " + suit.ToString() + "s");
 }
        public void PokerHandsComparisons(CompareHandsTestCase testCase)
        {
            var detector     = new PokerHandDetector();
            var commonCards  = CardParser.ParseCards(testCase.CommonCards);
            var aliceCards   = CardParser.ParseCards(testCase.AliceCards);
            var bobCards     = CardParser.ParseCards(testCase.BobCards);
            var aliceTopHand = detector.DetectTopPokerHand(aliceCards.Concat(commonCards).ToHashSet());
            var bobTopHand   = detector.DetectTopPokerHand(bobCards.Concat(commonCards).ToHashSet());
            var winner       = DetectWinner(aliceTopHand, bobTopHand);

            Assert.AreEqual(expected: testCase.ExpectedTopHandPlayer, actual: winner);
        }
示例#7
0
 private void Gameloop()
 {
     foreach (Spacecraft spacecraft in spacecrafts)
     {
         ActionStack cards = spacecraft.player.actionSelection;
         for (int i = 0; i < cards.actionList.Count; i++)
         {
             SpacecraftAction action = CardParser.ParseCard(cards.getActionCard(i));
             spacecraft.AddAction(action);
         }
     }
 }
示例#8
0
        public void ParseCardsShouldSuccess()
        {
            var parsedCards   = CardParser.ParseCards("2♥ 10♢ A♣ J♤").ToList();
            var expectedCards = new[]
            {
                new Card(CardValue.Two, Suit.Hearts),
                new Card(CardValue.Ten, Suit.Diamonds),
                new Card(CardValue.Ace, Suit.Clovers),
                new Card(CardValue.Jack, Suit.Spades),
            };

            CollectionAssert.AreEqual(expectedCards, actual: parsedCards);
        }
    private void Awake()
    {
        cardIdToData = CardParser.GetCardData();

        cardFamilyToColor = new Dictionary <CardFamily, Color>();
        foreach (CardFamilyColor family in cardFamilyColors)
        {
            cardFamilyToColor[family.family] = family.color;
        }
        cardEdgeToSprite = new Dictionary <CardEdge, Sprite>();
        foreach (CardEdgeSprite edge in cardEdgeSprites)
        {
            cardEdgeToSprite[edge.edge] = edge.sprite;
        }
    }
示例#10
0
    public void SendFirstOut()
    {
        if (!GameManager.instance.myTurn)
        {
            Debug.LogWarning("It is not your turn, you cannot go out!");
            return;
        }

        JSONObject OutDeck = new JSONObject();

        for (int i = 0; i < 4; i++)
        {
            JSONObject cardArr = JSONObject.Create(JSONObject.Type.ARRAY);
            //print("type? " + cardArr.type);

            cardArr.Add(dropSpots[i].outState.ToString());

            if (dropSpots[i].outState != Out.None)
            {
                foreach (CardButton c in dropSpots[i].cards)
                {
                    cardArr.Add(CardParser.deparseCard(c.myCard));
                }
            }

            //cardArr.Add(Out.Run.ToString());
            //cardArr.Add("joker_2");
            //cardArr.Add("Club_3");
            //cardArr.Add("Club_4");
            //print("contents? - " + cardArr);

            OutDeck.AddField("out" + i, cardArr);
        }

        //OutDeck.AddField("out1", cardArr);
        //OutDeck.AddField("out2", cardArr);
        print("test? - " + OutDeck);
        nh_network.server.SendFirstOut(OutDeck);

        hasGoneOut = true;
        GameManager.instance.outButton.SetActive(false);
        goOutBtn.interactable = false;

        GameManager.instance.openOutPanel(false);
    }
示例#11
0
    /// <summary>
    /// Returns true is card is discarded
    /// </summary>
    public bool DiscardCard(CardButton card)
    {
        string cardName = CardParser.deparseCard(card.GetComponent <CardButton>().myCard);

        if (GameManager.instance.discardCard(cardName))
        {
            GameManager.instance.finishFinalTurn(card);

            GameManager.instance.myHand.Remove(card);
            CardPooler.instance.PushCard(card.gameObject);

            NotificationManager.instance.myTurn(false);
            return(true);
        }
        else
        {
            return(false);
        }
    }
示例#12
0
        public static void PokerSessionShouldDistributePotsCorrectly(DistributePotTestCase testCase)
        {
            var players = testCase.Players.Select(p => new Player
            {
                PlayerPot = testCase.PlayerPot,
                Cards     = CardParser.ParseCards(p.Cards).ToList(),
                Strategy  = p.Folds
                        ? (IPlayerStrategy) new FoldAlwaysStategy()
                        : new AllInStrategy()
            }).ToList();

            var session = new PokerSession(players);

            session.CheatCommunityCards(CardParser.ParseCards(testCase.CommunityCards).ToList());
            session.Simulate();

            CollectionAssert.AreEqual(
                expected: testCase.Players.Select(p => p.ExpectedPot).ToList(),
                actual: players.Select(p => p.PlayerPot)
                );
        }
示例#13
0
    public void SendUpdatedOutDeck()
    {
        JSONObject OutDeck = new JSONObject();

        for (int i = 0; i < 4; i++)
        {
            JSONObject cardArr = JSONObject.Create(JSONObject.Type.ARRAY);
            cardArr.Add(firstOutDrops[i].outState.ToString());

            if (firstOutDrops[i].outState != Out.None)
            {
                foreach (CardButton c in firstOutDrops[i].cards)
                {
                    cardArr.Add(CardParser.deparseCard(c.myCard));
                }
            }

            OutDeck.AddField("out" + i, cardArr);
        }

        nh_network.server.UpdateFirstOut(OutDeck);
    }
示例#14
0
    public void MyCard(string cardName)
    {
        myCard     = CardParser.parseCard(cardName);
        handObject = parentObject = transform.parent;

        //set texts
        char cardText = CardParser.valueToChar(myCard.number);

        /*if (cardText == '0') transform.GetChild(1).GetComponent<TMPro.TextMeshProUGUI>().text = "10";
         * else transform.GetChild(1).GetComponent<TMPro.TextMeshProUGUI>().text = cardText.ToString();
         * transform.GetChild(0).GetComponent<TMPro.TextMeshProUGUI>().text = myCard.suit.ToString();
         *
         * if(myCard.suit == Suit.Diamond || myCard.suit == Suit.Heart)
         * {
         *  // make texts red
         *  transform.GetChild(1).GetComponent<TMPro.TextMeshProUGUI>().color = Color.red;
         *  transform.GetChild(0).GetComponent<TMPro.TextMeshProUGUI>().color = Color.red;
         * }
         * else
         * {
         *  // make texts black
         *  transform.GetChild(1).GetComponent<TMPro.TextMeshProUGUI>().color = Color.black;
         *  transform.GetChild(0).GetComponent<TMPro.TextMeshProUGUI>().color = Color.black;
         * }*/

        if (cardText == '0')
        {
            transform.GetChild(1).GetComponent <TMPro.TextMeshProUGUI>().text = "10";
            transform.GetChild(2).GetComponent <TMPro.TextMeshProUGUI>().text = "10";
        }
        else
        {
            transform.GetChild(1).GetComponent <TMPro.TextMeshProUGUI>().text = cardText.ToString();
            transform.GetChild(2).GetComponent <TMPro.TextMeshProUGUI>().text = cardText.ToString();
        }

        UpdateCardImage(false);
    }
示例#15
0
        public SummarySeatLine(string line)
        {
            SeatNumber = Convert.ToInt32(line.Split(':')[0].Split(' ')[1]);
            PlayerName = line.Split(':')[1].Split('(')[0].Trim();
            DidntBet   = line.EndsWith("(didn't bet)");
            IsLoser    = line.Contains(" and lost ");

            if (line.Contains("showed ["))
            {
                ShowsHand = true;
                string cardBuffer = line.Split('[')[1].Split(']')[0].Trim();
                HoleCards = new HoleCards(CardParser.ParseCards(cardBuffer));
            }

            if (line.Contains("and won ("))
            {
                IsWinner = true;
                string wonBuffer = line.Split(']')[1].Split('(')[1].Split(')')[0].Trim();
                Amount = Convert.ToInt32(wonBuffer);
            }
            else if (line.Contains(" collected ("))
            {
                IsWinner = true;
                string collectedBuffer = line.Substring(line.LastIndexOf('(') + 1).Replace(")", "").Trim();
                Amount = Convert.ToInt32(collectedBuffer);
            }
            else if (line.Contains(" mucked "))
            {
                ShowsHand = true;
                string cardBuffer = line.Split('[')[1].Split(']')[0].Trim();
                HoleCards = new HoleCards(CardParser.ParseCards(cardBuffer));
            }

            if (line.Contains(" with "))
            {
                HandDescription = line.Substring(line.IndexOf(" with ") + 6).Trim();
            }
        }
示例#16
0
 public DealtToLine(string line)
 {
     PlayerName = line.Split(' ')[2].Trim();
     HoleCards  = new HoleCards(CardParser.ParseCards(line.Substring(line.LastIndexOf('['))));
 }
示例#17
0
 public ShowsLine(string line)
 {
     PlayerName      = line.Split(':')[0];
     HoleCards       = new HoleCards(CardParser.ParseCards(line.Split(':')[1].Trim().Split('[')[1].Split(']')[0]));
     HandDescription = line.Split(':')[1].Trim().Split('(')[1].Split(')')[0].Trim();
 }
示例#18
0
        public SummaryBoardLine(string line)
        {
            string cardBuffer = line.Split('[')[1].Split(']')[0].Trim();

            Cards = new BoardCards(CardParser.ParseCards(cardBuffer));
        }
示例#19
0
    private async Task <CardProcessorResponse> ProcessCards(
        IDictionary <string, string> tcgLinks,
        IDictionary <string, string> ocgLinks,
        IDictionary <string, string> links
        )
    {
        var size = links.Count;

        if (Options.MaxCardsToParse <= size)
        {
            links = links.RandomSubset(Options.MaxCardsToParse).ToDictionary(kv => kv.Key, kv => kv.Value);
        }
        //links = links.Take(Options.MaxCardsToParse);

        var errors = new ConcurrentBag <Error>();
        var repo   = new YuGiOhRepository(this);
        var count  = 0;

        await Parallel.ForEachAsync(links, ParallelOptions, async (nameToLink, _) =>
        {
            var retryCount = 0;
            Exception check;

            do
            {
                var(name, link) = nameToLink;

                try
                {
                    var parser = new CardParser(name, link);
                    // var parserHash = await parser.GetParseOutput().ContinueWith(outputTask => outputTask.Result.GetMurMurHash(), _); //wanted to try ContinueWith instead of wrapping await
                    //
                    // //this is to determine whether or not to parse
                    // if (!Options.ShouldIgnoreHash && await repo.GetCardHashAsync(parser.Id) == parserHash)
                    //     continue;

                    var card       = await parser.ParseAsync();
                    card.TcgExists = tcgLinks.ContainsKey(name);
                    card.OcgExists = ocgLinks.ContainsKey(name);

                    await repo.InsertCardAsync(card);
                    // await repo.InsertCardHashAsync(card.Id, parserHash);

                    check = null;
                }
                catch (Exception ex)
                {
                    retryCount++;
                    check = ex;

                    if (retryCount == Options.Config.MaxRetry)
                    {
                        errors.Add(new Error
                        {
                            Name       = name,
                            Message    = ex.Message,
                            StackTrace = ex.StackTrace,
                            Url        = string.Format(ConstantString.YugipediaUrl + ConstantString.MediaWikiIdUrl, link),
                            Type       = Type.Card,
                            Timestamp  = DateTime.UtcNow
                        });
                    }

                    await Task.Delay(Options.Config.RetryDelay, CancellationToken.None);
                }
            } while (check is not null && retryCount < Options.Config.MaxRetry);

            var __ = WriteProgress("Cards", ref count, size);
        });

        ClearLine();

        return(new CardProcessorResponse
        {
            Count = size,
            Errors = errors
        });
    }
示例#20
0
        public IHttpActionResult Post([FromBody] Round hands)
        {
            // A lot of this validation happens client side so validating
            // here is more for the sake of thoroughness (Not assuming the
            // client is nice even though in this case I control the client.)
            // than anything else.

            if (hands == null || hands.Hands == null || hands.Hands.Count == 0)
            {
                return(BadRequest("Data is missing."));
            }

            // Perform data validation for number of cards.
            if (!hands.Hands.TrueForAll(x => x.Hand != null && x.Hand.Count == 5))
            {
                return(BadRequest("Wrong number of cards found in someone's hand."));
            }

            HashSet <string> playersPresent = new HashSet <string>();

            if (!hands.Hands.TrueForAll(x => x.Name != null && x.Name != "" && playersPresent.Add(x.Name)))
            {
                return(BadRequest("A player has no name, or there are two players with the same name!"));
            }

            HashSet <string> cardsPresent = new HashSet <string>();

            // Validate no duplicate players and no duplicate cards.
            foreach (Play play in hands.Hands)
            {
                if (!play.Hand.TrueForAll(x => cardsPresent.Add(x)))
                {
                    return(BadRequest("A card was either missing or a duplicate."));
                }
            }

            // Enumerate through all plays, picking out the highest card, in the case of a draw the
            // first player is considered the winner.
            HandValueComputer computer  = new HandValueComputer();
            CardParser        parser    = new CardParser();
            string            winPlayer = "";
            int winValue = 0;

            foreach (Play p in hands.Hands)
            {
                try
                {
                    IEnumerable <Tuple <int, char> > cards = p.Hand.Select(x => parser.ParseCard(x));
                    int val = computer.ComputeValue(cards);
                    if (val > winValue)
                    {
                        winPlayer = p.Name;
                        winValue  = val;
                    }
                }
                catch (ArgumentException ae)
                {
                    // Return a bad request in the case where a card cannot be parsed.
                    return(BadRequest("Bad card found."));
                }
            }
            return(Ok(winPlayer));
        }
示例#21
0
        private static void Main()
        {
            var game = new DosGame(new ShufflingDealer(Decks.Classic), 1, 7);
            var p    = game.Players.First();

            while (true)
            {
                var line = Console.ReadLine();
                line = line?.ToLowerInvariant().Trim();
                if (line == "quit")
                {
                    return;
                }

                if (string.IsNullOrWhiteSpace(line))
                {
                    continue;
                }

                if (line == "dos cards" || line == "dosc")
                {
                    Console.WriteLine(string.Join(Environment.NewLine, game.PersonalGameTableLines(p)));
                    continue;
                }

                if (line == "dosd")
                {
                    Console.WriteLine(game.EndTurn(p));
                    continue;
                }

                if (line.StartsWith("dos play "))
                {
                    var cardString = line.Substring(9).Trim();
                    Console.WriteLine(
                        CardParser.TryParseShortCard(cardString, out var card)
                            ? game.AddCardToCenterRow(p, card).Message
                            : $"Did not recognise the card \"{cardString}\", expected something like b9");
                    continue;
                }

                if (line.StartsWith("dos match "))
                {
                    var cardWords        = line.Substring(10).Split(" ", StringSplitOptions.RemoveEmptyEntries);
                    var cards            = new List <Card>();
                    var target           = (Card?)null;
                    var lookingForTarget = false;
                    foreach (var cardWord in cardWords)
                    {
                        if (!lookingForTarget)
                        {
                            if (cardWord == "on")
                            {
                                lookingForTarget = true;
                                continue;
                            }

                            if (CardParser.TryParseShortCard(cardWord, out var card))
                            {
                                cards.Add(card);
                            }
                        }
                        else
                        {
                            if (CardParser.TryParseShortCard(cardWord, out var card))
                            {
                                target = card;
                            }

                            break;
                        }
                    }

                    if (cards.IsEmpty() || target == null)
                    {
                        Console.WriteLine("Failed to parse your matching cards, sorry");
                    }
                    else
                    {
                        Console.WriteLine(game.MatchCenterRowCard(p, target.Value, cards.ToArray()));
                    }
                }
            }
        }
示例#22
0
 public void ReadFromSpreadsheet()
 {
     cardInfoDictionary = CardParser.ReadMasterSpreadsheet(cardSpreadsheet);
 }