Exemplo n.º 1
0
class Test(unittest.TestCase):
    def setUp(self):
        self.card_1 = Card("Geography", "What is the capital of Alaska?",
                           "Juneau")
        self.card_2 = Card(
            "STEM",
            "The Viking spacecraft sent back to Earth photographs and reports about the surface of which planet?",
            "Mars")
        self.card_3 = Card(
            "STEM",
            "Describe in words the exact direction that is 697.5° clockwise from due north?",
            "North north west")
        self.deck = Deck([self.card_1, self.card_2, self.card_3])

    def test_it_has_attributes(self):
        self.assertEqual(self.deck.cards,
                         [self.card_1, self.card_2, self.card_3])

    def test_add_card(self):
        self.assertEqual(self.deck.cards,
                         [self.card_1, self.card_2, self.card_3])

        self.card4 = Card("Geography", "What is it?", "I don't know!")

        expected = [self.card_1, self.card_2, self.card_3, self.card4]
        self.deck.add_card(self.card4)
        self.assertEqual(self.deck.cards, expected)

    def test_it_can_get_all_categories(self):
        expected = ['STEM', 'Geography']
        self.assertEqual(self.deck.all_categories(), expected)
Exemplo n.º 2
0
def main(deck_paths, blacklist, columns, sort_by):
    # build card "database"
    db = DB(blacklist)

    # turn all the deck files into decks
    decks = list(map(Deck.from_txt_deck, deck_paths))

    # map cards in deck to cards in db
    cards = Deck(
        None,
        {card: count
         for deck in decks for card, count in deck.cards.items()})

    # lookup for IDs of decks
    id_lookup = {card: deck.identity for deck in decks for card in deck.cards}

    # lookup identity if needed
    def get_identity(deck, db, card):
        identity = id_lookup[card]
        return {'display': identity, 'sort': (identity, )}

    all_columns = {
        'cycle': ('Cycle', Deck.card_cycle),
        'type': ('Type', Deck.card_type),
        'identity': ('Identity', get_identity),
        'faction': ('Faction', Deck.card_faction),
    }

    print(
        cards.to_markdown(db,
                          title=None,
                          columns=[(key, all_columns[key][0],
                                    all_columns[key][1]) for key in columns],
                          sort_by=sort_by))
Exemplo n.º 3
0
 def setUp(self):
     self.card_one = Card("Heart", "5", 5)
     self.card_two = Card("Diamond", "Jack", 11)
     self.card_three = Card("Spade", "7", 7)
     self.card_four = Card("Spade", "Ace", 14)
     cards = [self.card_one, self.card_two, self.card_three, self.card_four]
     self.deck = Deck(cards)
Exemplo n.º 4
0
 def test_add_card(self):
     """add_card() interface tests."""
     deck_name = 'test deck'
     cards = ['card 0', 'card 1', 'card 2']
     deck = Deck(deck_name)
     for idx, c in enumerate(cards, 1):
         deck.add_card(c)
         self.assertEqual(len(deck), idx)
Exemplo n.º 5
0
 def setUp(self):
     self.deck_name = 'test deck'
     self.deck = Deck(self.deck_name)
     self.cards = [
         Flashcard('q0', 'a0', 0, 0, str(datetime.datetime.utcnow())),
         Flashcard('q1', 'a1', 0, 0, str(datetime.datetime.utcnow())),
         Flashcard('q2', 'a2', 0, 0, str(datetime.datetime.utcnow()))
     ]
     for c in self.cards:
         self.deck.add_card(c)
Exemplo n.º 6
0
 def test_deck_count(self):
     card_1 = Card("What is the capital of Alaska?", "Juneau", "Geography")
     card_2 = Card(
         "The Viking spacecraft sent back to Earth photographs and reports about the surface of which planet?",
         "Mars", "STEM")
     card_3 = Card(
         "Describe in words the exact direction that is 697.5° clockwise from due north?",
         "North north west", "STEM")
     cards = [card_1, card_2, card_3]
     deck = Deck(cards)
     self.assertEqual(deck.count(), 3)
Exemplo n.º 7
0
    def __init__(self, num_players: int = 4, p1_override: Hand = None):
        if num_players < 1:
            raise Exception("Can't play a round with less than 1 player")

        self.deck = Deck(omit_cards=p1_override).shuffle()
        self.player_hands = {}
        for i in range(0, num_players):
            if p1_override and i == 0:
                self.player_hands[i] = p1_override
                continue
            self.player_hands[i] = Hand(self.deck.deal_cards(2))
        self.community_cards = Hand(self.deck.deal_cards(5))
