Ejemplo n.º 1
0
def play():
    """

    :return:
    """
    bj_settings = Settings()
    pygame.display.set_caption("Blackjack")

    # create play button rect
    play_button = pygame.image.load('images/play.png')
    play_rect = play_button.get_rect()
    play_rect.topleft = (475, 100)

    # draw screen and add objects
    bj_settings.game_screen.fill(bj_settings.GREEN)
    bj_settings.game_screen.blit(play_button, (475, 50))

    pygame.display.update()

    # get events
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == MOUSEBUTTONDOWN:
                if play_rect.collidepoint(event.pos):
                    player = Hand()
                    dealer = Hand()
                    deck = Deck()
                    tb.take_bet(10, player, dealer, deck)
Ejemplo n.º 2
0
def play():
    """
    play button screen
    :return:
    """
    bj_settings = Settings()
    pygame.display.set_caption("Blackjack")

    # create play button rect
    play_button = pygame.image.load('images/play.png')
    play_rect = play_button.get_rect()
    play_rect.topleft = (475, 100)

    # TODO FIX
    pygame.display.set_icon(pygame.image.load('images/poker.png'))

    bj_settings.screen.fill(bj_settings.bg_color)
    bj_settings.screen.blit(play_button, (475, 50))

    pygame.display.update()

    while True:
        # main game loop
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                if play_rect.collidepoint(event.pos):
                    player = Hand()
                    dealer = Hand()
                    deck = Deck()
                    tb.take_bet(1000, player, dealer, deck)
Ejemplo n.º 3
0
def deck_reset_deck_test():
    '''
    Reverse the dealing_test(). Deals out the hands, then tests reset functions,
    making sure the deck resets back to a 52 card deck and hands back to 0
    '''
    d = Deck()
    h1 = Hand()
    h2 = Hand()
    for i in range(7):
        d.deal_to_hand(h1)
        d.deal_to_hand(h2)

    if d.card_count() == 38:
        d.reset_deck()
        if h1.card_count() == 7 and h2.card_count() == 7:
            for i in range(h1.card_count()):
                h1.remove_card1()
                h2.remove_card1()
            if h1.is_empty() and h2.is_empty():
                return True
            else:
                print('NOT EMPTY')
                return False
        else:
            print('Doesn\'t have 7 cards')
            return False
    else:
        print('Doesn\'t have 38 cards')
        return False
Ejemplo n.º 4
0
def test_next_move():
    """
    Starting from position 222?/000?/111? with player 0 to play, 
    and second choice 2, 0, 1, what is the best move? What is the
    best following move for player 2?
    """
    h0 = Hand()
    h0.known_cards = Counter({2: 3})
    h0.number_of_unknown_cards = 1
    h1 = Hand()
    h1.known_cards = Counter({0: 3})
    h1.number_of_unknown_cards = 1
    h2 = Hand()
    h2.known_cards = Counter({1: 3})
    h2.number_of_unknown_cards = 1
    cards = Cards(3)
    cards.hands = [h0, h1, h2]

    cards.show(0)

    player = CleverPlayer(1000, 1000, [[2], [0], [1]])

    history = set()
    depth = 1000
    other, suit, result, _ = player._evaluate_move(0, cards, history, depth)
    print(f"player 0 asks {other} for {suit} (result={result})")
    assert result == 1
    assert suit == 1
    assert other == 2

    # player 1 must say yes, as he has this card
    has = player.has_card(2, 0, 1, cards, history)
    assert has

    cards.transfer(suit, other, 0, False)
    winner = cards.test_winner(0)
    assert winner == -1  # nobody has won yet
    print()
    cards.show(1)

    # Now player 1 to move
    other, suit, result, _ = player._evaluate_move(1, cards, history, depth)
    print(f"player 1 asks {other} for {suit} (result={result})")
    assert result == 1
    assert suit == 0
    assert other == 2

    # player 2 must say no, otherwise 1 wins immediately
    has = player.has_card(2, 1, 0, cards, history)
    assert not has

    cards.no_transfer(suit, other, 1, False)
    winner = cards.test_winner(1)
    cards.show(2)
    assert winner == 1, "test_next_move: expecting a win for player 1"
    print("----------------")
    print()
