Ejemplo n.º 1
0
  def test_order(self):
    # Sort by suit first.
    self.assertLess(Card(Suit.HEARTS, CardValue.ACE),
                    Card(Suit.DIAMONDS, CardValue.KING))
    self.assertLess(Card(Suit.HEARTS, CardValue.ACE, True),
                    Card(Suit.DIAMONDS, CardValue.KING, False))
    self.assertLess(Card(Suit.HEARTS, CardValue.ACE, False),
                    Card(Suit.DIAMONDS, CardValue.KING, True))

    # For same suit, sort by card value.
    self.assertLess(Card(Suit.HEARTS, CardValue.KING),
                    Card(Suit.HEARTS, CardValue.ACE))
    self.assertLess(Card(Suit.HEARTS, CardValue.KING, True),
                    Card(Suit.HEARTS, CardValue.ACE), False)
    self.assertLess(Card(Suit.HEARTS, CardValue.KING, False),
                    Card(Suit.HEARTS, CardValue.ACE), True)

    # Sort the whole deck, check the first and last card.
    deck = Card.get_all_cards()
    # Shuffle it since it is already sorted.
    shuffled_deck = deck[:]
    random.seed(1234)
    random.shuffle(shuffled_deck)
    self.assertNotEqual(deck, shuffled_deck)
    sorted_deck = list(sorted(shuffled_deck))
    self.assertEqual(sorted_deck[0], Card(Suit.HEARTS, CardValue.JACK))
    self.assertEqual(sorted_deck[-1], Card(Suit.CLUBS, CardValue.ACE))
Ejemplo n.º 2
0
    def test_sims_table_permutations(self):
        all_cards = Card.get_all_cards()

        permutations = sims_table_perm_generator(all_cards[:6], 0, 10)
        self.assertEqual(10, len(permutations))
        self.assertEqual(len(set(tuple(p) for p in permutations)),
                         len(permutations))

        permutations = sims_table_perm_generator(all_cards[:6], 0, None)
        self.assertEqual(720, len(permutations))
        self.assertEqual(len(set(tuple(p) for p in permutations)),
                         len(permutations))

        permutations = sims_table_perm_generator(all_cards[:6], 4, None)
        self.assertEqual(30, len(permutations))
        self.assertEqual(len(set(tuple(p) for p in permutations)),
                         len(permutations))
        for i, permutation in enumerate(permutations):
            # noinspection PyTypeChecker
            self.assertEqual(sorted(permutation[:4]), permutation[:4], msg=i)

        # The number of requested permutations is higher than the total number of
        # permutations that can be generated.
        self.assertEqual(
            set(tuple(p) for p in permutations),
            set(
                tuple(p)
                for p in sims_table_perm_generator(all_cards[:6], 4, 70)))

        with self.assertRaises(AssertionError):
            sims_table_perm_generator(all_cards[:6], 20, 10)
 def test_can_only_instantiate_with_queen_or_king(self):
   for card in Card.get_all_cards():
     if card.card_value not in [CardValue.QUEEN, CardValue.KING]:
       with self.assertRaises(AssertionError):
         AnnounceMarriageAction(PlayerId.ONE, card)
     else:
       AnnounceMarriageAction(PlayerId.ONE, card)
