Esempio n. 1
0
    def hand_strength(self, board):
        ''' hand strength '''

        evaluator = deuces.Evaluator()
        b5 = self.best_five(board)
        h1 = b5[:2].replace('S',
                            's').replace('H',
                                         'h').replace('D',
                                                      'd').replace('C', 'c')
        h2 = b5[3:5].replace('S',
                             's').replace('H',
                                          'h').replace('D',
                                                       'd').replace('C', 'c')
        b1 = b5[6:8].replace('S',
                             's').replace('H',
                                          'h').replace('D',
                                                       'd').replace('C', 'c')
        b2 = b5[9:11].replace('S',
                              's').replace('H',
                                           'h').replace('D',
                                                        'd').replace('C', 'c')
        b3 = b5[12:14].replace('S', 's').replace('H', 'h').replace(
            'D', 'd').replace('C', 'c')
        hl = [deuces.Card.new(h1), deuces.Card.new(h2)]
        bl = [deuces.Card.new(b1), deuces.Card.new(b2), deuces.Card.new(b3)]
        strength = evaluator.evaluate(bl, hl)

        return strength
Esempio n. 2
0
 def get_winner(self):
     evaluator = deuces.Evaluator()
     winner = 0
     best_score = 8000
     scores = "Each hand has been scored:"
     for uid in p.in_game:
         hand = []
         #Generate a hand that the deuces module understands
         for card in p.players[uid].hand.cards:
             rank = str(card.rank)
             if rank == '10':
                 rank = 'T'
             suit = card.suit.lower()
             hand.append(deuces.Card.new(rank + suit))
         p.players[uid].score = evaluator.evaluate([], hand)
         p.players[uid].rank_class = evaluator.get_rank_class(p.players[uid].score)
         if p.players[uid].score < best_score:
             best_score = p.players[uid].score
             winner = uid
         scores = scores + " " + p.players[uid].name + " - " + str(evaluator.class_to_string(p.players[uid].rank_class)) + ","
     del evaluator
     scores = scores[:-1]
     self.phenny.say(scores)
     
     winnings = self.betting_pot - p.players[winner].bet
     house = (winnings * 0.05)
     casino.gold += house
     winnings = (winnings * 0.95)
     p.players[winner].win(self.phenny, self.betting_pot)
     self.phenny.say("%s has the highest ranking hand! They won %d gold! They now have %d gold. %d gold was taken by the house." % (p.players[winner].name, winnings, p.players[winner].gold, house))
Esempio n. 3
0
    def process_user_class(self):
        # Save in a dict
        rank_dict = {}
        board = list(eval(self.dealer_cards))
        # create an evaluator
        evaluator = deuces.Evaluator()

        if self.player_cards and self.player_cards != '':
            player_cards_dict = eval(self.player_cards)
        else:
            player_cards_dict = {}
        if self.player_active_dict and self.player_active_dict != '':
            player_active_dict = eval(self.player_active_dict)
        else:
            player_active_dict = {}

        for player in player_cards_dict:
            if player_active_dict[player]:
                hand = player_cards_dict[player]
            # and rank your hand
                rank = evaluator.evaluate(board, hand)
            else:
                rank = -1

            rank_dict[player] = rank

        return rank_dict
Esempio n. 4
0
def generate_postflop_odds(preflop_type, deck):
    """
    For each of the six preflop buckets, calculates the odds of the postflop cards putting the hand into one of the five
    hand strength buckets.
    """
    evaluator=deuces.Evaluator()
    postflop_odds=[]
    for type in preflop_type: #Loops through each of the preflop buckets
        odds=[0, 0, 0, 0, 0]
        for hand in type: #Loops through each hand in the bucket
            new_deck=deck[:]
            new_deck.remove(hand[0]) #Removes the cards in the current hand from the deck
            new_deck.remove(hand[1])
            postflop_hands=list(itertools.combinations(new_deck, 5))
            for i in range(10000): #Doesn't loop through all possible five board cards for each hole card, only picks 50 random ones and estimates odds of going from one bucket to another
                board=postflop_hands.pop(random.randint(0, len(postflop_hands)-1))
                hand_strength=get_hand_strength(hand, board, evaluator)
                if hand_strength<=.2:
                    odds[0]+=1
                elif hand_strength>.2 and hand_strength<=.4:
                    odds[1]+=1
                elif hand_strength>.4 and hand_strength<=.6:
                    odds[2]+=1
                elif hand_strength>.6 and hand_strength<=.8:
                    odds[3]+=1
                else:
                    odds[4]+=1
        total=sum(odds)
        for i in range(len(odds)):
            odds[i]=odds[i]/float(total)
        print(odds)
        postflop_odds.append(odds)
    return postflop_odds