Ejemplo n.º 5
0
def main():
    d = Deck()
    print 'hands:'
    c1 = raw_input('card1?')
    c2 = raw_input('card2?')
    c3 = raw_input('card3?')
    c4 = raw_input('card4?')
    card1 = Card(c1[0], c1[1])
    card2 = Card(c2[0], c2[1])
    card3 = Card(c3[0], c3[1])
    card4 = Card(c4[0], c4[1])
    ps = list()
    ps.append(Hand(card1, card2))
    ps.append(Hand(card3, card4))
    # ps = d.deal_players(N_PLAYERS)
    ps_str = ''
    for p in ps:
        ps_str += str(p) + ', '
    print ps_str

    wins = [0] * N_PLAYERS
    for loop in range(0, N_LOOP):
        d.reset()
        for p in ps:
            d.draw_card(p.card1)
            d.draw_card(p.card2)

        # print "community:"
        com = d.deal_community()
        com_str = ''
        for c in com:
            com_str += str(c) + ', '
        # print com_str

        ss = []
        for i in range(0, N_PLAYERS):
            ss.append(Holdem.showdown_hand_score(ps[i], com))
            # print ps[i], ss[i]
            # # if ss[i][0] == '9':
            # #     exit()
        # print 'best:'
        max_index, max_value = max(enumerate(ss), key=operator.itemgetter(1))
        # print max_index, max_value
        if ss[0] == ss[1]:
            wins[0] += 0.5
            wins[1] += 0.5
        else:
            wins[max_index] += 1  # OCOC what about ties?

    for i_wins in wins:
        print round(float(i_wins) / N_LOOP * 1000) / 10.0
Ejemplo n.º 6
0
def deck_deal_to_hand_test():
    '''
    Testing card dealing by dealing 7 cards to 2 separate Hands and
    checking the count of both the cards and hands are correct
    '''
    d = Deck()
    h1 = Hand()
    h2 = Hand()
    for i in range(7):
        d.deal_to_hand(h1)
        d.deal_to_hand(h2)
    if d.card_count() == 38:
        if h1.card_count() == 7 and h2.card_count() == 7:
            return True
Ejemplo n.º 7
0
 def test_hard_17(self):
     hand = Hand([
         Card(rank='A', suit='spade'),
         Card(rank='K', suit='spade'),
         Card(rank='6', suit='spade'),
     ])
     self.assertEqual(hand.score(), 17)
Ejemplo n.º 8
0
    def _parse_players(line: str, trump: TrumpType) -> List[Player]:
        """
        Helper for parse_file.
        Example: line is such -
            [Deal "E:AK872.KQJT.K.Q94 QT95.85.AQJ2.AK7 4.A962.96.J86532 J63.743.T87543.T"]
            And the result is list of Player object. First is Player(PositionEnum.E, Hand)
            such that Hand is list contain A, K, 8, 7, 2 faces of suit ♠, ect.
        :param line: line from PBN file, which starts with "[Deal "
        :return: list of 4 Player objects, sorted by (N, E, S, W)
        """
        player_str, all_hands_str = line.split(':')
        next_position = POSITIONS[PLAYERS_DICT[player_str]]

        players = [None, None, None, None]
        players_str = all_hands_str.split(
            ' ')  # spaces separate every two players
        for p in players_str:
            curr_position = next_position
            cards_str = p.split('.')  # dots separate every two suits
            cards = []
            for i, suit in enumerate(cards_str):
                for face in suit:
                    cards.append(
                        Card(face=face,
                             suit=SuitType(SUITS[i]).name,
                             trump=trump))
                    next_position = PLAYERS_CYCLE[curr_position]
            players[curr_position.value - 1] = Player(curr_position,
                                                      Hand(cards))

        return players
