Ejemplo n.º 1
0
    def test_init(self, hand, make_holding):
        holding_no_cards = make_holding(player_id=hand.dealer.id,
                                        hand_id=hand.id)
        assert holding_no_cards.id > 0
        assert len(holding_no_cards.cards) == 0
        assert len(Card.query.all()) == 0

        holding_cards_ints = make_holding(
            player_id=hand.dealer.id,
            hand_id=hand.id,
            cards=[PokerCard.new('As'),
                   PokerCard.new('Ac')])
        assert holding_cards_ints.id > 0
        assert len(holding_cards_ints.cards) == 2
        assert len(Card.query.all()) == 2

        holding_cards_objs = make_holding(player_id=hand.dealer.id,
                                          hand_id=hand.id,
                                          cards=Card.query.all())
        assert holding_cards_objs.id > 0
        assert len(holding_cards_objs.cards) == 2
        assert len(Card.query.all()) == 2

        with pytest.raises(InvalidCardError):
            make_holding(player_id=hand.dealer.id,
                         hand_id=hand.id,
                         cards=["invalid card"])

        with pytest.raises(sqlalchemy.exc.IntegrityError):
            make_holding(player_id=None, is_board=False, hand_id=hand.id)
Ejemplo n.º 2
0
def get_score(hand_cards, board_cards):

    board = []
    for x in board_cards:
        x = x.encode('ascii', 'ignore')
        c = Card.new('{0}{1}'.format(x[0], x[1].lower()))
        board.append(c)

    hand = []
    for x in hand_cards:
        x = x.encode('ascii', 'ignore')
        c = Card.new('{0}{1}'.format(x[0], x[1].lower()))
        hand.append(c)

    score_min = 9999999
    if (len(hand) + len(board) <= 5):
        return score_min
    else:

        for board_five_match in combinations(board, 5 - len(hand)):
            evaluator = Evaluator()
            score = evaluator.evaluate(tuple(board_five_match), tuple(hand))
            if (score < score_min):
                score_min = score
        return score_min
Ejemplo n.º 3
0
 def test_codes_property(self, hand, make_holding):
     holding = make_holding(
         player_id=hand.dealer.id,
         hand_id=hand.id,
         cards=[PokerCard.new('As'),
                PokerCard.new('Ac')])
     assert holding.codes == [PokerCard.new('As'), PokerCard.new('Ac')]
Ejemplo n.º 4
0
def hand_strength(hand_cards, community):
    if len(community) == 0:
        hand_cards.sort(key=order_cards)
        raw_score = two_card_lookup[" ".join(hand_cards)]
        scaled_score = (1325 - raw_score) * 2.9562264151 + 3545
        return scaled_score

    elif len(community) == 3 and len(hand_cards) == 0:

        community.sort(key=order_cards)
        community = " ".join(community)
        community = transform_for_lookup(community)
        raw_score = three_card_lookup[community]
        scaled_score = (22100 - raw_score) * 0.2618552036 + 1675

        return scaled_score
    elif len(community) == 4 and len(hand_cards) == 0:

        community.sort(key=order_cards)
        community = " ".join(community)
        community = transform_for_lookup(community)
        raw_score = four_card_lookup[community]
        scaled_score = (270725 - raw_score) * 0.02756526525 + 22
        return four_card_lookup[community]
    else:
        deuces_cards = [Card.new(card) for card in hand_cards]
        deuces_community = [Card.new(card) for card in community]
        return evaluator.evaluate(deuces_cards, deuces_community)
Ejemplo n.º 5
0
    def evaluate_showdown_probabilities(self, hand, board, nsim):
        board_cards = [Card.new(j) for j in board]
        hand_cards = [Card.new(j) for j in hand]
        cards_in_play = cp.copy(board_cards)
        cards_in_play.extend(hand_cards)

        board_cards_to_draw = (5 - len(board))
        hand_cards_to_draw = (2 - len(hand))
        villain_cards_to_draw = 2
        num_cards_to_draw = board_cards_to_draw + hand_cards_to_draw + villain_cards_to_draw

        deck = de.Deck()
        draw_deck = list(set(deck.cards) - set(cards_in_play))
        nwins = 0.0
        for i in range(nsim):
            rest_of_cards = sample(draw_deck, num_cards_to_draw)
            board_sim = cp.copy(board_cards)
            hand_sim = cp.copy(hand_cards)

            board_sim.extend(rest_of_cards[0:board_cards_to_draw])
            hand_sim.extend(
                rest_of_cards[board_cards_to_draw:(board_cards_to_draw +
                                                   hand_cards_to_draw)])
            villain_hand = rest_of_cards[(board_cards_to_draw +
                                          hand_cards_to_draw):]

            villain_rank = self.card_evaluator.evaluate(
                board_sim, villain_hand)
            hero_rank = self.card_evaluator.evaluate(board_sim, hand_sim)

            nwins += hero_rank < villain_rank

        win_pct = nwins / nsim
        return win_pct