Esempio n. 5
0
def calculate_winner(g):
    '''
    Given 5 cards, calculates who has the stronger hand.
    '''
    player_1_hand = [
        deuces.Card.new(g.cards_in_play[0]),
        deuces.Card.new(g.cards_in_play[1])
    ]
    player_2_hand = [
        deuces.Card.new(g.cards_in_play[2]),
        deuces.Card.new(g.cards_in_play[3])
    ]
    board = [
        deuces.Card.new(g.cards_in_play[4]),
        deuces.Card.new(g.cards_in_play[5]),
        deuces.Card.new(g.cards_in_play[6])
    ]

    evaluator = deuces.Evaluator()
    player_1_hand_value = evaluator.evaluate(board, player_1_hand)
    player_2_hand_value = evaluator.evaluate(board, player_2_hand)
    if player_1_hand_value < player_2_hand_value:
        return g.tree.players[0]
    elif player_1_hand_value > player_2_hand_value:
        return g.tree.players[1]
    else:
        return None
    def __init__(self, qntd_players):

        self.game_deck = deuces.Deck()
        self.game_players = [self.game_deck.draw(2), self.game_deck.draw(2)]
        self.last_act = [1, 1]
        self.board = self.game_deck.draw(5)
        self.player_turn = 0
        self.now = 'bet'
        self.state = 1
        self.eval = deuces.Evaluator()
Esempio n. 7
0
    def __init__(self, qntd_players):
        # self.game_deck = deuces.deck
        # self.player_turn = 0
        # self.state = 0
        # self.game = game(qntd_players)
        # self.game.board = self.game.game_deck.draw(5)
        # self.game.players = [self.game.game_deck.draw(2),self.game.game_deck.draw(2)]
        # self.players_list = self.game.player_on

        self.game_deck = deuces.Deck()
        self.game_players = [self.game_deck.draw(2), self.game_deck.draw(2)]
        self.last_act = [1, 1]
        self.board = self.game_deck.draw(5)
        self.player_turn = 0
        self.state = 1
        self.eval = deuces.Evaluator()
Esempio n. 8
0
def calc_win_prob_by_sampling(hole_cards, board_cards, data):
    """
    Calculate the probability to win current players by sampling unknown cards
    Compute the probability to win one player first
    And then take the power of virtual player count
    """
    evaluator = deuces.Evaluator()
    o_hole_cards = []
    o_board_cards = []
    for card in hole_cards:
        o_hole_card = deuces.Card.new(card)
        o_hole_cards.append(o_hole_card)
    for card in board_cards:
        o_board_card = deuces.Card.new(card)
        o_board_cards.append(o_board_card)

    n = 1000
    win = 0
    succeeded_sample = 0
    for i in range(n):
        deck = deuces.Deck()
        board_cards_to_draw = 5 - len(o_board_cards)

        o_board_sample = o_board_cards + deck.draw(board_cards_to_draw)
        o_hole_sample = deck.draw(2)

        try:
            my_rank = evaluator.evaluate(o_board_sample, o_hole_cards)
            rival_rank = evaluator.evaluate(o_board_sample, o_hole_sample)
        except:
            continue
        if my_rank <= rival_rank:
            win += 1
        succeeded_sample += 1
    print "==== sampling result ==== win : %d, total : %d" % (win,
                                                              succeeded_sample)
    win_one_prob = win / float(succeeded_sample)

    win_all_prob = win_one_prob**virtual_player_count(data)
    print "==== Win probability ==== " + str(win_all_prob)
    return win_all_prob