Exemplo n.º 8
0
 def setUp(self):
     self.card_1 = Card("Geography", "What is the capital of Alaska?",
                        "Juneau")
     self.card_2 = Card(
         "STEM",
         "The Viking spacecraft sent back to Earth photographs and reports about the surface of which planet?",
         "Mars")
     self.card_3 = Card(
         "STEM",
         "Describe in words the exact direction that is 697.5° clockwise from due north?",
         "North north west")
     self.deck = Deck([self.card_1, self.card_2, self.card_3])
Exemplo n.º 9
0
    def test_equality(self):
        """__eq__() tests."""
        other_deck = Deck('other deck')
        for c in self.cards:
            other_deck.add_card(c)

        other_other_deck = Deck(self.deck_name)

        self.assertEqual(self.deck, self.deck)
        self.assertNotEqual(self.deck, other_deck)
        self.assertNotEqual(self.deck, other_other_deck)
        self.assertNotEqual(self.deck, 'not a deck')
Exemplo n.º 10
0
class HandConstructorTest(unittest.TestCase):
    def setUp(self):
        ''' set up a variety of hands and community cards manually for testing
        '''
        self.deck = Deck(SUITS, RANKS)
        self.hand = Hand(self.deck.deal(), self.deck.deal())
        self.community_cards = CommunityCards(self.deck.deal(),
                                              self.deck.deal(),
                                              self.deck.deal(),
                                              self.deck.deal(),
                                              self.deck.deal())
        self.hand_straight = Hand(Card('A', 'S'), Card('K', 'S'))
        self.cc_straight = CommunityCards(Card('Q', 'S'), Card('3', 'H'),
                                          Card('J', 'S'), Card('T', 'S'),
                                          Card('9', 'S'))
        self.hand_flush = Hand(Card('T', 'S'), Card('3', 'S'))
        self.cc_flush = CommunityCards(Card('4', 'S'), Card('7', 'H'),
                                       Card('9', 'S'), Card('J', 'S'),
                                       Card('K', 'S'))

        self.straight_hand_eval = HandConstructor(self.hand_straight,
                                                  self.cc_straight)
        self.flush_hand_eval = HandConstructor(self.hand_flush, self.cc_flush)

    def test_is_flush(self):
        ''' no test yet
        '''
        pass

    def test_order_suits(self):
        ''' no test yet
        '''
        self.flush_hand_eval.order_suits()

    def test_tally_ranks(self):
        ''' no test yet
        '''
        self.flush_hand_eval.tally_ranks()

    def test_eval_kinds(self):
        '''
        '''
        self.flush_hand_eval.eval_kinds()

    def test_is_straight(self):
        self.assertTrue(self.straight_hand_eval.eval_straight())

    def test_straight_rank(self):
        ''' test report rank of a six or seven card straight correctly
        '''
        # TODO: i may have changed the input data and screwed this up... when verified remove this comment
        self.assertEqual(self.straight_hand_eval.eval_straight(), True)
Exemplo n.º 11
0
    def __init__(self, methodName='runTest'):
        self.island = CardMock(name='Island', type='')
        self.mountain = CardMock(name='Mountain', type='')
        self.tireless = CardMock(name='Tireless Tracker', type='')

        self.test_deck = Deck()
        self.my_hand = Hand()

        deck_location = 'D:\\code\\delirium\\tests\\test_data\\delirium.txt'
        self.gb_delirium = Deck()
        self.gb_delirium.load_text_list(deck_location)

        unittest.TestCase.__init__(self, methodName)
Exemplo n.º 12
0
class TestDeck(unittest.TestCase):
    def setUp(self):
        self.card_one = Card("Heart", "5", 5)
        self.card_two = Card("Diamond", "Jack", 11)
        self.card_three = Card("Spade", "7", 7)
        self.card_four = Card("Spade", "Ace", 14)
        cards = [self.card_one, self.card_two, self.card_three, self.card_four]
        self.deck = Deck(cards)

    def test_it_exists(self):
        assert type(self.deck) == Deck
        assert type(self.deck.cards[0]) == Card

    def test_value_of_card_at(self):
        assert self.deck.value_of_card_at(0) == 5
        assert self.deck.value_of_card_at(1) == 11
        assert self.deck.value_of_card_at(2) == 7

    def test_high_ranking_cards(self):
        assert self.deck.high_ranking_cards() == [
            self.card_two, self.card_four
        ]

    def test_percent_high_ranking(self):
        assert self.deck.percent_high_ranking() == 0.5

    def test_remove_card(self):
        self.deck.remove_card()
        assert len(self.deck.cards) == 3

    def test_add_card(self):
        new_card = Card("Heart", "King", 13)
        self.deck.add_card(new_card)
        assert len(self.deck.cards) == 5