Ejemplo n.º 6
0
def get_action(board_cards=[],hand_cards=['AH', 'KD']):
    if(len(board_cards)+len(hand_cards)==0):
        return 'error'
    
    board = []
    for x in board_cards:
        c = Card.new('{0}{1}'.format(x[0], x[1].lower()))
        board.append(c)
    
    hand = []
    for x in hand_cards:
        c = Card.new('{0}{1}'.format(x[0], x[1].lower()))
        hand.append(c)
    
    score = get_score_by_simulate(hand,board)
    print(score)
    BAD_SCORE = 7000
    BEST_SCORE = 1000
    BETTER_SCORE = 2000
    GOOD_SCORE = 4000
    
    if(len(hand)+len(board)>5 and score>BAD_SCORE):
        action = 'fold'
    else:
        if(score<=BEST_SCORE):
            action = 'all_in'
        elif(score<=BETTER_SCORE):
            action = 'raise_max'
        elif(score>BETTER_SCORE and score<=GOOD_SCORE):
            action = 'raise_min'
        else:
            action = 'call'
    
    return action
Ejemplo n.º 7
0
def is_good(board_cards=[], hand_cards=['AH', 'KD']):
    if (len(board_cards) + len(hand_cards) == 0):
        return False

    board = []
    for x in board_cards:
        c = Card.new('{0}{1}'.format(x[0], x[1].lower()))
        board.append(c)

    hand = []
    for x in hand_cards:
        c = Card.new('{0}{1}'.format(x[0], x[1].lower()))
        hand.append(c)

    evaluator = Evaluator()
    deck = Deck()
    random_cards = deck.draw(5 - len(board) - len(hand))
    score = evaluator.evaluate(board + random_cards, hand)
    rank_class = evaluator.get_rank_class(score)

    print_cards(board + random_cards + hand, rank_class)

    if (rank_class < 9):
        return True
    return False
Ejemplo n.º 8
0
 def get_card_suite(board, hand):
     if not (all(hand) and all(board)):
         return -1
     elif '-' in hand or '-' in board:
         return -1
     board = [deucesCard.new(c) for c in board]
     hand = [deucesCard.new(c) for c in hand]
     return evaluator.evaluate(board, hand)
Ejemplo n.º 9
0
def test_front_lookup_trips():
    weakest = [Card.new(x) for x in ['Kh', 'Ks', 'Kd', 'Ad', 'Qh']]
    middle = [Card.new(x) for x in ['Ah', 'As', 'Ad']]
    strongest = [Card.new(x) for x in ['Ah', 'As', 'Ad', '2d', '3d']]

    assert evaluator.evaluate(strongest, []) < \
        evaluator.evaluate(middle, []) < \
        evaluator.evaluate(weakest, [])
Ejemplo n.º 10
0
def test_front_lookup_aces():
    strongest = [Card.new(x) for x in ['Ah', 'As', '6d']]
    middle = [Card.new(x) for x in ['Ah', 'As', '5d', '4d', '3d']]
    weakest = [Card.new(x) for x in ['Ah', 'As', '5d']]

    assert evaluator.evaluate(strongest, []) < \
        evaluator.evaluate(middle, []) < \
        evaluator.evaluate(weakest, [])
Ejemplo n.º 11
0
def test_get_hands():
    '''Test that we convert a raw line of input cards into 2 hands of Cards'''
    raw_cards = '8C TS KC 9H 4S 7D 2S 5D 3S AC'
    expected_cards = (
        [Card.new('8c'), Card.new('Ts'), Card.new('Kc'), Card.new('9h'), Card.new('4s')],
        [Card.new('7d'), Card.new('2s'), Card.new('5d'), Card.new('3s'), Card.new('Ac')],
    )
    assert get_hands(raw_cards) == expected_cards
Ejemplo n.º 12
0
    def __init__(self):
        
        card = {}
        deck = []
        ranked_hands = []

        n = 0
        for i in ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A']:
            for j in ['s', 'h', 'c', 'd']:
                card[i+j] = Card.new(i+j)
                deck.append(Card.new(i+j))
                n += 1

        for hand in combinations([card['As'], card['Ad'], card['Ac'], card['Ah']], 2):
            ranked_hands.append(set(hand))

        for hand in combinations([card['Ks'], card['Kd'], card['Kc'], card['Kh']], 2):
            ranked_hands.append(set(hand))

        for hand in combinations([card['Qs'], card['Qd'], card['Qc'], card['Qh']], 2):
            ranked_hands.append(set(hand))

        ranked_hands.append(set((card['As'], card['Ks'])))
        ranked_hands.append(set((card['Ad'], card['Kd'])))
        ranked_hands.append(set((card['Ac'], card['Kc'])))
        ranked_hands.append(set((card['Ah'], card['Kh'])))

        for hand in combinations([card['Js'], card['Jd'], card['Jc'], card['Jh']], 2):
            ranked_hands.append(set(hand))

        ranked_hands.append(set((card['As'], card['Qs'])))
        ranked_hands.append(set((card['Ad'], card['Qd'])))
        ranked_hands.append(set((card['Ac'], card['Qc'])))
        ranked_hands.append(set((card['Ah'], card['Qh'])))

        ranked_hands.append(set((card['Ks'], card['Qs'])))
        ranked_hands.append(set((card['Kd'], card['Qd'])))
        ranked_hands.append(set((card['Kc'], card['Qc'])))
        ranked_hands.append(set((card['Kh'], card['Qh'])))

        ranked_hands.append(set((card['As'], card['Js'])))
        ranked_hands.append(set((card['Ad'], card['Jd'])))
        ranked_hands.append(set((card['Ac'], card['Jc'])))
        ranked_hands.append(set((card['Ah'], card['Jh'])))


        ranked_hands.append(set((card['Ks'], card['Js'])))
        ranked_hands.append(set((card['Kd'], card['Jd'])))
        ranked_hands.append(set((card['Kc'], card['Jc'])))
        ranked_hands.append(set((card['Kh'], card['Jh'])))

        for hand in combinations([card['Ts'], card['Td'], card['Tc'], card['Th']], 2):
            ranked_hands.append(set(hand))

        self.ranked_hands = ranked_hands
        self.card_dict = card
        self.deck = deck
        self.evaluator = Evaluator()