Ejemplo n.º 4
0
    def test(self):
        all_cards = Card.get_all_cards()
        seed = 1234

        permutations = random_perm_generator(all_cards[:6], 0, 10, seed)
        self.assertEqual(10, len(permutations))
        self.assertEqual(len(set(tuple(p) for p in permutations)),
                         len(permutations))

        permutations = random_perm_generator(all_cards[:6], 0, None, seed)
        self.assertEqual(720, len(permutations))
        self.assertEqual(len(set(tuple(p) for p in permutations)),
                         len(permutations))

        permutations = random_perm_generator(all_cards[:6], 4, None, seed)
        self.assertEqual(30, len(permutations))
        self.assertEqual(len(set(tuple(p) for p in permutations)),
                         len(permutations))
        for i, permutation in enumerate(permutations):
            # noinspection PyTypeChecker
            self.assertEqual(sorted(permutation[:4]), permutation[:4], msg=i)

        with self.assertRaises(AssertionError):
            random_perm_generator(all_cards[:6], 20, 10)

        # Test the default RNG
        permutations = random_perm_generator(all_cards[:6], 0, 10)
        self.assertEqual(10, len(permutations))
        self.assertEqual(len(set(tuple(p) for p in permutations)),
                         len(permutations))
 def test_cannot_play_cards_not_in_hand(self):
   game_state = get_game_state_for_tests()
   for card in Card.get_all_cards():
     action = PlayCardAction(PlayerId.ONE, card)
     self.assertEqual(card in game_state.cards_in_hand[PlayerId.ONE],
                      action.can_execute_on(game_state))
     self.assertEqual(card in game_state.cards_in_hand[PlayerId.ONE],
                      action.can_execute_on(game_state.next_player_view()))
   action = PlayCardAction(PlayerId.ONE,
                           game_state.cards_in_hand[PlayerId.ONE][0])
   self.assertTrue(action.can_execute_on(game_state))
   self.assertTrue(action.can_execute_on(game_state.next_player_view()))
   game_state = action.execute(game_state)
   for card in Card.get_all_cards():
     action = PlayCardAction(PlayerId.TWO, card)
     self.assertEqual(card in game_state.cards_in_hand[PlayerId.TWO],
                      action.can_execute_on(game_state))
     self.assertEqual(card in game_state.cards_in_hand[PlayerId.TWO],
                      action.can_execute_on(game_state.next_player_view()))
Ejemplo n.º 6
0
 def create_widgets_for_all_cards(
         path: Optional[str] = None) -> Dict[Card, "CardWidget"]:
     """
 Creates a CardWidget for each of the 20 possible cards.
 :param path: The path to the folder containing the card images.
 """
     kwargs = {
         'do_rotation': False,
         'do_scale': False,
         'do_translation': False
     }
     return {
         card: CardWidget(card, path=path, **kwargs)
         for card in Card.get_all_cards()
     }
Ejemplo n.º 7
0
    def _compute_metric(metric_name, func):
        # pylint: disable=too-many-locals
        cards = Card.get_all_cards()[:14]
        num_runs = 10
        permutations_generators = [
            random_perm_generator, lexicographic_perm_generator,
            sims_table_perm_generator
        ]
        num_generators = len(permutations_generators)
        generator_columns = []
        series = []
        test_scenarios = [10, 20, 50, 100, 200, 500, 1000]
        for perm_generator in permutations_generators:
            name = perm_generator.__name__
            generator_columns.append(name)
            all_timing_data = []
            for num_permutations_requested in test_scenarios:
                timing_data = func(perm_generator, cards, 5,
                                   num_permutations_requested, num_runs)
                all_timing_data.extend(timing_data)
            all_timing_data = pandas.Series(all_timing_data)
            all_timing_data.name = name
            series.append(all_timing_data)

        series_description = []
        for num_permutations_requested in test_scenarios:
            series_description.extend([num_permutations_requested] * num_runs)
        series.append(
            pandas.Series(data=series_description, name="test_scenarios"))

        dataframe = pandas.concat(series, axis=1)

        eval_data_folder = os.path.join(os.path.dirname(__file__), "eval",
                                        "data")
        # noinspection PyTypeChecker
        dataframe.to_csv(os.path.join(eval_data_folder,
                                      f"permutations_{metric_name}.csv"),
                         index=False)

        dataframe.boxplot(column=generator_columns,
                          by="test_scenarios",
                          layout=(1, num_generators),
                          figsize=(5 * num_generators, 5))
        plt.suptitle(f"{metric_name} data based on {num_runs} runs for each " +
                     "test_scenarios")
        plt.savefig(
            os.path.join(eval_data_folder, f"permutations_{metric_name}.png"))
Ejemplo n.º 8
0
def get_unseen_cards(game_view: GameState) -> List[Card]:
    """
  Returns the sorted list of cards that were not yet seen by the player
  corresponding to the given game view.
  """
    cards_set = game_view.cards_in_hand.one + game_view.cards_in_hand.two + \
                game_view.talon + [game_view.trump_card] + \
                [game_view.current_trick.one, game_view.current_trick.two] + \
                [trick.one for trick in game_view.won_tricks.one] + \
                [trick.two for trick in game_view.won_tricks.one] + \
                [trick.one for trick in game_view.won_tricks.two] + \
                [trick.two for trick in game_view.won_tricks.two]
    cards_set = {
        card
        for card in Card.get_all_cards() if card not in cards_set
    }
    cards_set = list(sorted(cards_set))
    return cards_set