Ejemplo n.º 9
0
    def __init__(self, id=''):
        """Initialize player object"""

        self.hand = Hand()
        self.id = id
        self.turnsLeft = 0
        self.hasToBeat = False
Ejemplo n.º 10
0
 def test_hand_can_cast_itself_to_new_ranked(self):
     hand = Hand()
     hand.add_card(Card("C", "A"))
     hand.add_card(Card("D", "A"))
     new_hand = hand.to_ranked("C")
     for card in new_hand:
         assert isinstance(card, RankedCard)
Ejemplo n.º 11
0
 def test_bust(self):
     hand = Hand([
         Card(rank='K', suit='spade'),
         Card(rank='Q', suit='spade'),
         Card(rank='J', suit='spade'),
         Card(rank='A', suit='spade'),
     ])
     hand.is_bust()
Ejemplo n.º 12
0
def test_hand():
    hand = Hand()
    for i in range(2):
        for j in range(4):
            hand.cards.append(
                Card(Card.values[randint(0, 12)], Card.suits[randint(0, 3)]))
    hand.sort_hand()
    return hand
Ejemplo n.º 13
0
    def __init__(self, user):
        self.name = str(user)
        self.display_name = user.display_name

        self.inv = Inventory()

        self.decks = []
        self.hand = Hand()
Ejemplo n.º 14
0
def hand_card_count_test():
    d = Deck()
    h = Hand()
    d.deal_cards(h, 8)
    if h.card_count() == 8:
        return True
    else:
        return False
Ejemplo n.º 15
0
def deck_deal_cards_test():
    d = Deck()
    h = Hand()
    d.deal_cards(h, 10)
    if d.card_count() == 42 and h.card_count() == 10:
        return True
    else:
        return False
Ejemplo n.º 16
0
def hand_print_output():
    print('------: Creating Hand')
    d = Deck()
    d.shuffle_deck()
    h = Hand()
    d.deal_cards(h, 8)
    print(Fore.CYAN + 'OUTPUT: ', end='')
    print(Style.RESET_ALL, end='')
    hand_iter(h)
Ejemplo n.º 17
0
    def parse_cards(self):
        if hasattr(self, 'me') and self.me:
            key = ('hand', self.me)
            if key in self.sharedData:
                cards = self.sharedData.pop(key)
                self.hand = Hand(cards[0], cards[1])

        if 'table' in self.sharedData:
            self.table_cards = self.sharedData.pop('table')
Ejemplo n.º 18
0
 def test_really_hard_14(self):
     hand = Hand([
         Card(rank='A', suit='spade'),
         Card(rank='A', suit='club'),
         Card(rank='A', suit='heart'),
         Card(rank='A', suit='diamond'),
         Card(rank='K', suit='spade')
     ])
     self.assertEqual(hand.score(), 14)
Ejemplo n.º 19
0
    def __init__(self, id=''):
        """Initialize CPU object"""

        super().__init__(id)

        # self.id = "CPU" + str(id)
        self.hand = Hand()
        self.seed = random.seed()
        # 1 is no error, 0 is never slap
        self.errorSlapRate = 0.5  # random.uniform(0, 1) # TODO: not uniform
