def estimate_proba(hand, board, n_player, n_simul=1000): evaluator = Evaluator() to_draw = 5 - len(board) deck = set_deck(hand, board) winnings = [] for _ in range(n_simul): deck2 = deepcopy(deck) shuffle(deck2.cards) if to_draw == 1: board2 = board + [deck2.draw(to_draw)] else: board2 = board + deck2.draw(to_draw) if n_player > 2: other_hands = list( zip(deck2.draw(n_player - 1), deck2.draw(n_player - 1))) score_others = min([ evaluator.evaluate(list(hand2), board2) for hand2 in other_hands ]) elif n_player == 2: other_hand = deck2.draw(2) score_others = evaluator.evaluate(other_hand, board2) score_player = evaluator.evaluate(hand, board2) winnings += [score_player < score_others] return mean(winnings)
def compareRank(self): HighRank = 8000 HingRankIndex = -1 board = [] evalulator = Evaluator() sh1 = self.convertHand(self.object1.student_Hand) HighRank = evalulator.evaluate(board, sh1) HighRankIndex = 0 print "\n" print "Player 1: " + self.object1.student_Name + "\t Cards: " + self.printHand( self.object1.student_Hand) + "\t Card-rank: " + str(HighRank) sh2 = self.convertHand(self.object2.student_Hand) rank = evalulator.evaluate(board, sh2) print "\n" print "Player 2: " + self.object2.student_Name + "\t Cards: " + self.printHand( self.object2.student_Hand) + "\t Card-rank: " + str(rank) if (rank < HighRank): HighRank = rank HighRankIndex = 1 if (self.object3 is None): print "\n" print "Player " + str(HighRankIndex + 1) + " is winner with rank " + str(HighRank) return else: sh3 = self.convertHand(self.object3.student_Hand) rank = evalulator.evaluate(board, sh3) print "\n" print "Player 3: " + self.object3.student_Name + "\t Cards: " + self.printHand( self.object3.student_Hand) + "\t Card-rank: " + str(rank) if (rank < HighRank): HighRank = rank HighRankIndex = 2 if (self.object4 is None): print "\n" print "Player " + str(HighRankIndex + 1) + " is winner with rank " + str(HighRank) return else: sh4 = self.convertHand(self.object4.student_Hand) rank = evalulator.evaluate(board, sh4) print "\n" print "Player 4: " + self.object1.student_Name + "\t Cards: " + self.printHand( self.object4.student_Hand) + "\t Card-rank: " + str(rank) if (rank < HighRank): HighRank = rank HighRankIndex = 3
def handle_stage_rank_new(self, stage, players, hand_cards, board_cards=[]): if hand_cards is None or len(hand_cards) != 2: #logging.error("hand_cards error: %s", hand_cards) print "hand_cards error: ", hand_cards return 0 if board_cards is None: board_cards = [] if players >= 12 or players < 0: #logging.warning("players too much or too few: %d, change it to 1", players) print "players too much or too few: %d, change it to 1" % players players = 1 board = board_cards hand = hand_cards win = 0 succeeded_sample = 0 evaluator = Evaluator() deck = RemovableDeck() deck.remove(hand) deck.remove(board) for i in range(10000): new_deck = copy.deepcopy(deck) new_deck.shuffle_without_reset() board_cards_to_draw = 5 - len(board) board_sample = board if board_cards_to_draw > 0: board_sample += new_deck.draw(board_cards_to_draw) try: my_rank = evaluator.evaluate(board_sample, hand) i_can_succeed = True for j in range(players): hand_sample = new_deck.draw(2) other_rank = evaluator.evaluate(board_sample, hand_sample) if other_rank < my_rank: i_can_succeed = False break except Exception, e: continue if i_can_succeed: win += 1 succeeded_sample += 1
def build_dataframe(nb_hands=100, nb_players=2): decks = [Deck() for _ in range(nb_hands)] df_board = pd.DataFrame({'board': [deck.draw(5) for deck in decks]}) df_players = pd.concat([ pd.DataFrame({'player': [deck.draw(2) for deck in decks]}) for _ in range(nb_players) ], axis=1, keys=range(nb_players)) df_players = df_players.swaplevel(0, 1, axis=1) evaluator = Evaluator() df_scores = pd.concat([ df_board.join(df_players.xs(i, level=1, axis=1)).apply( lambda x: evaluator.evaluate(x['board'], x['player']), axis=1).to_frame('score') for i in df_players.columns.get_level_values(1) ], axis=1, keys=df_players.columns.get_level_values(1)) df_scores = df_scores.swaplevel(0, 1, axis=1) return df_board, df_players, df_scores
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
def build_dataframe(nb_hands): decks = [Deck() for _ in range(nb_hands)] boards = [deck.draw(5) for deck in decks] player1 = [deck.draw(2) for deck in decks] player2 = [deck.draw(2) for deck in decks] player3 = [deck.draw(2) for deck in decks] player4 = [deck.draw(2) for deck in decks] e = Evaluator() scores = [(e.evaluate(b, p1), e.evaluate(b, p2), e.evaluate(b, p3), e.evaluate(b, p4)) for (b, p1, p2, p3, p4) in zip(boards, player1, player2, player3, player4)] df = pd.DataFrame(scores) return df
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
def __finalize_game(self): """ Giving all the money to the player with the best hand (Nothing to adapt here) :return: """ evaluator = Evaluator() hand_strength = np.array( [evaluator.evaluate(hand, self.board) for hand in self.hands]) if any(~(self.all_ins | self.ins)): hand_strength[~(self.all_ins | self.ins)] = np.nan if any(self.all_ins | self.ins): winner = np.nanargmin(hand_strength) # computing how much money the winner is getting from the others money_transfer = np.min( [self.bets, [self.bets[winner]] * self.n_players], axis=0) self.money[winner] += np.sum(money_transfer) self.bets = self.bets - money_transfer # redistributing what hasn't been won to the players self.money += self.bets self.bets *= 0
def run(number): """ This function generates a population sample with size sample. It also computes probabilities for each hand, considering a frequentist approach. Arguments: - number (int): run ID Returns: - stats (str): returns a JSON formatted string containing probabilities for each poker hand """ print 'starting run #{0}'.format(number) evaluator = Evaluator() poker_hands = defaultdict(int) for _ in range(SAMPLE_SIZE): deck = Deck() p1_hand = deck.draw(5) p1_score = evaluator.evaluate(p1_hand, []) if p1_score == 1: # just a little hack poker_hands['Royal Flush'] += 1 else: p1_class = evaluator.get_rank_class(p1_score) poker_hands[evaluator.class_to_string(p1_class)] += 1 stats = dict((k, round(float(v)/SAMPLE_SIZE, 7)) for k, v in poker_hands.items()) return json.dumps(stats)
def test_valuation(self): player0 = self.df_players.xs(0, level=1, axis=1) df = self.df_board.join(player0) evaluator = Evaluator() valuations = df.apply( lambda x: evaluator.evaluate(x['board'], x['player']), axis=1) expected = [310, 2415, 5362, 4014, 2991] self.assertEqual(valuations.values.tolist(), expected)
def test_create_single_df_of_scores(self): evaluator = Evaluator() df = self.df_board.join(self.df_players.xs(0, level=1, axis=1)).apply( lambda x: evaluator.evaluate(x['board'], x['player']), axis=1).to_frame('score') expected = [[310], [2415], [5362], [4014], [2991]] self.assertEqual(df.values.tolist(), expected) self.assertEqual(df.columns, ['score'])
def get_score_by_simulate(board_cards, hand_cards, iteration=5): try: score_min = 10000 # deuces evaluate score, the small, the better 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) if (len(hand) + len(board) < 5): score_list = [] for i in range(iteration): evaluator = Evaluator() deck = Deck() random_cards = deck.draw(5 - len(board) - len(hand)) if (isinstance(random_cards, int)): random_cards = [random_cards] score = evaluator.evaluate(board + random_cards, hand) score_list.append(score) score_list.remove(max(score_list)) score_list.remove(min(score_list)) return sum(score_list) / float(len(score_list)) 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 except Exception as e: traceback.print_exc() printtolog('EXCEPTION={0}'.format(e)) return score_min
def getRank3(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]) ] rank3 = evaluator.evaluate(board, hand) return rank3
def get_gap_between_hands_and_board(hands, board): evaluator = Evaluator() value = evaluator.evaluate(board, hands) if len(board) == 5: board_value = evaluator.evaluate(board, []) gap = abs(value - board_value) print("(5 Board Cards) Gap: {}".format(gap)) return gap elif len(board) == 4: v1 = evaluator.evaluate(board, [hands[0]]) v2 = evaluator.evaluate(board, [hands[1]]) gap1 = abs(value - v1) gap2 = abs(value - v2) max_gap = max(gap1, gap2) print( "(4 Board Cards) V1: {}, V2: {}, Gap1: {}, Gap2: {}, Max Gap: {}". format(v1, v2, gap1, gap2, max_gap)) return max_gap else: return 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
def ai_action(data, debug=False): rank, s_player, round_count = get_player(data) table_card, self_card = get_card(data) betCount = get_betCount(data) min_bet = get_minBet(data) print "Survive player : {n}".format(n=s_player) print "Sparrow ranking: {n}".format(n=rank) print "Total BetCount : {n}".format(n=betCount) print "min_bet : {n}".format(n=min_bet) gamma = 0 beta = 0 alpha = 0 if rank < 3: alpha = -1200 gamma = -1000 ''' if round_count > 5 and rank > 5: gamma += 1000 beta += 1000 if rank > 7: beta += 500 ''' if min_bet > 200: gamma += -500 beta += -500 if min_bet > 400: gamma += -1000 beta += -500 if len(table_card + self_card) >= 5: evaluator = Evaluator() pscore = evaluator.evaluate(table_card, self_card) pclass = evaluator.get_rank_class(pscore) print "Sparrow hand rank = %d (%s)\n" % ( pscore, evaluator.class_to_string(pclass)) if pscore > 6000 + beta: return "fold" elif pscore > 4000 + gamma: return "call" elif pscore > 2000 + alpha: return "raise" else: return "allin" elif round_count < 10 and min_bet > 300: return "fold" else: return "call"
def build_dataframe(nb_hands=1000): decks = [Deck() for _ in range(nb_hands)] boards = [deck.draw(5) for deck in decks] player1 = [deck.draw(2) for deck in decks] player2 = [deck.draw(2) for deck in decks] e = Evaluator() score1 = [e.evaluate(b, h) for (b, h) in zip(boards, player1)] score2 = [e.evaluate(b, h) for (b, h) in zip(boards, player2)] return pd.DataFrame({'score1': score1, 'score2': score2})
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)
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
def fast_eval(hole_card, public_card, players=9, simulations=1000): for i in range(0, len(hole_card)): hole_card[i] = Card.new(conv(hole_card[i])) for i in range(0, len(public_card)): public_card[i] = Card.new(conv(public_card[i])) win_rate = 0 evaluator = Evaluator() for _ in range(simulations): deck = Deck() for c in hole_card: deck.cards.remove(c) for c in public_card: deck.cards.remove(c) player_hands = [] for _ in range(players): player_hands.append(deck.draw(2)) board = [] board.extend(public_card) if 5 - len(public_card) == 1: board.append(deck.draw(1)) else: board.extend(deck.draw(5 - len(public_card))) flag = True num = 0 for p in player_hands: if evaluator.evaluate(board, p) < evaluator.evaluate( board, hole_card): flag = False break elif evaluator.evaluate(board, p) > evaluator.evaluate( board, hole_card): flag = False win_rate += 1 break else: num += 1 if flag: win_rate += 1.0 / num return 1.0 * win_rate / simulations
def get_score_by_simulate(hand, board, iteration=100): if(len(hand)+len(board)<=5): score_list = [] for i in range(iteration): evaluator = Evaluator() deck = Deck() random_cards = deck.draw(5-len(board)-len(hand)) score = evaluator.evaluate(board+random_cards, hand) score_list.append(score) score_list.remove(max(score_list)) score_list.remove(min(score_list)) return sum(score_list)/float(len(score_list)) else: score_min = 9999999 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
class HandEvaluator: def __init__(self): self.card_evaluator = Evaluator() 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
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
def handstrength(ourcards, board): ahead = 0.0 tied = 0.0 behind = 0.0 evaluator = Evaluator() deck = remove_cards(ourcards, board) evalhand = str_to_cards(ourcards) evalboard = str_to_cards(board) ourrank = evaluator.evaluate(evalboard, evalhand) opcombos = combinations(deck, 2) for combo in opcombos: holecards = str_to_cards(list(combo)) oprank = evaluator.evaluate(evalboard, holecards) if ourrank < oprank: ahead += 1 elif ourrank == oprank: tied += 1 else: behind += 1 handstrength = (ahead + tied/2)/(ahead+tied+behind) return handstrength
def test_create_df_of_scores(self): evaluator = Evaluator() scores = pd.concat([ self.df_board.join(self.df_players.xs(i, level=1, axis=1)).apply( lambda x: evaluator.evaluate(x['board'], x['player']), axis=1).to_frame('score') for i in self.df_players.columns.get_level_values(1) ], axis=1, keys=range(2)) scores = scores.swaplevel(0, 1, axis=1) self.assertEqual(len(scores), 5) expected = [('score', 0), ('score', 1)] self.assertEqual(scores.columns.tolist(), expected)
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
def determine_winners(players_and_cards, board): """ Find the player with the most valuable five-card hand, using two hole cards and five community cards. :return: List of Player objects """ evaluator = Evaluator() winners = [] high_score = None for player_id, cards in players_and_cards: score = evaluator.evaluate(cards, board) if high_score is None or score < high_score: high_score = score winners = [player_id] elif score == high_score: winners.append(player_id) return winners
def rankPositions(playerCards, communityCards, folds, handRanks): # Find hand ranks and put players in order of best hand to worst. initialNumberPlayers = len(folds) holeCards = [0] * 2 foldedHandRank = 10000 # A score worse than any non-folded outcome. board = setUpDeucesCards(communityCards) evaluator = Evaluator() for position in range(initialNumberPlayers): if(not folds[position]): holeCards[0] = playerCards[position][0] holeCards[1] = playerCards[position][1] hand = setUpDeucesCards(holeCards) # Evaluate hand rank. handRanks[position] = evaluator.evaluate(board, hand) else: handRanks[position] = foldedHandRank # Sort positions by hand ranks lowest-highest. handRankPositions = sortHandRanks(handRanks) return handRankPositions
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
def get_winner(board, hands): for hand in hands: assert len(hand) == 2, "Inavlid hand length" best_rank = 7463 # rank one worse than worst hand winners = [] evaluator = Evaluator() for player, hand in enumerate(hands): # evaluate current board position rank = evaluator.evaluate(hand, board) percentage = 1.0 - evaluator.get_five_card_rank_percentage( rank) # higher better here # print "Player %d, percentage rank among all hands = %f" % (player + 1, percentage) # detect winner if rank == best_rank: winners.append(player + 1) best_rank = rank elif rank < best_rank: winners = [player + 1] best_rank = rank return winners
def setUp(self): random.seed(0) hand = [Deck() for _ in range(5)] self.df_board = pd.DataFrame( {'board': [deck.draw(5) for deck in hand]}) players = [ pd.DataFrame({'player': [deck.draw(2) for deck in hand]}) for _ in range(2) ] df_players = pd.concat(players, axis=1, keys=range(2)) self.df_players = df_players.swaplevel(0, 1, axis=1) evaluator = Evaluator() df_scores = pd.concat([ self.df_board.join(self.df_players.xs(i, level=1, axis=1)).apply( lambda x: evaluator.evaluate(x['board'], x['player']), axis=1).to_frame('score') for i in self.df_players.columns.get_level_values(1) ], axis=1, keys=range(2)) self.df_scores = df_scores.swaplevel(0, 1, axis=1)
def display_game_state(self, table, round_actions): evaluator = Evaluator() if len(table.board) > 0: p_score = evaluator.evaluate(table.board, self.hand) p_class = evaluator.get_rank_class(p_score) p_string = evaluator.class_to_string(p_class) else: p_string = "" os.system('clear') print(round_actions) print("") print("Pot: ", table.current_pot) print("Board: ", end="") Card.print_pretty_cards(table.board) print("") print("Your hand: ", end="") Card.print_pretty_cards(self.hand) print("%s \n" % (p_string)) print("Your stack: %d" % self.stack) print("") print("Current bet: ", table.current_bet)
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
class PokerUtils: def __init__(self): self.emulateCount = 1000 self.maxRank = 7462 self.evaluator = Evaluator() self.color = { 'SPADES': 0, 'HEARTS': 1, 'CLUBS': 2, 'DIAMONDS': 3 } self.rColor = ['♠', '♥', '♣', '♦'] self.eColor = ['s', 'h', 'c', 'd'] self.rPoint = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'] self.ePoint = self.rPoint self.type = { 'HIGH_CARD': 0, 'ONE_PAIR': 1, 'TWO_PAIR': 2, 'THREE_OF_A_KIND': 3, 'STRAIGHT': 4, 'FLUSH': 5, 'FULL_HOUSE': 6, 'FOUR_OF_A_KIND': 7, 'STRAIGHT_FLUSH': 8 } self.entries = { 'HIGH_CARD': self.__is_high_card, 'ONE_PAIR': self.__is_one_pair, 'TWO_PAIR': self.__is_two_pair, 'THREE_OF_A_KIND': self.__is_three_of_a_kind, 'STRAIGHT': self.__is_straight, 'FLUSH': self.__is_flush, 'FULL_HOUSE': self.__is_full_house, 'FOUR_OF_A_KIND': self.__is_four_of_a_kind, 'STRAIGHT_FLUSH': self.__is_straight_flush } # cards: [(int<color>, int<point>), ...] # point is reverse-sorted def __diff_cards(self, cards): _cardsPoint = [] for card in cards: if card[1] not in _cardsPoint: _cardsPoint.append(card[1]) return len(_cardsPoint) def __is_high_card(self, cards): return self.__diff_cards(cards) == 5 and \ not self.__is_flush(cards) and \ not self.__is_straight(cards) def __is_one_pair(self, cards): return self.__diff_cards(cards) == 4 def __is_two_pair(self, cards): return self.__diff_cards(cards) == 3 and \ (cards[2][1] != cards[0][1] and cards[2][1] != cards[4][1]) def __is_three_of_a_kind(self, cards): return self.__diff_cards(cards) == 3 and \ (cards[0][1] == cards[1][1] == cards[2][1] or cards[1][1] == cards[2][1] == cards[3][1] or cards[2][1] == cards[3][1] == cards[4][1]) def __is_straight(self, cards): return self.__diff_cards(cards) == 5 and \ (cards[4][1] == 12 or cards[0][1] - cards[4][1] == 4) def __is_flush(self, cards): return cards[0][0] == cards[1][0] == \ cards[2][0] == cards[3][0] == cards[4][0] def __is_full_house(self, cards): return self.__diff_cards(cards) == 2 and \ cards[0][1] == cards[1][1] and cards[3][1] == cards[4][1] def __is_four_of_a_kind(self, cards): return self.__diff_cards(cards) == 2 and \ (cards[0][1] != cards[1][1] or cards[3][1] != cards[4][1]) def __is_straight_flush(self, cards): return self.__is_straight(cards) and self.__is_flush(cards) def sortedGroupList(self, cards): cards = [(card / 13, card % 13) for card in cards] return sorted(cards, key = lambda card: card[1], reverse = True) def getColorOf(self, card): return card / 13 def getPointOf(self, card): return card % 13 def cardsBeautify(self, cards): return ' '.join([self.rColor[card[0]] + self.rPoint[card[1]] \ for card in cards]) def toOrigin(self, cards): cards = [self.color[card[0]] * 13 + card[1] - 2 for card in cards] return cards def modifyCardsOrder(self, cards, cardsType): if cardsType in ['STRAIGHT_FLUSH', 'FLUSH', 'STRAIGHT', 'HIGH_CARD']: return cards if cardsType == 'FOUR_OF_A_KIND': if cards[0][1] != cards[1][1]: cards = cards[1:] + cards[:1] elif cardsType == 'FULL_HOUSE': if cards[1][1] != cards[2][1]: cards = cards[2:] + cards[:2] elif cardsType == 'THREE_OF_A_KIND': if cards[1][1] != cards[2][1]: cards = cards[2:] + cards[:2] elif cards[0][1] != cards[1][1] and cards[3][1] != cards[4][1]: cards = cards[1:4] + cards[0:1] + cards[4:5] elif cardsType == 'TWO_PAIR': if cards[0][1] != cards[1][1]: cards = cards[1:] + cards[:1] elif cards[0][1] == cards[1][1] and cards[3][1] == cards[4][1]: cards = cards[0:2] + cards[3:5] + cards[2:3] elif cardsType == 'ONE_PAIR': if cards[3][1] == cards[4][1]: cards = cards[3:] + cards[:3] elif cards[2][1] == cards[3][1]: cards = cards[2:4] + cards[0:2] + cards[4:5] elif cards[1][1] == cards[2][1]: cards = cards[1:3] + cards[0:1] + cards[3:5] return cards # cards: (int<>, int<>, ...) def cardsType(self, cards): cards = self.sortedGroupList(cards) # 12 3 2 1 0 ---> 3 2 1 0 12 if cards[0][1] == 12 and cards[1][1] == 3 and \ cards[2][1] == 2 and cards[3][1] == 12 and cards[4][1] == 3: cards = a[1:] + a[:1] for key in self.type: if self.entries[key](cards): cards = self.modifyCardsOrder(cards, key) rank = self.type[key] * 13 ** 5 for idx, card in enumerate(cards): rank += card[1] * 13 ** (4 - idx) return rank, key, self.cardsBeautify(cards) # The small the better # cards: (int<card>, ...) 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 def restCards(self, usedCards): mask = [1] * 52 for card in usedCards: mask[card] = 0 return list(itertools.compress(range(52), mask)) def randomChoose(self, restCards, num): return random.sample(set(restCards), num) def C(self, n, k): return reduce(operator.mul, range(n - k + 1, n + 1)) / \ reduce(operator.mul, range(1, k +1)) # hold/ftr: ((string<color>, int<point>), ...) # point: 2-14 def loseRate(self, hold, ftr): hold = self.toOrigin(hold) ftr = self.toOrigin(ftr) cards = hold + ftr myRank = self.cardsRank(tuple(cards)) total = self.C(52 - len(cards), 2) count = 0 restCards = self.restCards(cards) for _hold in itertools.combinations(restCards, 2): for _cards in itertools.combinations(ftr + list(_hold), 5): _rank = self.cardsRank(tuple(_cards)) if _rank < myRank: count += 1 break return count * 100.0 / total # ftr/cards: (int<card>, ...) # Return: 1 if win, else 0 def emulate(self, myRank, ftr, cards, playerCount): ftr = list(ftr) cards = list(cards) ftr += self.randomChoose(self.restCards(cards), 5 - len(ftr)) players = [[]] * playerCount usedCards = [] minRank = self.maxRank for idx in range(playerCount): players[idx] = self.randomChoose(self.restCards(cards + ftr + usedCards), 2) rank = self.cardsRank(tuple(ftr + players[idx])) if rank < minRank: minRank = rank usedCards += players[idx] if myRank < minRank: return 1 else: return 0 # Hand Strength # hold/ftr: ((string<color>, int<point>), ...) def HS(self, hold, ftr, playerCount): hold = self.toOrigin(hold) ftr = self.toOrigin(ftr) cards = hold + ftr myRank = self.cardsRank(tuple(cards)) winCount = 0 for idx in range(self.emulateCount): winCount += self.emulate(myRank, tuple(ftr), tuple(cards), playerCount) return winCount * 1.000 / self.emulateCount # Rate of Return def RR(self, hold, ftr, playerCount, bet, pot): if bet == 0: return 2.0 HS = self.HS(hold, ftr, playerCount) return HS * (bet + pot) / bet, HS
import numpy from deuces import Card, Evaluator, Deck import itertools import pickle evaluator = Evaluator() pre_flop = pickle.load(open("preflop_scores.p", "rb")) for i in range(0, 1000000): deck = Deck() board = deck.draw(5) player1_hand = deck.draw(2) player2_hand = deck.draw(2) player1_hand.sort() p1_score = evaluator.evaluate(board, player1_hand) p2_score = evaluator.evaluate(board, player2_hand) key = tuple(player1_hand) if key not in pre_flop: pre_flop[key] = [0, 0] if p1_score < p2_score: pre_flop[key] = [pre_flop[key][0] + 1, pre_flop[key][1] + 1] elif p2_score < p1_score: pre_flop[key][1] += 1 else: pre_flop[key] = [pre_flop[key][0] + 1, pre_flop[key][1] + 2] # for key in pre_flop: # pre_flop[key] = pre_flop[key][0] / pre_flop[key][1]
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
player[i].hand_value=deck.draw(2) Card.print_pretty_cards(player[i].hand_value) ##for i in range(int(no_of_Players)): ## print "\nplayer[",i,"].hand_value=",player[i].hand_value ## print "player[",i,"].account_value=",player[i].account_value ## print "player[",i,"].score=",player[i].score card_allocation_module(no_of_Players) print "\n" ##player[0].hand_value=deck.draw(2) ##player[1].hand_value=deck.draw(2) Card.print_pretty_cards(board) ##Card.print_pretty_cards(player[0].hand_value) ##Card.print_pretty_cards(player[1].hand_value) print "\n" evaluator=Evaluator() for i in range(int(no_of_Players)): player[i].score=evaluator.evaluate(board,player[i].hand_value) player[i].rank=evaluator.get_rank_class(player[i].score) for i in range(int(no_of_Players)): print "Player ",i," hand rank = %d (%s)\n" % (player[i].score, evaluator.class_to_string(player[i].rank)) ##print "Player 2 hand rank = %d (%s)\n" % (player[1].score, evaluator.class_to_string(player[1].rank)) hands = [player[i].hand_value for i in range(int(no_of_Players))] evaluator.hand_summary(board, hands)
class Game: def __init__(self, player_list, chips, blinds): self.player_list = player_list self.player_num = len(player_list) #self.hands = [[] for i in range(len(player_list))] self.deck = Deck() self.evaluator = Evaluator() self.blinds = blinds self.chips = chips self.pot = [0 for x in range(0,self.player_num)] self.table_chips = 0 self.raise_counter = 0 self.table = [] self.strengths =[[], []] def dealCards(self): for i in range(0, self.player_num): self.player_list[i].hand = self.deck.draw(2) Card.print_pretty_cards(self.player_list[i].hand) def resetChips(self): for i in range(0, self.player_num): self.player_list[i].chips = self.chips self.player_list[i].resetBets def shuffleCards(self): self.deck = Deck() def clearTableChips(self): self.table_chips = 0 def resetPot(self): self.pot = 0 def rounds(self, round_num): if round_num == 1: print("The Flop") self.table += self.deck.draw(3) elif round_num == 2: print("The Turn") self.table += [self.deck.draw(1)] elif round_num == 3: print("The River") self.table += [self.deck.draw(1)] else: print("Showdown") Card.print_pretty_cards(self.table) for i in range(len(self.player_list)): self.strengths[i].append(self.player_list[i].calc_hand_strength(self)) #returns list of players remaining in hand in order of hand strength def handRank(self): scores = [] for i in range(0, self.player_num): if self.player_list[i].folded == False: strength = self.evaluator.evaluate(self.table, self.player_list[i].hand) scores.append([i, strength]) print self.player_list[i].name + ": " + self.evaluator.class_to_string(self.evaluator.get_rank_class(strength)) Card.print_pretty_cards(self.player_list[i].hand) scores = sorted(scores,key=itemgetter(1)) groups = groupby(scores, itemgetter(1)) result = [[item[0] for item in data] for (key, data) in groups] for i in result[0]: print self.player_list[i].name + " wins!" return result def play(self): # Gameplay is initilalized self.resetChips() # Position of dealer at the beginning dealer = 0 while True: self.shuffleCards() self.pot = [0 for x in range(0,self.player_num)] self.table_chips = 0 self.raise_counter = 0 self.table = [] self.strengths =[[], []] counter = 0 for i in range(self.player_num): if self.player_list[i].chips <= 0: counter += 1 else: self.player_list[i].folded = False if counter == self.player_num - 1: print "Game Over" break print "Next Round" self.player_list = np.roll(self.player_list, 1) min_bet = 0 # Round starts # People are dealt cards at the start of the round self.dealCards() # Small and Big blinds are put on the table self.player_list[(dealer + 1) % self.player_num].chips -= self.blinds[0] #self.player_list[(dealer + 1) % self.player_num].current_bet = self.blinds[0] print(self.player_list[(dealer + 1) % self.player_num].name + " pays small blind of " + str(self.blinds[0])) self.pot[(dealer + 1) % self.player_num] = self.blinds[0] self.player_list[(dealer + 2) % self.player_num].chips -= self.blinds[1] #self.player_list[(dealer + 2) % self.player_num].current_bet = self.blinds[1] print(self.player_list[(dealer + 2) % self.player_num].name + " pays big blind of " + str(self.blinds[1])) self.pot[(dealer + 2) % self.player_num] = self.blinds[1] #self.table_chips += self.blinds[1] + self.blinds[0] min_bet = self.blinds[1] people_in = self.player_num turn = 0 # Rounds of betting for j in xrange(0, 4): raise_counter = -10 place = dealer + 2 raise_const = 1 counter = 0 for i in range(self.player_num): if self.player_list[i].chips > 0: counter += 1 while raise_counter != min_bet: raise_counter = min_bet for i in xrange(place + 1, place + people_in + raise_const): if self.player_list[i % people_in].folded == True or self.player_list[i % people_in].chips == 0 or counter == 1: continue print("Current bet: " + str(min_bet)) self.player_list[i % people_in].printName() amount_bet = self.player_list[i % people_in].bet(min_bet,self.pot[i % people_in]) #still have to verify correct bet self.pot[i % people_in] += amount_bet tot = self.pot[i % people_in] ''' self.table_chips += amount_bet tot = amount_bet + self.player_list[i % people_in].current_bet self.player_list[i % self.player_num].current_bet += amount_bet print(self.player_list[i % people_in].chips) ''' if min_bet < tot: min_bet = tot place = i raise_const = 0 break #self.pot += self.table_chips #self.clearTableChips() #for i in xrange(0, self.player_num): # self.player_list[i].resetBets() turn += 1 self.rounds(turn) #distribute chips to winner(s) print self.strengths handRank = self.handRank() #print repr(handRank) + '\n' for winner in handRank: #print repr(winner) + '\n' #for tied winners, sort by the amount they've bet (least first) winner.sort(key = lambda x: self.pot[x]) #loop over tied winners, resolve smaller sidepots first for i in range(0,len(winner)): #loop over pot and grab their bet size from every other player amount_bet = self.pot[winner[i]] chips_won = 0 for j in range(0,len(self.pot)): if self.pot[j] > amount_bet: self.pot[j] -= amount_bet chips_won += amount_bet else: chips_won += self.pot[j] self.pot[j] = 0 #split chips proportionally among players that bet enough for this pot for j in range(i,len(winner)): self.player_list[winner[j]].chips += int(chips_won*(1/(len(winner)-i))) #print "player %d won %d chips \n" % (winner[j],chips_won*(1/(len(winner)-i))) print "Player %s won %d chips" % (self.player_list[winner[j]].name,chips_won*(1/(len(winner)-i))) for i in range(self.player_num): print self.player_list[i].chips print "\n"
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 + \ Card.get_rank_int(perm[2]) * 0.000001 front_lookup[prime_prod] = rank - kicker with open('res/front_lookup.p', 'wb') as f: pickle.dump(front_lookup, f)
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
for i in range(n): boards.append(deck.draw(m)) hands.append(deck.draw(2)) deck.shuffle() return boards, hands n = 10000 cumtime = 0.0 evaluator = Evaluator() boards, hands = setup(n, 5) for i in range(len(boards)): start = time.time() evaluator.evaluate(boards[i], hands[i]) cumtime += time.time() - start avg = float(cumtime / n) print "7 card evaluation:" print "[*] Deuces: Average time per evaluation: %f" % avg print "[*] Decues: Evaluations per second = %f" % (1.0 / avg) ### cumtime = 0.0 boards, hands = setup(n, 4) for i in range(len(boards)): start = time.time() evaluator.evaluate(boards[i], hands[i]) cumtime += time.time() - start
wins2 = 0 wins3 = 0 wins4 = 0 ties1 = 0 ties2 = 0 ties3 = 0 ties4 = 0 total_boards = 0 ans5 = input("\nHow many boards do you want to simulate? ") num_boards = ans5 while num_boards != 0 and type(num_boards) == int: for i in range(0,num_boards): total_boards += 1 new_leftovers = copy.deepcopy(leftovers) board = [new_leftovers.pop(random.randint(0,len(new_leftovers)-1)) for i in range(5)] s1 = evaluator.evaluate(board, hand1) s2 = evaluator.evaluate(board, hand2) s3 = evaluator.evaluate(board, hand3) s4 = evaluator.evaluate(board, hand4) s = [s1,s2,s3,s4] # compute number of winners winners = [] if s1 == min(s): winners += [s1] if s2 == min(s): winners += [s2] if s3 == min(s): winners += [s3] if s4 == min(s): winners += [s4] # cases with ties....
class Game: def __init__(self, player_list, chips, blinds, num_hands=100): self.player_list = player_list self.player_num = 2 self.num_hands = num_hands self.deck = Deck() self.evaluator = Evaluator() self.blinds = blinds self.chips = chips self.pot = [0 for x in range(0, 2)] self.table_chips = 0 self.raise_counter = 0 self.table = [] self.bet_round = 0 self.strengths =[[], []] self.last_bets = [None,None] self.times = dict([('main',{'total':0,'count':0}),('strength',{'total':0,'count':0})]+[(player.name,{'total':0,'count':0}) for player in player_list]) # Function for dealing cards to every player def dealCards(self): for i in range(2): self.player_list[i].hand = self.deck.draw(2) print self.player_list[i].name Card.print_pretty_cards(self.player_list[i].hand) # Reset player chip amounts and bets def resetChips(self): for i in range(2): self.player_list[i].chips = self.chips self.player_list[i].resetBets # Shuffle deck def shuffleCards(self): self.deck = Deck() # Clear chips off table def clearTableChips(self): self.table_chips = 0 # Reset the pot to 0 def resetPot(self): self.pot = 0 # Reset every player's flag that indicates folding def resetFolds(self): for player in self.player_list: player.folded = False # Adds one card to the table and prints cards each time the round ends def rounds(self): round_num = self.bet_round if round_num == 1: print("The Flop") self.table += self.deck.draw(3) elif round_num == 2: print("The Turn") self.table += [self.deck.draw(1)] elif round_num == 3: print("The River") self.table += [self.deck.draw(1)] else: print("Showdown") Card.print_pretty_cards(self.table) for i in range(2): self.strengths[i].append(self.player_list[i].calc_hand_strength(self)) #returns list of players remaining in hand in order of hand strength def handRank(self): scores = [] for i in range(2): if self.player_list[i].folded == False: strength = self.evaluator.evaluate(self.table, self.player_list[i].hand) scores.append([i, strength]) print self.player_list[i].name + ": " + self.evaluator.class_to_string(self.evaluator.get_rank_class(strength)) Card.print_pretty_cards(self.player_list[i].hand) scores = sorted(scores,key=itemgetter(1)) groups = groupby(scores, itemgetter(1)) result = [[item[0] for item in data] for (key, data) in groups] for i in result[0]: print self.player_list[i].name + " wins!" return result def distribute_chips(self, order=0): #keep track of winnings for each player so we can pass it to bots winnings = self.player_num*[0] if order == 0: handRank = self.handRank() else: handRank = order if self.player_list[0].folded == False and self.player_list[1].folded == False: if self.pot[0] > self.pot[1]: self.player_list[0].chips += self.pot[0] - self.pot[1] self.pot = [min(self.pot), min(self.pot)] elif self.pot[0] < self.pot[1]: self.player_list[1].chips += self.pot[1] - self.pot[0] self.pot = [min(self.pot), min(self.pot)] #print repr(handRank) + '\n' if len(handRank[0]) ==1: print "Player %s won %d chips" % (self.player_list[handRank[0][0]].name,self.pot[handRank[1][0]]) self.player_list[handRank[0][0]].chips += sum(self.pot) winnings[handRank[0][0]] = self.pot[handRank[1][0]] print "Player %s lost %d chips" % (self.player_list[handRank[1][0]].name,self.pot[handRank[1][0]]) #self.player_list[handRank[1][0]].chips -= self.pot[handRank[1][0]] winnings[handRank[1][0]] = -self.pot[handRank[1][0]] else: print "Player %s won %d chips" % (self.player_list[handRank[0][0]].name,0) print "Player %s won %d chips" % (self.player_list[handRank[0][1]].name,0) self.player_list[0].chips += self.pot[0] self.player_list[1].chips += self.pot[1] for i in range(2): print self.player_list[i].name + ': ' + str(self.player_list[i].chips) print "\n" for j,i in enumerate(self.player_list): i.end_round(self, winnings[j]) # Starts one game of poker def play(self): t1 = time.time() # Gameplay is initilalized self.resetChips() # Position of dealer at the beginning dealer = 0 for num_hand in range(self.num_hands): self.shuffleCards() self.pot = [0 for x in range(2)] self.table_chips = 0 self.raise_counter = 0 self.table = [] self.strengths =[[], []] counter = 0 for i in range(2): if self.player_list[i].chips > 0: self.player_list[i].folded = False else: self.player_list[i].folded = True if self.player_list[0].folded == True or self.player_list[1].folded == True: print "Game Over" for j,i in enumerate(self.player_list): if isinstance(i, Bot): i.end() break for j,i in enumerate(test.player_list): if isinstance(i, rl_bot.RLBot): i.learner.round = 0 print "Next Round" self.player_list = np.roll(self.player_list, 1) self.last_bets = np.roll(self.last_bets,1) # Round starts # People are dealt cards at the start of the round self.dealCards() # Small and Big blinds are put on the table print(self.player_list[(dealer + 1) % 2].name + " pays small blind of " + str(self.blinds[0])) self.player_list[(dealer + 1) % 2].chips -= self.blinds[0] self.pot[(dealer + 1) % 2] = self.blinds[0] print(self.player_list[dealer % 2].name + " pays big blind of " + str(self.blinds[1])) self.pot[dealer % 2] = min([self.player_list[dealer % 2].chips,self.blinds[1]]) self.player_list[dealer % 2].chips -= min([self.player_list[dealer % 2].chips,self.blinds[1]]) min_bet = self.blinds[1] self.bet_round = 0 # Rounds of betting for j in range(4): raise_counter = -10 raise_const = 1 counter = 0 if self.player_list[0].folded == True: self.distribute_chips([[1],[0]]) break elif self.player_list[1].folded == True: self.distribute_chips([[0],[1]]) break for i in range(2): if self.player_list[i].chips > 0: counter += 1 while raise_counter != min_bet: raise_counter = min_bet for i in xrange(dealer + 1, dealer + 2 + raise_const): if self.player_list[i % 2].folded == True or self.player_list[i % 2].chips == 0 or counter == 1: continue print("Current bet: " + str(min_bet)) self.player_list[i % 2].printName() #track amount of time for player t2 = time.time() amount_bet = self.player_list[i % 2].bet(min_bet, self.pot[i % 2], self.times, self) self.times[self.player_list[i % 2].name]['count'] += 1 self.times[self.player_list[i % 2].name]['total'] += time.time() - t2 self.last_bets[i % 2] = amount_bet if self.player_list[0].folded == True or self.player_list[1].folded == True : break #still have to verify correct bet self.pot[i % 2] += amount_bet self.player_list[i%2].chips -= amount_bet if min_bet < self.pot[i % 2]: min_bet = self.pot[i % 2] dealer = i raise_const = 0 break self.bet_round += 1 self.rounds() #distribute chips to winner(s) if self.player_list[0].folded == False and self.player_list[1].folded == False: self.distribute_chips() self.resetFolds() #update times self.times['main']['count'] += 1 self.times['main']['total'] += time.time() - t1
class PokerMath(): #Populate dict with card values to save processing time later #Also add all integers to a numpy array for quick processing 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() def is_best_hand(self, hole, other_hands, board): #print board my_score = self.evaluator.evaluate(hole, board) for hand in other_hands: if my_score > self.evaluator.evaluate(hand, board): #greater number = worse hand return False return True def hand_strength(self, hole, board, num_players, trials = 1000, possible_hands = [], current=False): #convert cards to proper format temp_hole = [] for card in hole: temp_hole.append(self.card_dict[card]) hole = temp_hole temp_board = [] for card in board: temp_board.append(self.card_dict[card]) board = temp_board temp_possible_hands = [] for hand in possible_hands: temp_possible_hands.append([self.card_dict[hand[0]], self.card_dict[hand[1]]]) possible_hands = temp_possible_hands wins = 0. for i in range(trials): other_hands = [] temp_deck = self.deck[:] #make a copy of the deck! #remove hole and board cards from deck for card in board + hole: temp_deck.remove(card) #shuffle the deck random.shuffle(temp_deck) #deal out cards to the other players if len(possible_hands) == 0: for i in range(num_players): other_hands.append([temp_deck.pop(),temp_deck.pop()]) else: hands = possible_hands[:] for i in range(num_players): rand_hand = random.choice(hands) ''' Card.print_pretty_cards(hole) Card.print_pretty_cards(rand_hand) Card.print_pretty_cards(temp_board) print '----------' ''' other_hands.append(rand_hand) hands.remove(rand_hand) temp_deck.remove(rand_hand[0]) temp_deck.remove(rand_hand[1]) #deal board cards if not current: temp_board = board[:] for i in range(0 , 5 - len(board)): temp_board.append(temp_deck.pop()) #check if we won if self.is_best_hand(hole, other_hands, temp_board): wins += 1 return wins / trials
class Player(): # strategy is a function def __init__(self, strategy, buy_in, n_players, ID=0): self.getAction = strategy self.n_opponents = n_players-1 self.earnings = 0.0 self.states = [buy_in, 0, None] # [current funds, bet amount, action] self.id = ID self.evaluator = Evaluator() self.n_raise = 0 self.n_call = 0 self.n_games = 0 self.action = None def setHoleCards(self, cards): assert len(cards) == 2 self.hole_cards = cards def setCommunityCards(self, cards): assert len(cards) == 5 self.community_cards = cards # return score of best hand made up of hole cards and community cards 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) # update states upon winning a round # 0 = Current funds, 1 = bet amount, 2 = Action def winUpdate(self, winnings): # accounting for how much you yourself put into the pot self.earnings += (winnings - self.states[1]) self.states[0] += winnings self.states[1] = 0 self.states[2] = None # update states upon losing a round, returns loss # 0 = Current funds, 1 = bet amount, 2 = Action def loseUpdate(self): loss = self.states[1] self.earnings -= loss self.states[1] = 0 self.states[2] = None return -loss # return tag summarizing two card hand as a string def getHandTag(self): card1Num, card1Suit = self.hole_cards[0][0], self.hole_cards[0][1] card2Num, card2Suit = self.hole_cards[1][0], self.hole_cards[1][1] if card1Num == card2Num: return card1Num + card2Num card1Val = cardRank[card1Num] card2Val = cardRank[card2Num] if card1Suit == card2Suit: if card1Val > card2Val: return card1Num + card2Num + 's' else: return card2Num + card1Num + 's' else: if card1Val > card2Val: return card1Num + card2Num + 'o' else: return card2Num + card1Num + 'o' def get_preflop_odds(self,preflop_odds_table,hole_cards): """ This functions searches the preflop_odds_table for the winning odds of a given preflop hand given by the "hole_cards" for a given number of players """ # First, we need to assign a proper "tag" to be searched in the table card1 = list(hole_cards[0]) card2 = list(hole_cards[1]) # If the card number is the same, they cannot be suited if card1[0] == card2[0]: tag=str(card1[0])+str(card2[0]) odds=preflop_odds_table[tag][0][self.n_opponents-1] else: try: # Checking if suit is the same if card1[1] == card2[1]: tag=str(card1[0])+str(card2[0])+'s' else: tag=str(card1[0])+str(card2[0])+'o' odds=preflop_odds_table[tag][0][self.n_opponents-1] except KeyError: # Higher value should come first in the tag if card1[1] == card2[1]: tag=str(card2[0])+str(card1[0])+'s' else: tag=str(card2[0])+str(card1[0])+'o' odds=preflop_odds_table[tag][0][self.n_opponents-1] return odds def getAction(self, game, call, raise_amt): pass