Ejemplo n.º 13
0
 def __init__(self, new_deck, player_hand_string, flop=False):
     self.my_hand = [Card.new(i) for i in player_hand_string]
     self.deck = new_deck
     self.deck.cards.remove(self.my_hand[0])
     self.deck.cards.remove(self.my_hand[1])
     if flop:
         for new_card in flop:
             self.board_cards.append(Card.new(new_card))
             self.deck.cards.remove(self.board_cards[-1])
Ejemplo n.º 14
0
def holding(hand):
    return Holding.create(id=1,
                          player_id=hand.dealer_id,
                          hand_id=hand.id,
                          is_board=False,
                          active=True,
                          created_utc=datetime.datetime(2019, 7, 31),
                          cards=[PokerCard.new('As'),
                                 PokerCard.new('Ac')])
Ejemplo n.º 15
0
def test_front_lookup_very_low():
    weakest = [Card.new(x) for x in ['2h', '3s', '4d']]
    middle = [Card.new(x) for x in ['2h', '3s', '5d']]
    stronger = [Card.new(x) for x in ['2h', '4s', '5d']]
    strongest = [Card.new(x) for x in ['2h', '3s', '7d']]

    assert evaluator.evaluate(strongest, []) < \
        evaluator.evaluate(stronger, []) < \
        evaluator.evaluate(middle, []) < \
        evaluator.evaluate(weakest, [])
Ejemplo n.º 16
0
 def getHandStrength(self):
     evaluator = Evaluator()
     score = evaluator.evaluate(
         [Card.new(str(self.hand[0])),
          Card.new(str(self.hand[1]))],
         [Card.new('Td'), Card.new('4c'),
          Card.new('9s')])
     rank = evaluator.get_rank_class(score)
     print "Score:", score, "Percentile:", round(
         1 - float(score) / float(7254),
         2), "Class:", evaluator.class_to_string(rank)
Ejemplo n.º 17
0
def get_hand_strength(hole_cards, board_cards):
    """
    Takes in hole cards and board cards and returns the hand strength.
    """
    evaluator=Evaluator()
    hole=[Card.new(hole_cards[0]), Card.new(hole_cards[1])]
    board=[]
    for card in board_cards:
        board.append(Card.new(card))
    strength=(7643-evaluator.evaluate(hole, board))/float(7642)
    return strength
Ejemplo n.º 18
0
 def get_deuces_hand_strength(self, cards, board_cards):
     """
     Gets the effective hand strength of your cards at any stage of the game using the deuces library.
     """
     evaluator = Evaluator()
     hole = [Card.new(cards[0]), Card.new(cards[1])
             ]  #Turns cards and board cards into deuces.Card objects
     board = []
     for card in board_cards:
         board.append(Card.new(card))
     return (7643 - evaluator.evaluate(hole, board)) / float(
         7642)  #Turns the hand strength into a decimal in the range of 0-1
Ejemplo n.º 19
0
	def set_player_hand(self, first_card_name, second_card_name):
		if not self._check_non_empty_string(first_card_name):
			raise ValueError('First card name cannot be empty')
			return
			
		if not self._check_non_empty_string(second_card_name):
			raise ValueError('Second card name cannot be empty')
			return
			
		self.hand = [
			Card.new( first_card_name.strip() ),
			Card.new( second_card_name.strip() )
			]
Ejemplo n.º 20
0
    def encode(self, plyr_board, oppo_board, current_card,
               plyr_cards, game_over, score):
        current_card = [Card.new(current_card)]
        plyr_cards = [Card.new(x) for x in plyr_cards]

        plyr_front_ranks = self.cards_to_ranks(plyr_board.front.cards, 3)
        plyr_mid_ranks = self.cards_to_ranks(plyr_board.mid.cards, 5)
        plyr_back_ranks = self.cards_to_ranks(plyr_board.back.cards, 5)

        oppo_front_ranks = self.cards_to_ranks(plyr_board.front.cards, 3)
        oppo_mid_ranks = self.cards_to_ranks(plyr_board.mid.cards, 5)
        oppo_back_ranks = self.cards_to_ranks(plyr_board.back.cards, 5)

        plyr_front_suits = self.cards_to_suits(plyr_board.front.cards)
        plyr_mid_suits = self.cards_to_suits(plyr_board.mid.cards)
        plyr_back_suits = self.cards_to_suits(plyr_board.back.cards)

        oppo_front_suits = self.cards_to_suits(plyr_board.front.cards)
        oppo_mid_suits = self.cards_to_suits(plyr_board.mid.cards)
        oppo_back_suits = self.cards_to_suits(plyr_board.back.cards)

        current_card_rank = self.cards_to_ranks(current_card, 1)
        current_card_suit = self.cards_to_suits(current_card)

        remaining_card_ranks = self.cards_to_ranks(plyr_cards, 4)
        remaining_card_suits = self.cards_to_suits(plyr_cards)

        free_streets = np.array(plyr_board.get_free_streets())
        free_streets_std = (free_streets - 0.5) * 2  # Hacky "standardisation"

        encoding = np.hstack([
            plyr_front_ranks,
            plyr_mid_ranks,
            plyr_back_ranks,
            plyr_front_suits,
            plyr_mid_suits,
            plyr_back_suits,
            oppo_front_ranks,
            oppo_mid_ranks,
            oppo_back_ranks,
            oppo_front_suits,
            oppo_mid_suits,
            oppo_back_suits,
            current_card_rank,
            current_card_suit,
            remaining_card_ranks,
            remaining_card_suits,
            free_streets_std
        ])

        return encoding