Exemplo n.º 13
0
def simulate_all_hands(
        num_players: int = 4,
        iterations_per_hand: int = 10) -> Dict[str, Dict[str, int]]:
    outcomes = {}
    target_iterations = 52 * 51 * iterations_per_hand
    cur_iterations = 0
    log_interval = 1000
    time_checkpoint_s = time.time()
    initial_t = time_checkpoint_s

    for c1 in Deck().cards:
        for c2 in Deck().cards:
            win = 0
            loss = 0
            tie = 0
            if c1 != c2:
                for it in range(0, iterations_per_hand):
                    outcome = simulate_round_with_override(
                        num_players, [c1, c2])
                    if outcome == SimpleRound.Outcome.WIN:
                        win += 1
                    elif outcome == SimpleRound.Outcome.TIE:
                        tie += 1
                    else:
                        loss += 1
                    cur_iterations += 1
                    if cur_iterations % log_interval == 0:
                        new_t = time.time()
                        delta_t = new_t - time_checkpoint_s
                        time_checkpoint_s = new_t
                        speed = round(log_interval / delta_t, 2)
                        print(
                            f"{round((float(cur_iterations) / float(target_iterations)) * 100, 2)}% Complete - "
                            f"{cur_iterations}/{target_iterations} - "
                            f"simulations/s: {speed} - "
                            f"time remaining: {round((target_iterations - cur_iterations) / speed / 3600, 2)}h"
                        )
                c1_str = f"{c1[0]}{c1[1]}"
                c2_str = f"{c2[0]}{c2[1]}"

                if c1_str not in outcomes:
                    outcomes[c1_str] = {}
                outcomes[c1_str][c2_str] = {'w': win, 'l': loss, 't': tie}

    print(
        f"Total simulation time: {round((time.time() - initial_t) / 3600.0, 2)}h "
        f"({round((time.time() - initial_t), 2)}s)")
    return outcomes
Exemplo n.º 14
0
 def setUp(self):
   card_one = Card("Heart", "5", 5)
   card_two = Card("Diamond", "Jack",11)
   card_three = Card("Spade", "7", 7)
   card_four = Card("Spade", "Ace", 14)
   cards = [card_one, card_two, card_three, card_four]
   self.deck = Deck(cards)
   self.player1 = Player("John", self.deck)
   card_five = Card("Heart", "8", 8)
   card_six = Card("Diamond", "Jack",11)
   card_seven = Card("Spade", "3", 3)
   card_eight = Card("Club", "Queen", 12)
   cards2 = [card_five, card_six, card_seven, card_eight]
   self.deck2 = Deck(cards2)
   self.player2 = Player("John", self.deck2)
   self.turn = Turn(self.player1, self.player2)
Exemplo n.º 15
0
 def start(cls):
     print(
         "|                ****** Generating cards ******                |")
     time.sleep(3)
     cards = CardGenerator.generate_cards()
     deck = Deck(cards)
     interface = Interface(deck)
     interface.welcome()
Exemplo n.º 16
0
 def setUp(self):
     card_one = Card("Heart", "5", 5)
     card_two = Card("Diamond", "Jack", 11)
     card_three = Card("Spade", "7", 7)
     card_four = Card("Spade", "Ace", 14)
     cards = [card_one, card_two, card_three, card_four]
     self.deck = Deck(cards)
     self.player = Player("John", self.deck)
Exemplo n.º 17
0
    def test_deck_name(self):
        """_deck_name() interface tests."""
        deck_name = 'Mr. Neutron'
        named = Deck._deck_name(
            '{} {}'.format(Deck.ReservedWords.name, deck_name)
        )

        self.assertEqual(named, deck_name)
Exemplo n.º 18
0
 def test_starts_with_reserved_word(self):
     """_starts_with_reserved_word() interface tests."""
     for w in Deck.ReservedWords.all():
         self.assertTrue(
             Deck._starts_with_reserved_word(
                 '{} is a reserved word'.format(w)
             )
         )
