def list_to_pretty_str(card_ints): output = " " for i in range(len(card_ints)): c = card_ints[i] if i != len(card_ints) - 1: output += Card.int_to_pretty_str(c) + "," else: output += Card.int_to_pretty_str(c) + " " return output
def evaluate(self, board, hand): dhand = [] dboard = [] for c in board: dcard = DCard.new(repr(c)) dboard.append(dcard) for c in hand.cards(): dcard = DCard.new(repr(c)) dhand.append(dcard) return self.e.evaluate(dboard, dhand)
def suited3(hand): """Are there three or more of any one suit? If yes, return the cards in the most populous suit. """ L = [0] * 4 Lc = [] for c in hand: suit = int(log(Card.get_suit_int(c), 2)) # 0, 1, 2, 3 L[suit] += 1 if max(L) >= 3: suit_to_pull = 2 ** L.index(max(L)) # deuces reps as 1, 2, 4, 8 for c in hand: if Card.get_suit_int(c) == suit_to_pull: Lc.append(c) return Lc
def resolve_game(self, players): # print('Community cards: ', end='') # Card.print_pretty_cards(self.community) if len(players) == 1: players[0].refund(sum(self._side_pots)) # print('Player', players[0].playerID, 'wins the pot (',sum(self._side_pots),')') self._totalpot = 0 else: # compute hand ranks print("Board: ", Card.print_pretty_cards(self.community)) for player in players: player.handrank = self._evaluator.evaluate( player.hand, self.community) print("Player: {}".format(player.playerID), Card.print_pretty_cards(player.hand)) # trim side_pots to only include the non-empty side pots temp_pots = [pot for pot in self._side_pots if pot > 0] # compute who wins each side pot and pay winners for pot_idx, _ in enumerate(temp_pots): # print('players last pots', [(p.playerID, p.lastsidepot) for p in players]) # find players involved in given side_pot, compute the winner(s) pot_contributors = [ p for p in players if p.lastsidepot >= pot_idx ] winning_rank = min([p.handrank for p in pot_contributors]) winning_players = [ p for p in pot_contributors if p.handrank == winning_rank ] for player in winning_players: split_amount = int(self._side_pots[pot_idx] / len(winning_players)) if not self._quiet: print( 'Player', player.playerID, 'wins side pot (', int(self._side_pots[pot_idx] / len(winning_players)), ')') player.refund(split_amount) self._side_pots[pot_idx] -= split_amount # any remaining chips after splitting go to the winner in the earliest position if self._side_pots[pot_idx]: earliest = self._first_to_act( [player for player in winning_players]) earliest.refund(self._side_pots[pot_idx])
def __init__(self, card_string): self.card_string = card_string suits = "shdc" numbers = "AKQJT98765432" self.card_number = suits.find(card_string[1]) + numbers.find(card_string[0]) * 4 + 1 # specialKEval ^ offset by one self.number = numbers[::-1].find(card_string[0]) + 2 self.suit = card_string[1] self.rank = dCard.new(card_string)
def print_table(self, table_state): print('Stacks:') players = table_state.get('players', None) for player in players: print(player[4], ': ', player[1], end='') if player[2] == True: print('(P)', end='') if player[3] == True: print('(Bet)', end='') if player[0] == table_state.get('button'): print('(Button)', end='') if players.index(player) == table_state.get('my_seat'): print('(me)', end='') print('') print('Community cards: ', end='') Card.print_pretty_cards(table_state.get('community', None)) print('Pot size: ', table_state.get('pot', None)) print('Pocket cards: ', end='') Card.print_pretty_cards(table_state.get('pocket_cards', None)) print('To call: ', table_state.get('tocall', None))
def print_table(self, table_state): print("Stacks:") players = table_state.get("players", None) for player in players: print(player[4], ": ", player[1], end="") if player[2] == True: print("(P)", end="") if player[3] == True: print("(Bet)", end="") if player[0] == table_state.get("button"): print("(Button)", end="") if players.index(player) == table_state.get("my_seat"): print("(me)", end="") print("") print("Community cards: ", end="") Card.print_pretty_cards(table_state.get("community", None)) print("Pot size: ", table_state.get("pot", None)) print("Pocket cards: ", end="") Card.print_pretty_cards(table_state.get("pocket_cards", None)) print("To call: ", table_state.get("tocall", None))
def get_score(self, stagec): """ Returns a score that adjusts for their average hand. return > 0: our hand is better on average by # return < 0: our hand is worse on average by # """ if self.last_hand_count == len(self.table.hand)+len(self.player.hand) or len(self.table.getHand()) == 0: return self.last_hand_score else: self.last_hand_count = len(self.table.hand) + len(self.player.hand) score = 0 base_score = self.ev.evaluate(self.table.getHand(), self.player.getHand()) table_adjusted = tuple(self.table.getHand()) # change deck into deuces cards deck_adjusted = (dCard.new(x) for x in self.deck.cards) # all possbile hands possibilities = itertools.combinations(deck_adjusted, 2) length = len(self.table.hand) + len(self.player.hand) scoresum = 0 num = 0 for p in possibilities: scoresum += self.ev.hand_size_map[length](table_adjusted+p) num += 1 scoresum /= float(num) # get our score adjusted for what they could have self.log.debug(" Base score: {0}".format(base_score)) self.log.debug(" Score average: {0}".format(scoresum)) self.log.debug(" Relative Score: {0}".format(base_score - scoresum)) self.log.debug(" Confidence: {0}".format(self.config["confidence"])) score = (base_score + stagec["score_offset"]) self.log.debug(" Offset Score: {0}".format(score)) if score < 0: score /= self.config["confidence"] else: score *= self.config["confidence"] score -= scoresum self.last_hand_score = score self.log.debug(" Score: {0}".format(score)) return score
def all_hands_in_range(list_of_str): """Return a list of lists of deuces objects, to answer 'What detailed hole cards (combos) are in range provided?' """ total_hands = [] for s in list_of_str: if s[0] == s[1]: # pairs (6 for each) a = [s[0] + 's', s[0] + 'h', s[0] + 'd', s[0] + 'c'] for pair_strings in combinations(a, 2): total_hands += [[Card.new(pair_strings[0]), Card.new(pair_strings[1])]] elif 's' in s: # suited (4 for each) for suit in 'shdc': total_hands += [[Card.new(s[0] + suit), Card.new(s[1] + suit)]] else: # offsuit (12 for each) a = [s[0] + 's', s[0] + 'h', s[0] + 'd', s[0] + 'c'] b = [s[1] + 's', s[1] + 'h', s[1] + 'd', s[1] + 'c'] for s1, s2 in product(a, b): if s1[1] == s2[1]: continue # because suited total_hands += [[Card.new(s1), Card.new(s2)]] return total_hands
def parse_table_state(self, table_state): potmoney = table_state.get('pot') betmoney = table_state.get('tocall') card1 = table_state.get('pocket_cards')[0] card2 = table_state.get('pocket_cards')[1] community = table_state.get('community') if len(community) < 3: flop1 = [0, 0] flop2 = [0, 0] flop3 = [0, 0] else: flop1 = [ Card.get_rank_int(community[0]), Card.get_suit_int(community[0]) ] flop2 = [ Card.get_rank_int(community[1]), Card.get_suit_int(community[1]) ] flop3 = [ Card.get_rank_int(community[2]), Card.get_suit_int(community[2]) ] if len(community) < 4: turn = [0, 0] else: turn = [ Card.get_rank_int(community[3]), Card.get_suit_int(community[3]) ] if len(community) < 5: river = [0, 0] else: river = [ Card.get_rank_int(community[4]), Card.get_suit_int(community[4]) ] state = [ float(potmoney / 50000), float(betmoney / 50000), float(Card.get_rank_int(card1) / 13), float(Card.get_suit_int(card1) / 4), float(Card.get_rank_int(card2) / 13), float(Card.get_suit_int(card2) / 4), float(flop1[0] / 13), float(flop1[1] / 4), float(flop2[0] / 13), float(flop2[1] / 4), float(flop3[0] / 13), float(flop3[1] / 4), float(turn[0] / 13), float(turn[1] / 4), float(river[0] / 13), float(river[1] / 4) ] players = table_state.get('players', None) for player in players: state.extend([ float(player[4] / 10), float(player[1] / 5000), float(player[2]), float(player[3]), float(player[0]) ]) if len(players) < 10: for notplaying in range(0, 10 - len(players)): state.extend([0., 0., 0., 0., 0.]) return state
### find_pcts() does 10,000 iterations by default. And we call it 4 * ### 20 * 4 times = 3.2 million iters altogether. 4 showdowns (graph) * ### 20 hands (lines on each graph) * 4 streets (points on each line). ### Takes rather a while. 5 min on Intel Core i5 at 3.1 GHz (really ### only uses 1 core though). In other words, one call of find_pcts() ### takes about 1 sec. Seems maybe 15 - 20 min on MacBook Pro 2.7 GHz ### Intel Core i7? ### ### Now with 4 processes, 1:30 on Core i5 3.1 GHz. 8 million iters. ### Implies about 8900 per sec. 4 min on MacBook Pro 2.7 GHz Intel ### Core i7. myid = randint(1,999) * 100 p1 = [Card.new('As'), Card.new('Ac')] villain = {'jqs' : [Card.new('Js'), Card.new('Qs')] , 'aks' : [Card.new('Ad'), Card.new('Kd')] , 'kqs' : [Card.new('Ks'), Card.new('Qs')] } for villain_str, p2 in villain.iteritems(): for i in range(5): main_deck = Deck() board = [] for j, ncards in enumerate([0, 3, 1, 1]): row = [villain_str, i + myid, j] add_to_board = draw_sure(main_deck, ncards, p1 + p2 + board) board = board + add_to_board ps = find_pcts(p1, p2, start_b = board)
def board_to_string(board): result = "" for card in board: result += "{} ".format(Card.int_to_pretty_str(card)) return result
def card_str(self): return '{}, {}'.format(Card.int_to_pretty_str(self.cards[0]), Card.int_to_pretty_str(self.cards[1]))
def getHumanHand(self): '''borkd''' return ' '.join([dCard.int_to_pretty_str(x) for x in self.getHand()])
### Takes about 38 sec on Intel Core i5 at 3.1 GHz. ### 1 min on my macbook (2.7ghz i7). for n in range(75000): deck = Deck() ## Deal the hole cards ring = [] for i in range(9): p = deck.draw(2) p.sort(reverse=True) ring.append(p) ## Deal board board = deck.draw(5) ## Show down [winners, winrank] = ring_winners(board, ring) for i, hole in enumerate(ring): hole_str = Card.int_to_str(hole[0])[0] + Card.int_to_str(hole[1])[0] if Card.get_suit_int(hole[0]) == Card.get_suit_int(hole[1]): hole_str += 's' else: hole_str += 'o' wl = '' if i in winners: wl = 'w' else: wl = 'l' print hole_str + ',' + winrank + ',' + wl + ',' + str(n) + ',' + str(i)
def manage_winnings(self): ''' Function that checks who the winners are and distributes the pot acordingly. ''' if self.table.state < 4: # A single player remained, the rest have folded # Go through each bet, if they dont belong to the un-folded player, # add them upp so we can transfer them to the winner. winnings = 0 winner = None for player in self.table.bets[self.table.state]: for state in xrange(self.table.state + 1): winnings += sum(self.table.bets[state][player]) if player.state != 6: winner = player winner.bankroll += winnings winner.signal_end(win=True, amt=winnings, nr_round=self.nr_round) log('WINNER: %s %s' % (winner.name, winnings)) for p in self.table.players: if p is not winner: lost_amt = 0 for bets in self.table.bets.values(): lost_amt += sum(bets[p]) p.signal_end(win=False, amt=lost_amt, nr_round=self.nr_round) else: # A so called 'showdown' e = Evaluator() dboard = [] for card in self.table.family_cards: dboard.append(DCard.new(repr(card))) vals = {} for p in self.table.players: vals[p] = [0, 0] for p in self.table.players: for s in self.table.bets: vals[p][0] += sum(self.table.bets[s][p]) hand = [ DCard.new(repr(p.hand.cards()[0])), DCard.new(repr(p.hand.cards()[1])), ] vals[p][1] = e.evaluate(dboard, hand) if p.state != 6 else 9000 to_distribute = sum([v[0] for v in vals.values()]) best_card_score = min([v[1] for v in vals.values()]) winners = [ p for p, v in vals.iteritems() if v[1] == best_card_score ] winnings = 0 for p, v in vals.iteritems(): if p in winners: p.bankroll += v[0] winnings += v[0] else: for w in winners: w.bankroll += int(v[0]/len(winners)) winnings += int(v[0]/len(winners)) for w in winners: w.signal_end( win=True, amt=int(winnings/len(winners)), nr_round=self.nr_round) for p in self.table.players: if p not in winners: lost_amt = 0 for bets in self.table.bets.values(): lost_amt += sum(bets[p]) p.signal_end(win=False, amt=lost_amt, nr_round=self.nr_round) log('WINNER(s): %s %s' % (', '.join([w.name for w in winners]), int(winnings/len(winners))))
deuces_plus = 'AA KK QQ JJ TT 99 88 77 66 55 44 33 22'.split() bway = 'A K Q J T'.split() ATB = [] for i in bway: for j in bway: if i == j: continue elif bway.index(i) > bway.index(j): ATB.append(j + i) elif bway.index(i) < bway.index(j): ATB.append(i + j + 's') assert len(ATB) == 20 ## Input vars: board = [Card.new('Qs'), Card.new('Td'), Card.new('4c')] range_list = ['AA', 'KK', 'QQ', 'AK', 'AKs', 'KQ', 'KQs', 'JJ', '33', '22', 'A4', '99', 'AJ', 'KJ'] range_list = deuces_plus + ATB ## tricky ones highlighted: ## 1 2 3 4 5 6 7 8 9 ## sf quad boat flush straight trip set 2p overp tp 1.5p mp wp overc ah nmh ## ^^^^^^^^ ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^ print "Range:", range_list print "Board:", pr(board) print print add_margins(range_plot(range_list))
import numpy as np from deuces.deuces import Card board = [ Card.new('Ah'), Card.new('Kd'), Card.new('Jc') ] hand = [ Card.new('Qs'), Card.new('Th') ] Card.print_pretty_cards(board + hand)
from deuces.deuces import Card, Deck from pokermodules.nuts import nut_hand from sys import argv if '--test' in argv: pause = False else: pause = True for i in range(15): deck = Deck() flop = deck.draw(3) turn = [deck.draw(1)] river = [deck.draw(1)] for board in [flop, flop + turn, flop + turn + river]: Card.print_pretty_cards(board) if pause: dummy = raw_input('Think hard... ') print "Nuts:", nut_hand(board) print
def extract_ranks(hole, board): hrs = [Card.get_rank_int(c) for c in hole] brs = [Card.get_rank_int(c) for c in board] brs.sort(reverse = True) # high card is index 0 return hrs, brs
def __init__(self, strCard): self.strCard = strCard self.evalCard = Card.new(strCard) self.face = strCard[0] self.suit = strCard[1]
def card_pairs_board(c, b): card_rank = Card.get_rank_int(c) board_ranks = map(Card.get_rank_int, b) return card_rank in board_ranks
def hand2ranks(h): Lr = [] for c in h: Lr.append(Card.get_rank_int(c)) Lr.sort() return Lr
def getHand(self): ''' get a hand compatible with deuces ''' return [dCard.new(x.card_string) for x in self.hand]