Ejemplo n.º 21
0
    def test_cards_relationship(self, hand, make_holding, make_card):
        holding = make_holding(player_id=hand.dealer.id, hand_id=hand.id)
        card1 = make_card(code=PokerCard.new('As'), rank='A', suit='s')
        card2 = make_card(code=PokerCard.new('Ac'), rank='A', suit='c')

        assert len(holding.cards) == 0

        holding.cards.append(card1)
        assert len(holding.cards) == 1
        assert holding.cards[0] is card1

        holding.cards.append(card2)
        assert len(holding.cards) == 2
        assert holding.cards[1] is card2
Ejemplo n.º 22
0
def getRank(num_player,card_player,board_player):
	playerrank=[[]for row in range(num_player)]
	hand=[]*2
	board=[]*5
	for i in range(num_player):
		for t in range(len(card_player[i])):
			hand=[Card.new(card_player[i][t][0]),Card.new(card_player[i][t][1])]
			evaluator=Evaluator()
			board=[Card.new(board_player[i][0]),Card.new(board_player[i][1]),Card.new(board_player[i][2]),Card.new(board_player[i][3]),Card.new(board_player[i][4])]
			rank=evaluator.evaluate(board,hand)
			playerrank[i].append(rank)
			print hand,rank,playerrank[i]
	print playerrank
	return playerrank
Ejemplo n.º 23
0
def get_strength_difference(hole_cards_1, hole_cards_2, board_cards):
    """
    Takes in the hole cards and the board cards and returns the difference in hand strength between player one and
    player two.
    """
    evaluator=Evaluator()
    hole_1=[Card.new(hole_cards_1[0]), Card.new(hole_cards_1[1])]
    hole_2=[Card.new(hole_cards_2[0]), Card.new(hole_cards_2[1])]
    board=[]
    for card in board_cards:
        board.append(Card.new(card))
    strength_1=(7643-evaluator.evaluate(hole_1, board))/float(7642)
    strength_2=(7643-evaluator.evaluate(hole_2, board))/float(7642)
    return strength_1-strength_2
Ejemplo n.º 24
0
def test_front_royalties():
    front = [Card.new(x) for x in ['2h', '2c', '3d']]
    assert RoyaltyCalculator.score_front_royalties(front) == 0

    front = [Card.new(x) for x in ['6h', '6c', '3d']]
    assert RoyaltyCalculator.score_front_royalties(front) == 1

    front = [Card.new(x) for x in ['Ah', 'Ac', '3d']]
    assert RoyaltyCalculator.score_front_royalties(front) == 9

    front = [Card.new(x) for x in ['2h', '2c', '2d']]
    assert RoyaltyCalculator.score_front_royalties(front) == 10

    front = [Card.new(x) for x in ['Ah', 'Ac', 'Ad']]
    assert RoyaltyCalculator.score_front_royalties(front) == 22
Ejemplo n.º 25
0
def test_front_royalties():
    front = [Card.new(x) for x in ['2h', '2c', '3d']]
    assert RoyaltyCalculator.score_front_royalties(front) == 0

    front = [Card.new(x) for x in ['6h', '6c', '3d']]
    assert RoyaltyCalculator.score_front_royalties(front) == 1

    front = [Card.new(x) for x in ['Ah', 'Ac', '3d']]
    assert RoyaltyCalculator.score_front_royalties(front) == 9

    front = [Card.new(x) for x in ['2h', '2c', '2d']]
    assert RoyaltyCalculator.score_front_royalties(front) == 10

    front = [Card.new(x) for x in ['Ah', 'Ac', 'Ad']]
    assert RoyaltyCalculator.score_front_royalties(front) == 22
Ejemplo n.º 26
0
 def add(self, new_card):
     nc = Card.new(new_card)
     if nc in self.deck.cards:
         self.board_cards.append(nc)
         self.deck.cards.remove(self.board_cards[-1])
     else:
         raise Exception("Found repeated card: " + str(new_card))
Ejemplo n.º 27
0
 def get_format_cards(self, cards):
     allcards = []
     for card in cards:
         card = str(card)
         newcard= Card.new(str(card[0].upper() +card[1].lower()))
         allcards.append(newcard)
     return allcards
Ejemplo n.º 28
0
    def get_bet(self, data):
        roundnum = data['game']['roundName']
        players = data['game']['players']
        chips = data['self']['chips']
        hands = data['self']['cards']
        
        self.raise_count = data['game']['raiseCount']
        self.my_step = data['game']['betCount']
        self.my_chips = chips
        self.my_name = data['self']['playerName'] 

        self.number_players = len(players)
        self.my_call_bet = data['self']['minBet']
        self.my_raise_bet = self.my_call_bet * 2
        self.hole = []
        for card in (hands):
            card = convert_card_str(card)
            card = Card.new(card)
            self.hole.append(card)
        
        print ("...roundnum: ", format(roundnum), " -> force bet")
        print ('...my_call_bet:', format(self.my_call_bet), "my_raise_bet", format(self.my_raise_bet), "my_chips", format(self.my_chips), "table bet", format(self.table_bet))
        
        Card.print_pretty_cards (self.hole)
        Card.print_pretty_cards (self.board)
 
        if roundnum == 'Deal' and self.my_step == 0:
            print ("...Force to bet!")
            action = 'call'
            amount = self.my_call_bet
            self.my_step += 1
            self.total_bet += amount
            return action, amount
        else:
            return self.get_action(data)