Esempio n. 9
0
def transform_sampling(sim_num, hole_cards, board_cards, data, is_max):
    eval_hand = [getCard(card) for card in (hole_cards)]
    eval_board = [getCard(card) for card in (board_cards)]
    d_hands = [deuces.Card.new(card) for card in hole_cards]

    evaluator = deuces.Evaluator()
    SUIT_TO_STRING = {
        1: "s",
        2: "h",
        3: "d",
        4: "c"
    }
    RANK_TO_STRING = {
        2: "2",
        3: "3",
        4: "4",
        5: "5",
        6: "6",
        7: "7",
        8: "8",
        9: "9",
        10: "T",
        11: "J",
        12: "Q",
        13: "K",
        14: "A"
    }
    
    win = 0
    succeeded_sample = 0
    num_players = player_count[str(data["game"]["roundName"])]
    #print "Is max? %s" % is_max
    
    for i in range(sim_num):
        board_cards_to_draw = 5 - len(eval_board)
        e_board_sample = eval_board + _pick_unused_card(board_cards_to_draw, eval_board+eval_hand) # exclude my cards and community cards
        unused_cards = _pick_unused_card((num_players - 1) * 2, eval_hand + e_board_sample)
        e_opponents_hole = [unused_cards[2 * i:2 * i + 2] for i in range(num_players - 1)]

        d_oppo_sample = []
        d_oppo_set = []
        d_board_sample = []
        for evalcard in e_board_sample:  # pokereval Card type
            s_hand = str(RANK_TO_STRING[evalcard.rank]) + str(SUIT_TO_STRING[evalcard.suit])
            d_board_card = deuces.Card.new(s_hand)
            d_board_sample.append(d_board_card)

        for evalcardset in e_opponents_hole:
            d_oppo_set = []
            for e_card in evalcardset:
                s_hand = str(RANK_TO_STRING[e_card.rank]) + str(SUIT_TO_STRING[e_card.suit])
                d_oppo_card = deuces.Card.new(s_hand)
                d_oppo_set.append(d_oppo_card)
                #print ("Opponents hands : "+s_hand)
            d_oppo_sample.append(d_oppo_set)
            

        try:
            my_rank = evaluator.evaluate(d_hands, d_board_sample)
            rival_rank = [evaluator.evaluate(opp_hole, d_board_sample) for opp_hole in d_oppo_sample]
            #my_rank = pow(evaluator.evaluate(d_hands, d_board_sample), num_players)
            #rival_rank = [pow(evaluator.evaluate(opp_hole, d_board_sample), num_players) for opp_hole in d_oppo_sample]
       
        except:
            continue

        if is_max == 'true':
            if my_rank <= max(rival_rank):
                win += 1
        else:
            if my_rank <= min(rival_rank):
                win += 1
        succeeded_sample += 1
    
    #print "number of min method called: %d, win: %d, total: %d" %(minnum, win, succeeded_sample)
    return (win, succeeded_sample)
Esempio n. 10
0
    username=user,
    password=pw,
    user_agent='Dealer bot v{} by /u/eganwall'.format(version))

# initialize our repository and logger
sg_repo = SG_Repository.Repository()
logger = SG_Utils.LogUtility()

# get our messaging classes
error_messages = SG_Messages.ErrorMessages
reply_messages = SG_Messages.ReplyMessages
constants = SG_Messages.MiscConstants

# initialize the classes we need to run the poker game
card = deuces.Card()
evaluator = deuces.Evaluator()


def handle_message(ch, method, properties, body):
    # get current time for elapsed time tracking
    start_time = time.time()

    message = json.loads(body)

    # get the comment instance so we can reply to it
    comment = reddit.comment(message['comment_id'])

    # get the player from the DB so we can validate their wager
    # and update their balance
    player = sg_repo.GET_PLAYER_BY_USERNAME(comment.author.name)