Ejemplo n.º 9
0
    def test(self):
        all_cards = Card.get_all_cards()

        permutations = lexicographic_perm_generator(all_cards[:6], 0, 10)
        self.assertEqual(10, len(permutations))
        self.assertEqual(len(set(tuple(p) for p in permutations)),
                         len(permutations))

        permutations = lexicographic_perm_generator(all_cards[:6], 0, None)
        self.assertEqual(720, len(permutations))
        self.assertEqual(len(set(tuple(p) for p in permutations)),
                         len(permutations))

        permutations = lexicographic_perm_generator(all_cards[:6], 4, None)
        self.assertEqual(30, len(permutations))
        self.assertEqual(len(set(tuple(p) for p in permutations)),
                         len(permutations))
        for i, permutation in enumerate(permutations):
            # noinspection PyTypeChecker
            self.assertEqual(sorted(permutation[:4]), permutation[:4], msg=i)

        # The number of requested permutations is higher than the total number of
        # permutations that can be generated.
        self.assertEqual(permutations,
                         lexicographic_perm_generator(all_cards[:6], 4, 70))

        # Test that the permutations are generated in the expected order.
        index_permutations = [[0, 1, 2, 3, 4], [0, 1, 2, 4,
                                                3], [0, 1, 3, 4, 2],
                              [0, 2, 3, 4, 1], [1, 2, 3, 4, 0]]
        expected_permutations = [[all_cards[index] for index in perm]
                                 for perm in index_permutations]
        self.assertEqual(expected_permutations,
                         lexicographic_perm_generator(all_cards[:5], 4, None))

        with self.assertRaises(AssertionError):
            lexicographic_perm_generator(all_cards[:6], 20, 10)
Ejemplo n.º 10
0
 def new(dealer: PlayerId = PlayerId.ONE,
         random_seed: Optional[Any] = None) -> "GameState":
   """
   Creates and returns a new game state representing the beginning of a new
   game.
   :param dealer: The PlayerID that deals the cards. The opponent will be
   to lead.
   :param random_seed: Seed to pass to the random number generator. Calls using
   the same seed will shuffle the deck in the same way. The game states can be
   different, depending on who is the dealer. If the dealer is the same the
   game states will be equal.
   :return: the new game state.
   """
   deck = Card.get_all_cards()
   rng = random.Random(x=random_seed)
   rng.shuffle(deck)
   if dealer == PlayerId.ONE:
     cards_in_hand = PlayerPair(one=deck[:5], two=deck[5:10])
   else:
     cards_in_hand = PlayerPair(one=deck[5:10], two=deck[:5])
   trump_card = deck[10]
   return GameState(cards_in_hand=cards_in_hand, trump=trump_card.suit,
                    trump_card=trump_card, talon=deck[11:],
                    next_player=dealer.opponent())
Ejemplo n.º 11
0
 def test_create_and_print_all_cards():
   deck = Card.get_all_cards()
   for card in deck:
     print(repr(card), card)
Ejemplo n.º 12
0
 def test_get_all_cards(self):
   deck = Card.get_all_cards()
   self.assertEqual(20, len(deck))
   self.assertEqual(20, len(set(deck)))
   self.assertEqual(deck, sorted(deck))
Ejemplo n.º 13
0
 def _get_remaining_cards(self, game_view: GameState) -> List[Card]:
     remaining_cards = set(Card.get_all_cards())
     remaining_cards -= set(self._my_cards)
     remaining_cards -= set(self._played_cards)
     remaining_cards -= {game_view.trump_card}
     return list(remaining_cards)
Ejemplo n.º 14
0
        return animation

    def __repr__(self):
        result = super().__repr__()
        if hasattr(self, "_card"):
            result += str(self._card)
        return result


if __name__ == "__main__":

    def toggle_visible(clicked_card_widget: CardWidget):
        animation = clicked_card_widget.get_flip_animation(0.5, True)
        animation.start(clicked_card_widget)

    float_layout = FloatLayout()
    float_layout.size = 1000, 1000
    deck = Card.get_all_cards()
    random.shuffle(deck)

    for _card in deck:
        card_widget = CardWidget(_card)
        card_widget.size = 240, 370
        card_widget.grayed_out = random.random() > 0.5
        card_widget.pos = random.randint(100, 900), random.randint(100, 900)
        card_widget.rotation = random.randint(0, 180)
        card_widget.bind(on_double_tap=toggle_visible)
        float_layout.add_widget(card_widget)

    runTouchApp(float_layout)