Ejemplo n.º 29
0
def get_probabilities(card_1, card_2, other_players, trials=10000):
    """
    for a given preflop hand, compute the probabilities of winning or tying.
    Note that we've got a very important design decision here: we could obtain
    the probabilities in a combinatorial fashion -- it's possible to mathematically
    reason to obtain the exact probability of winning or tying, but this seems
    quite involved. It's much easier to use a Monte Carlo simulation to approximate
    the probabilities. With a large number of trials (e.g. 10k or 100k) the
    approximations should be sufficiently close to the theoretical "true" values
    for all practical intents and purposes. 
    """
    deck = map(lambda (x, y): Card.new(y + x), list(product(suits, ranks)))
    wins = 0
    ties = 0
    deck.remove(card_1)
    deck.remove(card_2)
    for i in range(trials):
        # Randomly shuffling the deck and slicing the first few cards to get hands
        # seems computationally cheaper than using random.choice to select subsets as hands
        shuffle(deck)
        shared_cards = deck[:5]
        # hands held by other players
        other_hands = [
            deck[5 + (2 * x):7 + (2 * x)] for x in range(other_players)
        ]
        result = eval_table([card_1, card_2], shared_cards, other_hands)
        if result == WIN:
            wins += 1
        elif result == TIE:
            ties += 1
    return wins / float(trials), ties / float(trials)
Ejemplo n.º 30
0
 def cardsRank(self, cards):
     evaCards = []
     for card in cards:
         evaCards.append(Card.new(self.ePoint[self.getPointOf(card)] + \
                                  self.eColor[self.getColorOf(card)]))
     rank = self.evaluator.evaluate(evaCards)
     return rank
Ejemplo n.º 31
0
def get_probabilities(card_1, card_2, other_players, trials=10000):
    """
    for a given preflop hand, compute the probabilities of winning or tying.
    Note that we've got a very important design decision here: we could obtain
    the probabilities in a combinatorial fashion -- it's possible to mathematically
    reason to obtain the exact probability of winning or tying, but this seems
    quite involved. It's much easier to use a Monte Carlo simulation to approximate
    the probabilities. With a large number of trials (e.g. 10k or 100k) the
    approximations should be sufficiently close to the theoretical "true" values
    for all practical intents and purposes. 
    """
    deck = map(lambda (x,y): Card.new(y+x), list(product(suits,ranks)))
    wins = 0
    ties = 0
    deck.remove(card_1)
    deck.remove(card_2)
    for i in range(trials):
        # Randomly shuffling the deck and slicing the first few cards to get hands
        # seems computationally cheaper than using random.choice to select subsets as hands
        shuffle(deck)
        shared_cards = deck[:5]
        # hands held by other players
        other_hands = [deck[5+(2*x):7+(2*x)] for x in range(other_players)]
        result = eval_table([card_1, card_2], shared_cards, other_hands)
        if result == WIN:
            wins +=1
        elif result == TIE:
            ties +=1
    return wins/float(trials), ties/float(trials)
Ejemplo n.º 32
0
    def __init__(self, cards, board, evaluator=None):
        """Initialize new poker hand from a card array and an evaluator."""
        assert len(cards) == 2
        assert len(board) in [3, 4, 5]

        # checking there are 5, 6 or 7 unique cards
        cardset = set(list(cards) + list(board))
        assert len(cardset) == len(cards) + len(board)

        if isinstance(cards[0], str):
            self._cards = [Card.new(card_str) for card_str in cards]
        else:
            self._cards = list(cards)
        self._cards = sorted(self._cards)

        #TODO allow for Flop object to be passed

        self._board = Flop(board)

        if evaluator:
            self.ev = evaluator
        else:
            ev = Evaluator()
            self.ev = ev

        self.rank = self.ev.evaluate(self._cards, self._board._cards)
        self.rank_class = self.ev.get_rank_class(self.rank)

        self._hand_ranks = sorted(
            [Card.get_rank_int(card) for card in self._cards])
        self._board_ranks = self._board.ranks
Ejemplo n.º 33
0
def takeAction(player, action, data):
    global current_md5
    global hand
    global board

    # print(action)
    # print(data)

    if action == "__new_peer":
        # calcuate md5 by player name
        # current_md5 = "70be3acc4a99a780e1b405e1ff7971c5"
        current_md5 = hashlib.md5(player).hexdigest()
        print('MD5 of Current User: '******'playerName']:
                card_list = player_info['cards']
                for card in card_list:
                    hand.append(Card.new(convertToDeucesCard(card)))
                print("****** My hand cards ******")
                Card.print_pretty_cards(hand)
                print("***************************")
    elif action == "__bet":
        takeActionByDeuces(player, action, data)
    elif action == "__action":
        if len(data['game']['board']) == 0:
            takeActionByHand(player, action, data)
        else:
            takeActionByDeuces(player, action, data)