Exemplo n.º 19
0
def score_all_hands() -> Dict[Tuple[str, str], Decimal]:
    scores = {}

    for c1 in Deck().cards:
        for c2 in Deck().cards:
            for c3
            if c1 != c2:

                outcome = simulate_round(num_players, [c1, c2])
                if outcome == SimpleRound.Outcome.WIN:
                    win += 1
                elif outcome == SimpleRound.Outcome.TIE:
                    tie += 1
                else:
                    loss += 1
                cur_iterations += 1
                if cur_iterations % log_interval == 0:
                    print(f"{round((float(cur_iterations)/float(target_iterations))*100, 2)}% Complete - {cur_iterations}/{target_iterations}")
Exemplo n.º 20
0
    def test_load_and_save(self):
        """load() and save() interface tests."""
        # Save and load the deck.
        with tempfile.NamedTemporaryFile(mode='w', newline='') as tf:
            self.deck.save(tf.name, overwrite=True)
            saved_deck = Deck.load(tf.name)

        # Test.
        self.assertEqual(saved_deck, self.deck)
Exemplo n.º 21
0
 def test_it_exists(self):
     category_1 = {"category": "Geography"}
     card_1 = Card("What is the capital of Alaska?", "Juneau", category_1)
     category_2 = {"category": "Art"}
     card_2 = Card("Who painted Starry Night?", "Vincent Van Gogh",
                   category_2)
     category_3 = {"category": "STEM"}
     card_3 = Card(
         "The Viking spacecraft sent back to Earth photographs and reports about the surface of which planet?",
         "Mars", category_3)
     deck = Deck([card_1, card_2, card_3])
     assert isinstance(deck, Deck)
Exemplo n.º 22
0
    def setUp(self):
        ''' set up a variety of hands and community cards manually for testing
        '''
        self.deck = Deck(SUITS, RANKS)
        self.hand = Hand(self.deck.deal(), self.deck.deal())
        self.community_cards = CommunityCards(self.deck.deal(),
                                              self.deck.deal(),
                                              self.deck.deal(),
                                              self.deck.deal(),
                                              self.deck.deal())
        self.hand_straight = Hand(Card('A', 'S'), Card('K', 'S'))
        self.cc_straight = CommunityCards(Card('Q', 'S'), Card('3', 'H'),
                                          Card('J', 'S'), Card('T', 'S'),
                                          Card('9', 'S'))
        self.hand_flush = Hand(Card('T', 'S'), Card('3', 'S'))
        self.cc_flush = CommunityCards(Card('4', 'S'), Card('7', 'H'),
                                       Card('9', 'S'), Card('J', 'S'),
                                       Card('K', 'S'))

        self.straight_hand_eval = HandConstructor(self.hand_straight,
                                                  self.cc_straight)
        self.flush_hand_eval = HandConstructor(self.hand_flush, self.cc_flush)
Exemplo n.º 23
0
    def __init__(self):
        deck = Deck.shuffle()
        self.trump = deck[-1]

        hand1 = deck[:HAND_SIZE]
        deck = deck[HAND_SIZE:]

        hand2 = deck[:HAND_SIZE]

        self.deck = deck[HAND_SIZE:]
        self.ai = AIPlayer(self, hand1)
        self.player = Player(self, hand2)
        self.set_first_turn()
Exemplo n.º 24
0
class SimpleRound:
    community_cards: Hand
    player_hands: Dict[int, Optional[Hand]]
    deck: Deck

    def __init__(self, num_players: int = 4, p1_override: Hand = None):
        if num_players < 1:
            raise Exception("Can't play a round with less than 1 player")

        self.deck = Deck(omit_cards=p1_override).shuffle()
        self.player_hands = {}
        for i in range(0, num_players):
            if p1_override and i == 0:
                self.player_hands[i] = p1_override
                continue
            self.player_hands[i] = Hand(self.deck.deal_cards(2))
        self.community_cards = Hand(self.deck.deal_cards(5))

    def results(self) -> Dict[int, Outcome]:
        round_score = RoundScore(self.player_hands, self.community_cards)
        result = {}
        winning_result = max([v for k, v in round_score.scores.items()])
        tie = len(
            list(
                filter(lambda v: v == winning_result,
                       round_score.scores.values()))) > 1
        for k, score in round_score.scores.items():
            if score == winning_result:
                if tie:
                    result[k] = Outcome.TIE
                else:
                    result[k] = Outcome.WIN
            else:
                result[k] = Outcome.LOSS
        return result

    def player_result(self, player_id: int) -> Outcome:
        return self.results()[player_id]
