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 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 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 __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 }
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 __init__(self): # All possible card ranks (0-12 inclusive) # + 13 - used for board cards when they have not been dealt # all_card_rank_values = np.array([x for x in range(14)]).reshape(14, 1) # All possible suit values (0 - 4 inclusive) # + 9 - used for board cards when they have not been dealt all_card_suit_values = np.array([1, 2, 4, 8, 9]).reshape(5, 1) self.rank_enc = OneHotEncoder(handle_unknown='error', categories='auto') self.rank_enc.fit(all_card_rank_values) self.suit_enc = OneHotEncoder(handle_unknown='error', categories='auto') self.suit_enc.fit(all_card_suit_values) # Put in dummy variables for undealt cards self.table_card_ranks = [0 for x in range(5)] self.table_card_suits = [0 for x in range(5)] self.evaluator = Evaluator() self.min_max_scaling = lambda a, b, min_x, max_x, x: a + ( (x - min_x) * (b - a)) / (max_x - min_x) self.preflop_suited_array = np.loadtxt( "./preflop_odds/suited_pair_scores.csv", delimiter=',') self.preflop_unsuited_array = np.loadtxt( "./preflop_odds/unsuited_pair_scores.csv", delimiter=',') self.normalise_preflop_arrays()
def __init__(self, preflop_tight_loose_threshold, aggresive_passive_threshold, bet_tolerance): self.preflop_tight_loose_threshold = preflop_tight_loose_threshold self.aggresive_passive_threshold = aggresive_passive_threshold self.bet_tolerance = bet_tolerance # deuces self.evaluator = Evaluator() self.deck = Deck()
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 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 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 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 declare_action(self, valid_actions, hole_card, round_state): choice = self.__choice_action(valid_actions) action = choice["action"] amount = choice["amount"] if action == "raise": amountToRaise = 40 amount = amountToRaise #rand.randrange(amount["min"], max(amount["min"], amount["max"]) + 1) opponentAgressivnessScore = opponentAgressivness(self) opponentAgressivnessScoreLast7Round = opponentAgressivness(self, 2) card1InString, card2InString = hole_card[0], hole_card[1] cardObject1 = cardToCardObject(card1InString) cardObject2 = cardToCardObject(card2InString) pot, levelOfBetting, cardsOnBoard, roundCount, isOnSmallblind, isOnBigBlind, smallBlindAmount, bigBlindAmount, stackOfPlayer, stackOfOpponent = extractInfoFromState(self.uuid, round_state) cardsOnBoardObjects = getBoardToCardsObject(cardsOnBoard) allCardsObjectOnBoard = cardsOnBoardObjects[:2 + levelOfBetting - 1] evaluator = Evaluator() if len(cardsOnBoardObjects) > 0: # if there is any card on board - so after flop every case handStrengthLibrary = evaluate(evaluator, allCardsObjectOnBoard, cardObject1, cardObject2) else: # preFLop handStrengthLibrary = 0 sklanskyClass = getSklanskyClass(card1InString, card2InString) cards = getAllCards() cards.remove(cardObject1) cards.remove(cardObject2) for boardCard in cardsOnBoardObjects: cards.remove(boardCard) evaluator = Evaluator() if len(cardsOnBoardObjects) > 0: HS = handStrength(cardsOnBoardObjects, cardObject1, cardObject2, cards, evaluator) else: HS = 0 EHS, PPOT, NPOT = 0,0,0 # if len(cardsOnBoardObjects) > 0: # if there is any card on board - so after flop every case # EHS, HS, PPOT, NPOT = effectiveHandStrength(cardsOnBoardObjects, handStrength, cardObject1, cardObject2) # else: # EHS, HS, PPOT, NPOT = 0, 0, 0, 0 # handle -BigBlind and smallBlind if levelOfBetting == 1 and action != "fold": if isOnSmallblind: realAmountToPlay = amount - smallBlindAmount elif isOnBigBlind: realAmountToPlay = amount - bigBlindAmount else: # no blind realAmountToPlay = amount else: realAmountToPlay = amount addRowToHistory(self.historyDF, [self.hashOfGame, self.uuid, hole_card[0], hole_card[1], action, realAmountToPlay, pot, levelOfBetting, cardsOnBoard, roundCount, isOnSmallblind, isOnBigBlind , smallBlindAmount, bigBlindAmount, stackOfPlayer, stackOfOpponent, sklanskyClass, EHS, HS, PPOT, NPOT, handStrengthLibrary, opponentAgressivnessScore, opponentAgressivnessScoreLast7Round]) return action, amount
def build(self, testMode=True): """ Initiate objects and views. """ ''' init game objects ''' self.deck = Deck() self.evaluator = Evaluator() self.player = [] self.player.append(Player(0)) self.player.append(Player(1)) # board stands for public cards on board self.board = Board() # In test mode, both player select right-most cards for the turn automatically self.testMode = testMode ''' create view objects ''' # Scatter that can be rotated to display players scatter_bot = ScatterLayout(do_rotation=False, do_translation=False, do_scale=False, size_hint=(1, 1), pos_hint={ 'x': 0, 'y': 0 }, rotation=0) # For player on top, the widget rotates 180 degree scatter_top = ScatterLayout(do_rotation=False, do_translation=False, do_scale=False, size_hint=(1, 1), pos_hint={ 'x': 0, 'y': 0 }, rotation=180) box = PlayerDeck() box2 = PlayerDeck() publicArea = PublicArea() box.build(self, "player1", 0, self.testMode) box2.build(self, "player2", 1, self.testMode) publicArea.build() scatter_bot.add_widget(box) scatter_top.add_widget(box2) self.add_widget(scatter_bot) self.add_widget(scatter_top) self.add_widget(publicArea) # register id of view objects self.ids[box.id] = box self.ids[box2.id] = box2 self.ids[publicArea.id] = publicArea
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 is_winner(self): # This function return 1 if the player wins, 0 if it is a draw, and -1 if the opponent wins. try: player_hand_str = Evaluator().evaluate(self.flop_cards, self.player_cards) opponent_hand_str = Evaluator().evaluate(self.flop_cards, self.opponent_cards) except TypeError, e: print( 'ERROR: Something went wrong. Make sure that all required cards are defined.' )
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 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 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 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 __str__(self): result = "\n\n ############## Population %d ##############\n" %(self.number) bestResult = 0 evaluator = Evaluator() for player_hand in self.population: result += str(player_hand) + "\n" currentResult = evaluator._five(player_hand.hand) if (currentResult > bestResult): bestResult = currentResult p_class = evaluator.get_rank_class(bestResult) result += "\n Best solution: %s " %(evaluator.class_to_string(p_class)) return result
def calculate_roulette(self): evaluator = Evaluator() for player_hand in self.population: fitness = evaluator._five(player_hand.hand) self.sum_of_fitness += fitness #Calculate roulette values for player_hand in self.population: fitness = float(evaluator._five(player_hand.hand)) self.roulette.append(fitness/self.sum_of_fitness*100) return self.roulette
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 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 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 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 __init__(self, smallBlind, bigBlind, maxBuyIn): """ Constructor accepts blinds and maximum table buy in as integers. """ self._players = [] # players at the table self._playing = [] # players who are not bankrupt self._sitOut = [] # players who have gone bankrupt self._dealer = 0 # position of dealer in self._playing self._eval = Evaluator() if type(smallBlind) != int or type(bigBlind) != int or type( maxBuyIn) != int: raise Exception('Parameters must be integer number of chips.') self._smallBlind = smallBlind self._bigBlind = bigBlind self._maxBuyIn = maxBuyIn
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])
def __init__(self, bots, initial_credits=2000, num_decks=1, small_blind_amount=1, seed=None): self.players = [] self.credits = {} self.id = {} self.deck = Deck() self.evaluator = Evaluator() # big blind amount is 2x small_blind_amount self.small_blind_amount = small_blind_amount # initialize randomness if seed is None: random.seed() # seed with, hopefully, /dev/urandom seed = random.randint(0, 2**32) self.output("random seed: %d" % seed) random.seed(seed) for id, bot in enumerate(bots): bot_instance = bot(id=id, credits=initial_credits, small_blind_amount=self.small_blind_amount, big_blind_amount=self.big_blind_amount) self.players.append(bot_instance) self.id[bot_instance] = id self.credits[bot_instance] = initial_credits bot_instance.credits_table = self.credits self.active_players = copy.copy(self.players)
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 __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
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 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 __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 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 __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 }
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)
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
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
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
deck = Deck() boards = [] hands = [] 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)
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 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 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
# playing the game... keep_playing = "Yes" while keep_playing == "Yes": _=os.system("clear") print "Let's play a poker hand!" print "\nOK here are the teams and their starting chips:" print "\n%s TEAM has %d chips" % (team1, team1chips) print "%s TEAM has %d chips" % (team2, team2chips) print "%s TEAM has %d chips" % (team3, team3chips) print "%s TEAM has %d chips" % (team4, team4chips) print "\nWow nice chips!" # new deck deck = Deck() deck.shuffle() evaluator = Evaluator() print "\nFirst we deal 2 cards to each team..." ans3 = raw_input("\nHit <enter> to see the hands: ") # random board and hands hand1 = deck.draw(2) hand2 = deck.draw(2) hand3 = deck.draw(2) hand4 = deck.draw(2) leftovers = deck.draw(44) # print the hands _=os.system("clear") print "%s TEAM has hand " % team1 Card.print_pretty_cards(hand1) print "\n%s TEAM has hand " % team2 Card.print_pretty_cards(hand2) print "\n%s TEAM has hand " % team3
from __future__ import division 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:
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
def is_straight(cards): if len(cards) < 5: return False rank = evaluator.evaluate(cards, []) rank_class = evaluator.get_rank_class(rank) 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)
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"
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