Esempio n. 11
0
    def win_prob(self, your_hand, river_cards, no_of_other_hands, sim=10000):
        """
        Input Example:
            Your Hand: ['Ah', '7c'] ---> Ace of Hearts and Seven of Clubs
            River Cards: ['Ad', '2d', '6d'] --> Ace of Diamonds, 2 of Diamonds, 6 of Diamonds, and 2 others (always 5)
            No of Others: 2 ---> 2 other players remain
            Simulations: number of Monte Carlo simulations to run, default=10000
        Output: Your win %
            If river_cards are present: Use MC simulations to estimate odds
            If no river_cards are present: Use lookup table to find pre-flop odds and return immediately
        """
        if len(river_cards) == 0:  #Pre-flop, compute with lookup table
            if your_hand[0][1] == your_hand[1][1]:  #suited
                return helper.preflop([
                    your_hand[0][0] + your_hand[1][0] + 's',
                    your_hand[1][0] + your_hand[0][0] + 's'
                ], no_of_other_hands + 1)
            else:  #unsuited
                return helper.preflop([
                    your_hand[0][0] + your_hand[1][0] + 'o',
                    your_hand[1][0] + your_hand[0][0] + 'o'
                ], no_of_other_hands + 1)
        else:
            possible_cards = [a + b for a in vals for b in suits]
            for card in your_hand:
                possible_cards.remove(card)
            for card in river_cards:
                possible_cards.remove(card)

            wins = 0
            num_cards = 5 - len(river_cards) + 2 * no_of_other_hands
            evaluator = d.Evaluator()

            for i in range(sim):  #10,000 MC simulations
                generated_cards = np.random.choice(possible_cards,
                                                   num_cards,
                                                   replace=False)
                counter = 0
                my_hand = [d.Card.new(card) for card in your_hand]
                board = [d.Card.new(card) for card in river_cards]
                while len(board) < 5:
                    board.append(d.Card.new(generated_cards[counter]))
                    counter += 1
                hand_strength = evaluator.evaluate(board, my_hand)
                best_strength = 1e10  #some random large number
                no_best_hands = 1  #number of hands that are at best_strength
                for j in range(no_of_other_hands):
                    new_hand = [
                        d.Card.new(generated_cards[counter]),
                        d.Card.new(generated_cards[counter + 1])
                    ]
                    counter += 2
                    new_strength = evaluator.evaluate(board, new_hand)
                    if new_strength < best_strength:
                        best_strength = new_strength
                        no_best_hands = 1  #reset
                    elif new_strength == best_strength:
                        no_best_hands += 1  #add one more
                if best_strength > hand_strength:
                    wins += 1
                elif best_strength == hand_strength:
                    wins += 1 / no_best_hands

            return wins / sim
Esempio n. 12
0
def getPostFlopAction(valid_actions, hand, board, stack, last_action):
    evaluator = de.Evaluator()
    # return your current hand value the 10 moves will be ascribed accordingly
    evaluation = evaluator.get_five_card_rank_percentage(
        evaluator.evaluate(hand, board))
    actionProb = (1 - evaluation) * 100
    if actionProb <= 10:
        fold_action_info = valid_actions[0]
        action, amount = fold_action_info["action"], fold_action_info["amount"]
    elif actionProb > 10 and actionProb <= 55:
        call_action_info = valid_actions[1]
        action, amount = call_action_info["action"], call_action_info["amount"]
    # no simple raise possible anymore
    elif valid_actions[2]["amount"]["min"] == -1:
        if valid_actions[1]["amount"] >= stack:
            action, amount = valid_actions[1]["action"], valid_actions[1][
                "amount"]
        else:
            amount = valid_actions[1]["amount"] - int(last_action[1]) + stack
            action = valid_actions[2]["action"]
    elif actionProb > 55 and actionProb <= 65:
        raise_action_info = valid_actions[2]
        action, amount = raise_action_info["action"], raise_action_info[
            "amount"]["min"]
    elif actionProb > 65 and actionProb <= 70:
        raise_action_info = valid_actions[2]
        amount_call_action = valid_actions[1]["amount"]
        action = raise_action_info["action"]
        amount = (raise_action_info["amount"]["min"] -
                  amount_call_action) * 1.5 + amount_call_action
    elif actionProb > 70 and actionProb <= 75:
        raise_action_info = valid_actions[2]
        amount_call_action = valid_actions[1]["amount"]
        action = raise_action_info["action"]
        amount = (raise_action_info["amount"]["min"] -
                  amount_call_action) * 2 + amount_call_action
    elif actionProb > 75 and actionProb <= 80:
        raise_action_info = valid_actions[2]
        amount_call_action = valid_actions[1]["amount"]
        action = raise_action_info["action"]
        amount = (raise_action_info["amount"]["min"] -
                  amount_call_action) * 3 + amount_call_action
    elif actionProb > 80 and actionProb <= 85:
        raise_action_info = valid_actions[2]
        amount_call_action = valid_actions[1]["amount"]
        action = raise_action_info["action"]
        amount = (raise_action_info["amount"]["min"] -
                  amount_call_action) * 5 + amount_call_action
    elif actionProb > 85 and actionProb <= 90:
        raise_action_info = valid_actions[2]
        amount_call_action = valid_actions[1]["amount"]
        action = raise_action_info["action"]
        amount = (raise_action_info["amount"]["min"] -
                  amount_call_action) * 10 + amount_call_action
    elif actionProb > 90 and actionProb <= 95:
        raise_action_info = valid_actions[2]
        amount_call_action = valid_actions[1]["amount"]
        action = raise_action_info["action"]
        amount = (raise_action_info["amount"]["min"] -
                  amount_call_action) * 25 + amount_call_action
    else:
        raise_action_info = valid_actions[2]
        action, amount = raise_action_info["action"], raise_action_info[
            "amount"]["max"]
    if valid_actions[2]["amount"]["max"] != -1:
        if action == "raise" and amount > valid_actions[2]["amount"]["max"]:
            amount = valid_actions[2]["amount"]["max"]
    return action, int(amount)