Exemplo n.º 25
0
    def setUp(self):
        ''' set up a variety of hands and community cards manually for testing
        '''
        deck = Deck(SUITS, RANKS, shuffled=True)
        players = list()
        self.player_number = 2
        for i in range(self.player_number):
            players.append(Player(name=str(i), chips=1500))

        self.player_1 = players[0]
        self.player_2 = players[1]  # initially the button, aka players[-1]

        self.game = Game(deck, players)
        self.cards_left_in_deck = len(self.game.deck.deck)
Exemplo n.º 26
0
    def test_round(self):
        card_1 = Card("What is the capital of Alaska?", "Juneau", 'Geography')
        card_2 = Card("What is the square root of 169?", "13", 'STEM')
        card_3 = Card("What is the power house of the freaking cell?",
                      "Mitochondria", 'STEM')

        cards = [card_1, card_2, card_3]

        deck = Deck(cards)

        round = Round(deck)

        assert round.deck == deck

        assert round.turns == []

        assert round.current_card() == card_1

        new_turn = round.take_turn('Juneau')

        assert isinstance(new_turn, Turn)

        assert new_turn.correct() == True

        assert round.turns == [new_turn]

        assert round.number_correct() == 1

        assert round.current_card() == card_2

        newer_turn = round.take_turn('12')

        assert len(round.turns) == 2
        assert (round.total_turns()) == 2

        assert newer_turn.correct() == False

        assert newer_turn.feedback() == 'Incorrect.'

        assert round.number_correct() == 1

        assert round.number_correct_by_category('Geography') == 1
        assert round.number_correct_by_category('STEM') == 0

        assert round.percent_correct() == 50.0

        assert round.percent_correct_by_category('Geography') == 100.0
        assert round.percent_correct_by_category('STEM') == 0.0

        assert round.current_card() == card_3
Exemplo n.º 27
0
 def test_take_turn(self):
     card_1 = Card("What is the capital of Alaska?", "Juneau", "Geography")
     card_2 = Card(
         "The Viking spacecraft sent back to Earth photographs and reports about the surface of which planet?",
         "Mars", "STEM")
     card_3 = Card(
         "Describe in words the exact direction that is 697.5° clockwise from due north?",
         "North north west", "STEM")
     cards = [card_1, card_2, card_3]
     deck = Deck(cards)
     round = Round(deck)
     new_turn = round.take_turn("Juneau")
     self.assertEqual(round.current_card(), card_2)
     self.assertIsInstance(new_turn, Turn)
     self.assertIs(new_turn.is_correct(), True)
Exemplo n.º 28
0
 def test_number_correct_by_category(self):
     card_1 = Card("What is the capital of Alaska?", "Juneau", "Geography")
     card_2 = Card(
         "The Viking spacecraft sent back to Earth photographs and reports about the surface of which planet?",
         "Mars", "STEM")
     card_3 = Card(
         "Describe in words the exact direction that is 697.5° clockwise from due north?",
         "North north west", "STEM")
     cards = [card_1, card_2, card_3]
     deck = Deck(cards)
     round = Round(deck)
     round.take_turn("Juneau")
     round.take_turn("Topeka")
     self.assertEqual(round.number_correct_by_category("Geography"), 1)
     self.assertEqual(round.number_correct_by_category("STEM"), 0)
Exemplo n.º 29
0
def swap(args):
    """Swap-create a new flashcard deck.

    Create a new flashcard deck by swapping questions and answers.

    Args:
        args (argparse.Namespace): command line arguments.
    """
    print('Swapping questions and answers from {} and saving to {}.'.format(
        args.deck, args.dest))
    src = Deck.load(args.deck)
    dest = Deck(src.name)
    for c in src:
        dest.add_card(Flashcard(c.answer, c.question))

    dest.save(args.dest)
Exemplo n.º 30
0
  def test_deck(self):
    card_1 = Card("What is the capital of Alaska?", "Juneau", 'Geography')
    card_2 = Card("What is the square root of 169?", "13", 'STEM')
    card_3 = Card("What is the power house of the freaking cell?", "Mitochondria", 'STEM')

    cards = [card_1, card_2, card_3]

    deck = Deck(cards)

    assert deck.cards == [card_1, card_2, card_3]

    assert deck.count() == 3

    assert deck.cards_in_category('Geography') == [card_1]
    assert deck.cards_in_category('STEM') == [card_2, card_3]
    assert deck.cards_in_category('pop culture') == []