Ejemplo n.º 20
0
def play_round(deck):

    playerHand = Hand()
    dealerHand = Hand()

    playerHand.add_card(deck.deal())
    playerHand.add_card(deck.deal())

    dealerHand.add_card(deck.deal())
    dealerHand.add_card(deck.deal())

    print("The dealer has: ")
    dealerHand.show(partial=True)

    print("You have: ")
    playerHand.show()

    while True:
        action = input("Do you want to \n" + "1. [H]it \n" + "2. [S]tand \n")
        if action in ["1", "h", "H"]:
            playerHand.add_card(deck.deal())
            print("You have: ")
            playerHand.show()
            if playerHand.cur_value == GOAL_CONSTANT:
                win_statement("You", playerHand.cur_value)
                return playerHand, dealerHand, deck
            if playerHand.cur_value > GOAL_CONSTANT:
                lose_statement("You", playerHand.cur_value)
                return playerHand, dealerHand, deck

        if action in ['2', 'S', 's']:
            while dealerHand.cur_value < DEALER_CONSTANT:
                dealerHand.add_card(deck.deal())
                dealerHand.show(partial=True)
            if dealerHand.cur_value > GOAL_CONSTANT:
                print("The dealer has: ")
                dealerHand.show()
                lose_statement("Dealer", dealerHand.cur_value)

            return playerHand, dealerHand, deck
        else:
            print("Please make a selection using 1 or 2")
Ejemplo n.º 21
0
def hand_add_card_test():
    c = Card('A', 'd')
    h = Hand()
    h.add_card(c)
    if h.card_count() == 1:
        if h.cards[0].rank == 'A' and h.cards[0].suit == 'd':
            return True
        else:
            return False
    else:
        return False
Ejemplo n.º 22
0
def hand_remove_card1_test():
    c = Card('A', 'd')
    h = Hand()
    h.add_card(c)
    if h.card_count() == 1:
        h.remove_card1()
        if h.card_count() == 0:
            return True
        else:
            return False
    else:
        return False
Ejemplo n.º 23
0
def hand_is_empty_test():
    c = Card("A", 'd')
    h = Hand()
    if h.is_empty():
        h.add_card(c)
        h.remove_card1()
        if h.is_empty():
            return True
        else:
            return False
    else:
        return False
Ejemplo n.º 24
0
    def __init__(self, name, credits=100, hand=None, deck=None):
        self.name = name
        self.credits = credits

        if deck is None:
            self.deck = Deck()
        else:
            self.deck = deck

        if hand is None:
            self.hand = Hand(deck=self.deck)
        else:
            self.hand = hand
Ejemplo n.º 25
0
    def __init__(self, player_type: PlayerType, deck: Deck):
        self.life = Life()
        self.aura = Aura()
        self.flare = Flare()
        self.type = player_type
        self.vigor = Vigor(player_type)
        self.hand = Hand()
        self.trumps = Trumps(deck.trump_cards)
        self.stock = Cards(deck.normal_cards)
        self.downed = Cards()
        self.discarded = Cards()
        self.grants = Grants()
        self.extra_cards = Cards(deck.extra_cards)

        # 個別のメガミ関連
        self.umbrella = None
        self.gauge = None
        self.stratagem = None
        self.machine = None

        self.stock.shuffle()
Ejemplo n.º 26
0
 def test_add_too_many_cards_should_raise_valueerror(self):
     hand = Hand([Card("C", value) for value in Card.value_names])
     with pytest.raises(ValueError):
         hand.add_card(Card("D", "S"))
Ejemplo n.º 27
0
 def test_simple(self):
     hand = Hand([Card(rank='5', suit='spade')])
     self.assertEqual(hand.score(), 5)