Ejemplo n.º 34
0
 def cardsRank(self, cards):
     evaCards = []
     for card in cards:
         evaCards.append(Card.new(self.ePoint[self.getPointOf(card)] + \
                                  self.eColor[self.getColorOf(card)]))
     rank = self.evaluator.evaluate(evaCards)
     return rank
Ejemplo n.º 35
0
def get_all_card():
    output = []
    tbl = get_all_cardstr()
    
    for c in tbl:
        output.append(Card.new(c))
        
    return output
Ejemplo n.º 36
0
def buildDeck(cards):
    deck = list();
    for value in Card.STR_RANKS:
        for suit in 'shdc':
            if value+suit not in cards:
                deck.append(Card.new(value+suit));
    deck = shuffleDeck(deck);
    return deck;
Ejemplo n.º 37
0
def parse_cards(cardstr):
    #have to replace 10 with T for deuces
    cardstr = cardstr.replace('10', 'T')
    cardlist = cardstr.split(' ')
    hand = []
    for card in cardlist:
        dcard = Card.new(card)
        hand.append(dcard)
    return hand
Ejemplo n.º 38
0
    def evaluate_hands(self):
        agent_hands = []
        if self.in_game_count > 1:
            evaluator = Evaluator()
            board = []
            scores = []
            hand_types = []

            for c in self.community_cards:
                board.append(Card.new(c))
            for i in range(0, len(self.agents)):
                agent = self.agents[i]
                agent_hand = []

                for c in agent.hand:
                    agent_hand.append(Card.new(c))

                if self.in_game[i]:
                    agent_hands.append(agent.hand)
                    agent_score = evaluator.evaluate(board, agent_hand)
                    agent_hand_type = evaluator.class_to_string(evaluator.get_rank_class(agent_score))
                    scores.append(agent_score)
                    hand_types.append(agent_hand_type)
                else:
                    agent_hands += [None]
                    scores.append(9999999999999)
            
            lowest_rank = scores[0]
            winner = 0
            for i in range(0, len(self.agents)):
                if lowest_rank > scores[i]:
                    lowest_rank = scores[i]
                    winner = i
                    
            return (winner, agent_hands)
        else: # Only 1 remaining player
            winner = 0
            for i in range(0, len(self.agents)):
                if (self.in_game[i]):
                    winner = i
                    break
            return winner, agent_hands
Ejemplo n.º 39
0
def get_lowest_unpairing_card(hand):
    """Add the worst possible card to an incomplete hand. Something
    that cannot pair up or make a flush or make a straight."""
    existing_ranks = set([Card.get_rank_int(x) for x in hand])
    remaining_ranks = list(set(range(12)) - existing_ranks)
    selected_rank = remaining_ranks[0]

    would_be_hand = hand + [Card.new(Card.STR_RANKS[selected_rank] + 'h')]
    if is_straight(would_be_hand):
        selected_rank = remaining_ranks[1]    # Don't make a straight

    selected_rank_str = Card.STR_RANKS[selected_rank]

    last_suit = Card.get_suit_int(hand[-1])
    last_suit_index = [1, 2, 4, 8].index(last_suit)
    selected_suit = [1, 2, 4, 8][(last_suit_index + 1) % 4]
    selected_suit_str = Card.INT_SUIT_TO_CHAR_SUIT[selected_suit]

    selected_card_str = selected_rank_str + str(selected_suit_str)
    return Card.new(selected_card_str)
Ejemplo n.º 40
0
def setUpDeucesCards(cardsList):
    # Take a list of cards numbered 1-52 and put them into the form
    #used by deuces evaluator.
    # Convert card numbers to a deuces form string.
    cardStrings = []
    for i in range (0,len(cardsList)):
        cardStrings.append(convertToDeuces(cardsList[i]))
    # Put cards into a deuces form hand.
    deucesCards = []
    for i in range (0,len(cardsList)):
        deucesCards.append(Card.new(cardStrings[i]))
    return deucesCards
Ejemplo n.º 41
0
def main(other_players, trials):
    with open("lookup-table-" + str(other_players), "w") as f:
        # iterate over all 169 equivalent starting hands. If you're curious about 
        # why there are only 169 equivalent starting hands, see:
        # https://en.wikipedia.org/wiki/Texas_hold_'em_starting_hands#Essentials
        count = 0
        for c1 in range(len(ranks)):
            for c2 in range(c1,len(ranks)):
                # note that the way we iterate means that r1 <= r2 always. 
                # knowing this makes it easier to get data from the output lookup table. 
                r1 = ranks[c1]
                r2 = ranks[c2]
                # We only ever use Spades and Clubs as suits because all that matters
                # is whether your starting cards are suited or off-suit. The suits
                # themselves are all equivalent, so the nominal choice doesn't matter.
                if r1==r2:
                    wins,ties = get_probabilities((Card.new(r1 + "s")), Card.new(r2 + "c"), 
                                                    other_players, trials)
                    write_to_file(f, r1, r2, "offsuit", wins, ties)
                    count +=1
                else:
                    wins,ties = get_probabilities((Card.new(r1 + "s")), Card.new(r2+ "c"), 
                                                    other_players, trials)
                    write_to_file(f, r1, r2, "offsuit", wins, ties)
                    count +=1

                    wins,ties = get_probabilities((Card.new(r1 + "s")), Card.new(r2+ "s"), 
                                                    other_players, trials)
                    write_to_file(f, r1, r2, "suited", wins, ties)
                    count +=1
                # Log the script's progress. For a given number of players, every simulation 
                # should take roughly equally long. However, the more players you have, 
                # the longer the entire process takes. (More hands to evaluate.)
                print "Simulated " + str(count) +" / 169"