Esempio n. 13
0
def run():
    SUIT_TO_STRING = {1: "s", 2: "h", 3: "d", 4: "c"}

    RANK_TO_STRING = {
        2: "2",
        3: "3",
        4: "4",
        5: "5",
        6: "6",
        7: "7",
        8: "8",
        9: "9",
        10: "T",
        11: "J",
        12: "Q",
        13: "K",
        14: "A"
    }

    hole_cards = ['4s', 'Qh']
    board_cards = ['Jc', '6c', '9h']
    #board_cards = []

    eval_hand = [getCard(card) for card in (hole_cards)]
    print eval_hand.__repr__()
    eval_board = [getCard(card) for card in (board_cards)]
    print eval_board.__repr__()
    d_hands = [deuces.Card.new(card) for card in hole_cards]

    evaluator = deuces.Evaluator()

    sim_num = 15000
    win = 0
    succeeded_sample = 0
    num_players = 6

    for i in range(sim_num):
        board_cards_to_draw = 5 - len(eval_board)
        e_board_sample = eval_board + _pick_unused_card(
            board_cards_to_draw,
            eval_board + eval_hand)  # exclude my cards and community cards
        unused_cards = _pick_unused_card((num_players - 1) * 2,
                                         eval_hand + e_board_sample)
        e_opponents_hole = [
            unused_cards[2 * i:2 * i + 2] for i in range(num_players - 1)
        ]

        d_oppo_sample = []
        d_oppo_set = []
        d_board_sample = []
        for evalcard in e_board_sample:  # pokereval Card type
            s_hand = str(RANK_TO_STRING[evalcard.rank]) + str(
                SUIT_TO_STRING[evalcard.suit])
            d_board_card = deuces.Card.new(s_hand)
            d_board_sample.append(d_board_card)
            #print ("Community : "+s_hand)

        for evalcardset in e_opponents_hole:
            d_oppo_set = []
            for e_card in evalcardset:
                s_hand = str(RANK_TO_STRING[e_card.rank]) + str(
                    SUIT_TO_STRING[e_card.suit])
                d_oppo_card = deuces.Card.new(s_hand)
                d_oppo_set.append(d_oppo_card)
                #print ("Opponents hands : "+s_hand)
            d_oppo_sample.append(d_oppo_set)

        try:
            my_rank = pow(evaluator.evaluate(d_hands, d_board_sample),
                          num_players)
            rival_rank = [
                pow(evaluator.evaluate(opp_hole, d_board_sample), num_players)
                for opp_hole in d_oppo_sample
            ]
            #print str(my_rank) +" versus "+str(rival_rank)
        except:
            continue
        if my_rank <= min(rival_rank):
            win += 1
        succeeded_sample += 1
    print "==== Sampling result ==== win : %d, total : %d" % (win,
                                                              succeeded_sample)
    win_one_prob = win / float(succeeded_sample)
    print "==== Win probability ==== " + str(win_one_prob)