Ejemplo n.º 28
0
    def run(self, input_socket):
        # Get a file-object for reading packets from the socket.
        # Using this ensures that you get exactly one packet per read.
        f_in = input_socket.makefile()

        debug = True

        hand = Hand()
        strength = 0
        board = Hand()
        pip = 0

        num_raises = 0

        pcklin = open('../../starting_hands/hand_strengths.pickle', 'r')
        hand_strengths = pickle.loads(pcklin.read())
        pcklin.close()

        opp_profile = PlayerProfile()

        while True:
            # Block until the engine sends us a packet.
            data = f_in.readline().strip()
            # If data is None, connection has closed.
            if not data:
                print "Gameover, engine disconnected."
                break
            if debug:
                print data

            words = data.split()

            if words[0] == "NEWGAME":
                my_name = words[1]
                opp_name = words[2]
                stack_size = int(words[3])
                bb = int(words[4])
                num_hands = int(words[5])
                time_bank = float(words[6])
            elif words[0] == "NEWHAND":
                hand_id = int(words[1])
                button = (words[2].lower() == 'true')
                hand = make_hand(' '.join(words[3:7]))
                board = Hand()
                my_bank = int(words[7])
                opp_bank = int(words[8])
                time_bank = float(words[9])
                pip = 0
                hand_strength_data = hand_strengths[hand.unique_id()]
                strength = float(hand_strength_data[0]) / hand_strength_data[1]
                num_raises = 0
                street = 0
                my_last_action = "CHECK"

                if (debug):
                    opp_profile.reset()
            elif words[0] == "HANDOVER":
                opp_profile.pretty_print()
                print
            elif words[0] == "GETACTION":
                pot_size = int(words[1])
                board_size = int(words[2])
                for i in range(len(board.cards), board_size):
                    board = board.add(make_card(words[3 + i]))
                curr_token = 3 + board_size
                num_last_actions = int(words[curr_token])
                last_actions_raw = words[curr_token + 1:curr_token +
                                         num_last_actions + 1]
                print("Last actions: {}".format(last_actions_raw))
                curr_token += num_last_actions + 1
                num_legal_actions = int(words[curr_token])
                legal_actions_raw = words[curr_token + 1:curr_token +
                                          num_legal_actions + 1]
                print("Legal actions: {}".format(legal_actions_raw))
                curr_token += num_legal_actions + 1
                timeBank = float(words[curr_token])

                can_check = False
                can_bet = False
                min_bet = 0
                max_bet = 0
                can_raise = False
                min_raise = 0
                max_raise = 0
                can_call = False
                to_call = 0

                for action in last_actions_raw:
                    print("processing action {}".format(action))
                    print("street: {}".format(street))
                    split_action = action.split(':')
                    if split_action[0] == 'DEAL':
                        # New card has been dealt, pip resets.
                        pip = 0
                        street += 1
                    elif split_action[-1] != my_name:
                        if split_action[0] == 'CHECK':
                            opp_profile.check_obs[street] += 1
                        elif split_action[0] == 'CALL':
                            opp_profile.call_obs[street] += 1
                            opp_profile.calls[street] += 1
                        elif split_action[0] == 'BET':
                            to_call = int(split_action[1])
                            opp_profile.check_obs[street] += 1
                            opp_profile.bets[street] += 1
                        elif split_action[0] == 'RAISE':
                            to_call = int(split_action[1])
                            opp_profile.call_obs[street] += 1
                            opp_profile.raises[street] += 1
                        elif split_action[0] == 'FOLD':
                            if my_last_action == 'CHECK':
                                opp_profile.check_obs[street] += 1
                            else:
                                opp_profile.call_obs[street] += 1
                        elif split_action[0] == 'POST':
                            to_call = 2
                    else:
                        my_last_action = split_action[0]
                        if split_action[0] == 'POST':
                            pip = int(split_action[1])

                for action in legal_actions_raw:
                    split_action = action.split(':')
                    if split_action[0] == 'CHECK':
                        can_check = True
                    elif split_action[0] == 'BET':
                        can_bet = True
                        min_bet = int(split_action[1])
                        max_bet = int(split_action[2])
                    elif split_action[0] == 'CALL':
                        can_call = True
                    elif split_action[0] == 'RAISE':
                        can_raise = True
                        min_raise = int(split_action[1])
                        max_raise = int(split_action[2])

                output = None

                if board_size == 0:
                    # Pre-flop strategy #
                    print("My hand strength is {}".format(strength))
                    if can_check:
                        if strength > 0.6:
                            # Premium hand #
                            if max_bet > 0:
                                output = "BET:{}".format(max_bet)
                            elif max_raise > 0:
                                output = "RAISE:{}".format(max_raise)
                            else:
                                output = "CHECK"
                        elif strength > 0.53:
                            # Good hand #
                            if max_bet > 0:
                                output = "BET:{}".format(
                                    (min_bet + max_bet) / 2)
                            elif max_raise > 0:
                                output = "RAISE:{}".format(
                                    (min_raise + max_raise) / 2)
                            else:
                                output = "CHECK"
                        else:
                            output = "CHECK"
                    else:
                        if strength > 0.7 and max_raise > 0:
                            output = "RAISE:{}".format(max_raise)
                        elif strength > 0.65 and max_raise > 0 and num_raises < 3:
                            output = "RAISE:{}".format(max_raise)
                        elif strength > 0.58 and max_raise > 0 and num_raises < 2:
                            output = "RAISE:{}".format(max_raise)
                        elif strength > 0.55:
                            output = "CALL"
                        else:
                            output = "FOLD"

                else:
                    # Post-flop strategy #
                    strength = relative_strength(hand, board)
                    print("My relative strength is {}".format(strength))

                    if can_check:
                        if max_bet == 0:
                            output = "CHECK"
                        else:
                            if strength > 0.9:
                                # Uber hand #
                                output = "BET:{}".format(max_bet)
                            elif strength > 0.75:
                                # Strong hand#
                                output = "BET:{}".format(
                                    (max_bet + min_bet) / 2)
                            else:
                                output = "CHECK"
                    elif num_raises == 0:
                        if strength > 0.95:
                            if max_raise > 0:
                                output = "RAISE:{}".format(max_raise)
                            else:
                                output = "CALL"
                        elif strength > 0.8:
                            raise_amount = int(pot_size * strength / 1.5)
                            if max_raise > 0 and raise_amount >= min_raise:
                                output = "RAISE:{}".format(
                                    min(max_raise, raise_amount))
                            else:
                                call_amount = int(pot_size * strength)
                                if to_call < call_amount:
                                    output = "CALL"
                                else:
                                    output = "FOLD"
                        elif strength > 0.65:
                            call_amount = int(pot_size * strength / 1.5)
                            if to_call < call_amount:
                                output = "CALL"
                            else:
                                output = "FOLD"
                        else:
                            output = "FOLD"
                    else:
                        if strength > 0.96 + 0.01 * num_raises:
                            if max_raise > 0:
                                output = "RAISE:{}".format(max_raise)
                            else:
                                output = "CALL"
                        elif strength > 0.85:
                            output = "CALL"
                        else:
                            output = "FOLD"

                if (debug):
                    print("My hand: {}".format(hand))
                    print("The board: {}".format(board))
                    print("my name: {}".format(my_name))
                    if can_check:
                        print("I can CHECK.")
                    if can_call:
                        print("I can CALL {}".format(to_call))
                    if can_bet:
                        print("I can BET {} to {}".format(min_bet, max_bet))
                    if can_raise:
                        print("I can RAISE {} to {}".format(
                            min_raise, max_raise))
                    if pip > 0:
                        print("I have {} in the pot".format(pip))
                    print("I choose to {}".format(output.strip()))

                # Calculate pip (how much money I have in the pot)
                split_output = output.split(':')
                if split_output[0] == 'RAISE' or split_output[0] == 'BET':
                    pip = int(split_output[1])

                # Add newline to output for the engine
                if (output[-1] != '\n'):
                    s.send("{}\n".format(output))
                else:
                    s.send(output)

                if (debug):
                    print

            elif words[0] == "REQUESTKEYVALUES":
                # At the end, the engine will allow your bot save key/value pairs.
                # Send FINISH to indicate you're done.
                s.send("FINISH\n")
        # Clean up the socket.
        s.close()
Ejemplo n.º 29
0
 def __init__(self, is_dealer=False):
     self.type = 'dealer' if is_dealer else 'player'
     self.hand = Hand()
Ejemplo n.º 30
0
 def test_prints_correctly(self):
     hand = Hand()
     hand.add_card(Card("C", "A"))
     hand.add_card(Card("D", "A"))
     regex = regex_builder("Hand")
     assert regex.match(str(hand))