Ejemplo n.º 42
0
    def encode(self, plyr_board, oppo_board, current_card,
               plyr_cards, game_over, score):
        if current_card is not None:
            current_card = Card.new(current_card)
            current_card_binary = self.card_to_ranks_binary(current_card)
        else:
            current_card_binary = np.zeros(13)

        free_streets = np.array(plyr_board.get_free_streets())
        free_streets_std = (free_streets - 0.5) * 2  # Hacky "standardisation"

        encoding = np.hstack([
            current_card_binary,
            free_streets_std
        ])

        return encoding
Ejemplo n.º 43
0
def getRank4(card):
	hand=[Card.new(card[0]),Card.new(card[1])]
	evaluator=Evaluator()
	board=[Card.new(card[2]),Card.new(card[3]),Card.new(card[4]),Card.new(card[5]),Card.new(card[6])]
	rank4=evaluator.evaluate(board,hand)
	return rank4
Ejemplo n.º 44
0
def getRankBoard(card):
	board1=[Card.new(card[2]),Card.new(card[3])]
	evaluator=Evaluator()
	board2=[Card.new(card[4]),Card.new(card[5]),Card.new(card[6])]
	rankboard=evaluator.evaluate(board1,board2)
	return rankboard
Ejemplo n.º 45
0
 def __init__(self, card_strs):
     self.cards = [Card.new(x) for x in card_strs]
Ejemplo n.º 46
0
 def add_card(self, new_card_str):
     self.cards.append(Card.new(new_card_str))
Ejemplo n.º 47
0
from rlofc.royalty_calculator import RoyaltyCalculator
from deuces import Card


no_pair  = [Card.new(x) for x in ['2h', '9c', '3d', '4d', '5d']]
one_pair = [Card.new(x) for x in ['Ah', 'Th', '8h', '5h', '5c']]
two_pair = [Card.new(x) for x in ['Ah', 'Th', 'Th', '5h', '5c']]
trips    = [Card.new(x) for x in ['Ah', 'Th', '8h', '8d', '8c']]
straight = [Card.new(x) for x in ['Ah', 'Kh', 'Qh', 'Jh', 'Tc']]
flush    = [Card.new(x) for x in ['Ah', 'Th', '8h', '5h', '4h']]
boat     = [Card.new(x) for x in ['Ah', 'As', 'Ac', '8d', '8c']]
quads    = [Card.new(x) for x in ['Ah', 'As', 'Ac', 'Ad', 'Kc']]
sf       = [Card.new(x) for x in ['Ah', '2h', '3h', '4h', '5h']]
royal    = [Card.new(x) for x in ['Ah', 'Kh', 'Qh', 'Jh', 'Th']]


def test_back_royalties():
    assert RoyaltyCalculator.score_back_royalties(no_pair) == 0
    assert RoyaltyCalculator.score_back_royalties(one_pair) == 0
    assert RoyaltyCalculator.score_back_royalties(two_pair) == 0
    assert RoyaltyCalculator.score_back_royalties(trips) == 0
    assert RoyaltyCalculator.score_back_royalties(straight) == 2
    assert RoyaltyCalculator.score_back_royalties(flush) == 4
    assert RoyaltyCalculator.score_back_royalties(boat) == 6
    assert RoyaltyCalculator.score_back_royalties(quads) == 10
    assert RoyaltyCalculator.score_back_royalties(sf) == 15
    assert RoyaltyCalculator.score_back_royalties(royal) == 35


def test_mid_royalties():
    assert RoyaltyCalculator.score_mid_royalties(no_pair) == 0
Ejemplo n.º 48
0
    def getHandScore(self):
        
        hand = [Card.new(c) for c in self.hole_cards]
        board = [Card.new(c) for c in self.community_cards]

        return self.evaluator.evaluate(board, hand)
Ejemplo n.º 49
0
from deuces import Card, Evaluator, Deck


# create a board and hole cards
board = []

hand = [
    Card.new('2s'),
    Card.new('5c')
]
hand2 = [
    Card.new('2s'),
    Card.new('7c')
]



# create an evaluator
evaluator = Evaluator()

# and rank your hand
rank = evaluator.evaluate(board, hand)
rank2 = evaluator.evaluate(board, hand2)

print rank, rank2
Ejemplo n.º 50
0
 def parse_cards(self, cards):
     list = []
     for tup in cards:
         list.append(Card.new(self.ranks[tup[0]] + str(tup[1])))
     return list
Ejemplo n.º 51
0
from deuces import Card, Evaluator, Deck

# create a card
card = Card.new('qh')

# create a board and hole cards
board = [
    Card.new('2h'),
    Card.new('2s'),
    Card.new('jc')
]
hand = [
    Card.new('qs'),
    Card.new('th')
]

# pretty print cards to console
Card.print_pretty_cards(board + hand)

# create an evaluator
evaluator = Evaluator()

# and rank your hand
rank = evaluator.evaluate(board, hand)
print "Rank for your hand is: %d" % rank

# or for random cards or games, create a deck
print "Dealing a new hand..."
deck = Deck()
board = deck.draw(5)
player1_hand = deck.draw(2)
Ejemplo n.º 52
0
def take_action(ws, event_name, data):
    global MY_SITE
    global HAND_CARDS
    global BOARD_CARDS
    global MINBET
    if event_name in ["__game_prepare", "__game_start"]:
        pass
    elif event_name == "__new_round":
        my_site, online_player_number = get_my_site(data)
        hand_cards = [player for player in data['players'] if player['playerName'] == name_md5][0]['cards']
        HAND_CARDS = [Card.new('{}{}'.format(hand_card[0], str.lower(hand_card[-1]))) for hand_card in hand_cards]
        if my_site == 1:
            MY_SITE = SB
            return
        elif my_site == 2:
            MY_SITE = BB
            return
        elif online_player_number >= 8:
            if my_site <= 4:
                MY_SITE = UTG
                return
            if online_player_number - my_site >= 2:
                MY_SITE = MP
                return
            if online_player_number - my_site >= 1:
                MY_SITE = CO
                return
            else:
                MY_SITE = BTN
                return
        else:
            if my_site <= 3:
                MY_SITE = UTG
                return
            if online_player_number - my_site >= 2:
                MY_SITE = MP
                return

            if online_player_number - my_site >= 1:
                MY_SITE = CO
                return
            else:
                MY_SITE = BTN
                return

    elif event_name == "__bet":
        BOARD_CARDS = [Card.new('{}{}'.format(card[0], str.lower(card[-1]))) for card in data['game']['board']]
        MINBET = data['self']['minBet']
        Card.print_pretty_cards(HAND_CARDS + BOARD_CARDS)
        win_prob = poker_deuces.calculate_winning_probability(HAND_CARDS, BOARD_CARDS, len(
            [player for player in data['game']['players'] if not player['folded']]), SAMPLE_COUNT)
        print('my winning probability: {}%'.format(win_prob * 100))

        ws.send(json.dumps({
            "eventName": "__action",
            "data": {
                "action": "bet"
            }
        }))
    elif event_name == "__action":
        BOARD_CARDS = [Card.new('{}{}'.format(card[0], str.lower(card[-1]))) for card in data['game']['board']]
        MINBET = data['self']['minBet']
        Card.print_pretty_cards(HAND_CARDS + BOARD_CARDS)
        win_prob = poker_deuces.calculate_winning_probability(HAND_CARDS, BOARD_CARDS, len([player for player in  data['game']['players'] if not player['folded']]), SAMPLE_COUNT)
        print('my winning probability: {}%'.format(win_prob * 100))

        ws.send(json.dumps({
            "eventName": "__action",
            "data": {
                "action": "call"
            }
        }))
    elif event_name == "__show_action":
        BOARD_CARDS = [Card.new('{}{}'.format(card[0], str.lower(card[-1]))) for card in data['table']['board']]
        # MINBET = data['action']['amount']
        win_prob = poker_deuces.calculate_winning_probability(HAND_CARDS, BOARD_CARDS, len(
            [player for player in data['players'] if not player['folded']]), SAMPLE_COUNT)
        Card.print_pretty_cards(HAND_CARDS + BOARD_CARDS)
        print('my winning probability: {}%'.format(win_prob * 100))
    elif event_name == "__round_end":
        MY_SITE = None
        MINBET = None
        HAND_CARDS = []
        BOARD_CARDS = []

        print('Round End')
    elif event_name == "__game_over":
        print('Game Over')
        os._exit(0)
    else:
        pass
Ejemplo n.º 53
0
Archivo: go.py Proyecto: xashes/deuces
from deuces import Card, Evaluator, Deck

# create a card
card = Card.new("Qh")

# create a board and hole cards
board = [Card.new("2h"), Card.new("2s"), Card.new("Jc")]
hand = [Card.new("Qs"), Card.new("Th")]

# pretty print cards to console
Card.print_pretty_cards(board + hand)

# create an evaluator
evaluator = Evaluator()

# and rank your hand
rank = evaluator.evaluate(board, hand)
print "Rank for your hand is: %d" % rank

# or for random cards or games, create a deck
print "Dealing a new hand..."
deck = Deck()
board = deck.draw(5)
player1_hand = deck.draw(2)
player2_hand = deck.draw(2)

print "The board:"
Card.print_pretty_cards(board)

print "Player 1's cards:"
Card.print_pretty_cards(player1_hand)
Ejemplo n.º 54
0
    if rank_class in [0, 1, 5]:
        return True

    return False


evaluator = Evaluator()
cards = ['Ah', 'Kh', 'Qh', 'Jh', 'Th', '9h', '8h',
         '7h', '6h', '5h', '4h', '3h', '2h']

perms = []
for i in xrange(len(cards)):
    for j in xrange(i, len(cards)):
        for k in xrange(j, len(cards)):
            perms.append([Card.new(cards[i]),
                          Card.new(cards[j]),
                          Card.new(cards[k])])

front_lookup = {}
for perm in perms:
    # Add the two lowest unpairing cards
    hand = copy(perm)

    hand.append(get_lowest_unpairing_card(hand))
    hand.append(get_lowest_unpairing_card(hand))

    prime_prod = Card.prime_product_from_hand(perm)
    rank = evaluator.evaluate(hand, []) + 1
    kicker = Card.get_rank_int(perm[0]) * 0.01 + \
        Card.get_rank_int(perm[1]) * 0.0001 + \
Ejemplo n.º 55
0
def str_to_cards(cardsstr):
    cards = []
    for cardstr in cardsstr:
        card = Card.new(cardstr)
        cards.append(card)
    return cards