def _get_observation(self, player): keys = ['position', 'state', 'stack', 'money_in_pot', 'bet_this_street', 'all_in'] values = [ [other.position, other.state, other.stack, other.money_in_pot, other.bet_this_street, other.all_in] for other in self.players if other is not player ] return { 'self': { 'position': player.position, 'cards': [[Card.get_suit_int(card), Card.get_rank_int(card)] for card in player.cards], 'stack': player.stack, 'money_in_pot': player.money_in_pot, 'bet_this_street': player.bet_this_street, }, 'table': { 'street': int(self.street), 'cards': [[Card.get_suit_int(card), Card.get_rank_int(card)] for card in self.cards], 'pot': self.pot, 'bet_to_match': self.bet_to_match, 'minimum_raise': self.minimum_raise, }, 'others': [ { key: val for key, val in zip(keys, value) } for value in values ] }
def eval_trick_winner(self): trumps = [] for card in self.playedCards: if Card.get_suit_int(card) == self.trumps: trumps.append(card) trumps.sort(reverse=True) if len(trumps) > 0: bestCard = trumps[0] else: leadSuits = [] for card in self.playedCards: if Card.get_suit_int(card) == self.leadSuit: leadSuits.append(card) leadSuits.sort(reverse=True) bestCard = leadSuits[0] winnerIndex = self.playedCards.index(bestCard) winner = self.playerOrder[winnerIndex] winner.trickCount += 1 print('\n', winner.name, ' wins the trick with ', Card.print_pretty_card(bestCard)) self.leadPlayer = winner self.playedCards = []
def convert_card_to_treys(cards): convert_cards = [] hand_nb_spade = 0 hand_nb_heart = 0 hand_nb_diamond = 0 hand_nb_clover = 0 feats = [] for card in cards: color = card[0] num = card[1] if color == "C": hand_nb_clover += 1 elif color == "H": hand_nb_heart += 1 elif color == "D": hand_nb_diamond += 1 elif color == "S": hand_nb_spade += 1 convert_cards.append(Card.new(num.upper() + color.lower())) for i in [0, 1, 2, 3, 4]: feat = np.zeros(13) try: feat[Card.get_rank_int(convert_cards[i])] = 1 feats.append(feat) except Exception as e: feats.append(feat) return feats, hand_nb_spade, hand_nb_heart, hand_nb_diamond, hand_nb_clover
def random_board(self, hand, with_full_deck): deck = self.deck_of_cards b = self.take(3) while (self.is_duplicates(b, hand)): b = self.take(3) b = [Card.new(b[0]), Card.new(b[1]), Card.new(b[2])] return b
def deal_next_round(self): """ helper function to update the current round and reset number of raises :return: """ if self.GameState.current_round == 0: # deal flop print("Dealing Flop") flop = self.deck.draw(3) print(Card.print_pretty_cards(flop)) self.GameState.bit_flop = flop self.GameState.flop[self.deck_lookup[flop[0]]] = 1 self.GameState.flop[self.deck_lookup[flop[1]]] = 1 self.GameState.flop[self.deck_lookup[flop[2]]] = 1 if self.GameState.current_round == 1: print("Dealing Turn") self.GameState.bb_size = int(self.GameState.bb_size * 2) turn = self.deck.draw(1) print(Card.print_pretty_cards([turn])) self.GameState.bit_turn = [turn] self.GameState.turn[self.deck_lookup[turn]] = 1 if self.GameState.current_round == 2: print("Dealing River") river = self.deck.draw(1) print(Card.print_pretty_cards([river])) self.GameState.bit_river = [river] self.GameState.flop[self.deck_lookup[river]] = 1 # num raises starts over self.GameState.num_raises = 0
def __init__(self, strategy=None, desiredCards=None): self.strategy = strategy self.desiredCards = ([ Card.print_pretty_card(Card.new(card)) if len(card) > 1 else card for card in desiredCards ] if desiredCards else None) self.POKER_HAND_EVALUATOR = Evaluator()
def pretty(self): print('Front:') print(Card.print_pretty_cards(self.front.cards)) print('Mid:') print(Card.print_pretty_cards(self.mid.cards)) print('Back:') print(Card.print_pretty_cards(self.back.cards))
def find_swap(hand): s1 = Card.get_suit_int(hand[0]) s2 = Card.get_suit_int(hand[1]) if (s1 == s2): if (s1 == 1): return 0 #both are spades, do nothing else: return [int_to_char[s1] + 's'] #swap with spades elif (s1 == 1 or s2 == 1): if (s1 == 1): if (s2 != 2): return [int_to_char[s2] + 'h'] else: return 0 else: #some suit with spade if (s1 != 2): return [int_to_char[s1] + 'h', 'hs'] else: #heart and spade return ['hs'] elif (s1 == 2 or s2 == 2): #no spades, hearts and something else if (s1 == 2): return [int_to_char[s2] + 's', 'sh'] else: return [int_to_char[s1] + 's'] else: return [int_to_char[s1] + 's', int_to_char[s2] + 'h']
def decide_action(status): hand = [] board = [] pocket_cards = status['pocketCards'] common_cards = status['communityCards'] for card in pocket_cards: if card['rank'] == "10": rank = "T" elif len(card['rank']) > 1: rank = card['rank'][0].upper() else: rank = card['rank'] suit = card['suit'][0] hand.append(Card.new('{}{}'.format(rank, suit))) for card in common_cards: if card['rank'] == "10": rank = "T" elif len(card['rank']) > 1: rank = card['rank'][0].upper() else: rank = card['rank'] suit = card['suit'][0] board.append(Card.new('{}{}'.format(rank, suit))) return 'call'
def evaluateFromState(self, state, playerid): # print("state",state.player_states[playerid].hand) evaluator = Evaluator() hand = [] board = [] # p1_score = evaluator.evaluate(board, player1_hand) for i in state.player_states[playerid].hand: hand.append(Card.new(card_to_normal_str(i))) # print(card_to_normal_str(i)) # print(hand) for j in state.community_card: if j != -1: # print(card_to_normal_str(j)) board.append(Card.new(card_to_normal_str(j))) # print(board) if len(board) == 0: rank = evaluator.evaluate(hand, []) elif len(board) == 3: rank = evaluator.evaluate(hand, board[:3]) elif len(board) == 4: rank = evaluator.evaluate(hand, board[:4]) elif len(board) == 5: rank = evaluator.evaluate(hand, board[:5]) rank_class = evaluator.get_rank_class(rank) class_string = evaluator.class_to_string(rank_class) percentage = 1.0 - evaluator.get_five_card_rank_percentage( rank) # higher better here # print("Player hand = {}, percentage rank among all hands = {}".format(class_string, percentage)) return [rank, percentage]
def withPreFlop(self, data): amount = 0 action = Action.Check self.allinTimes = 0 self.boardStrength = 0 Card.print_pretty_cards(self.hands) hole_winrate = self.holeEvaluator.evaluate(self.hands, 3, 1000) # print('Hole win rate:{}'.format(hole_winrate)) print('min bet:{}'.format(self.min_bet)) if hole_winrate > 0.5: # (J,J) action = Action.Allin elif hole_winrate > 0.4 and not self.isBetTooMuch(0, 0.5): # (6,6) action = Action.Bet amount = self.my_chips / 4 elif hole_winrate > 0.3: # (2,2) if not self.isBetTooMuch(0, 0.3): action = Action.Raise else: action = Action.Call elif self.player_bb == self.player_hashed_name and not self.isBetTooMuch(0, 0.2): action = Action.Check elif not self.isBetTooMuch(0, 0.1): action = Action.Call else: action = Action.Fold return (action, amount)
def updateHandsStrength(self, hole, boards): print("Hand card:") Card.print_pretty_cards(self.hands) print("Board card:") Card.print_pretty_cards(self.board) self.hands_strength = self.handEvaluator.evaluate( self.hands, self.board)
def assign_cards_to_display(self, guest_cards_st, learner_cards_st, reset = False): if reset: for card in self.guest_cards+self.learner_cards: card.pack_forget() position_cards = [0, 0] for card in self.guest_cards_st: guest_card = self.form_image(card) guest_card.pack(side='left', expand = False, padx=position_cards[0], pady=position_cards[1]) self.guest_cards.append(guest_card) for card in self.learner_cards_st: learner_card = self.form_image(card, learner=True) #if not self.sd_tr else self.form_image(card, learner=False) learner_card.pack(side='right', expand = False, padx=position_cards[0], pady=position_cards[1]) self.learner_cards.append(learner_card) cd = [] if self.community_display is not None: for card in self.community_display: card.pack_forget() if self.community_cards is not None: if not(all(i < 0 for i in self.community_cards)): if self.community_cards[0] is not -1 and self.community_cards[1] is not -1 and self.community_cards[2] is not -1: cd.append(Card.int_to_str(self.community_cards[0]).upper()) cd.append(Card.int_to_str(self.community_cards[1]).upper()) cd.append(Card.int_to_str(self.community_cards[2]).upper()) if self.community_cards[3] is not -1: cd.append(Card.int_to_str(self.community_cards[3]).upper()) if self.community_cards[4] is not -1: cd.append(Card.int_to_str(self.community_cards[4]).upper()) for card in cd: c = self.form_image(card, community=True) c.pack(side='left', expand = False, padx=20, pady=20) self.community_display.append(c)
def index(): evaluator = Evaluator() deck = Deck() card = Card.new('Qh') board = deck.draw(5) player_names = ("player 1", "player 2", "player 3", "player 4", "player 5", "player 6", "player 7", "player 8") players = {} output = {} # this is procedural programming, not functional programming :( for p in player_names: hand = deck.draw(2) score = evaluator.evaluate(board, hand) text = evaluator.class_to_string(evaluator.get_rank_class(score)) players[p] = score output[p] = {'score': score, 'text': text} # What about a tie? tie = (len(players.values()) == len(set(players.values()))) winner = min( players, key=players.get) # always 1 result :( Don't forget to fix the TEST! # does the tie involve the winning hand though? # TODO https://stackoverflow.com/questions/17821079/how-to-check-if-two-keys-in-dictionary-hold-the-same-value output["winners"] = winner output["tie"] = tie output["card"] = Card.int_to_str(card) j = json.dumps(output) return j
def display_hand(self): print("Top:") print(Card.print_pretty_cards(self.top_hand)) print("Middle:") print(Card.print_pretty_cards(self.middle_hand)) print("Bottom:") print(Card.print_pretty_cards(self.bottom_hand))
def has_suited_pockets(self, player_index): if Card.get_suit_int( self.pocket_cards[player_index][0]) == Card.get_rank_int( self.pocket_cards[player_index][1]): return True else: return False
def HeroVsRangeEquityCalc(self): global vilRange START = DT.datetime.now() # Hero Hand heroHandstr = self.ui.heroHand.toPlainText() heroCard1 = Card.new(heroHandstr[0:2]) heroCard2 = Card.new(heroHandstr[3:5]) heroHand = [ heroCard1, heroCard2 ] # This is not going to work on 10 ---- need to search for commas or sumn like below. 10 = T # Board Boardstr = self.ui.board.toPlainText() ### Func to be extracted to Loose file func(str,',') -> nCardList # Break up text by comma Board = separateCardsByComma( Boardstr) ## Functio nname should be better ### END FUN TO BE EXTRACTED # Evaluate Equity Equity = EquityVsRange(vilRange, heroHand, flop=Board) self.ui.EvalTextDisplay.setPlainText(str(Equity)) END = DT.datetime.now() TIME = END - START print(TIME.seconds)
def split_by_suit(cards): spades = [] hearts = [] diamonds = [] clubs = [] for card in cards: if Card.get_suit_int(card)==1: spades.append(card) elif Card.get_suit_int(card)==2: hearts.append(card) elif Card.get_suit_int(card)==4: diamonds.append(card) elif Card.get_suit_int(card)==8: clubs.append(card) else: return 'Card suit ERROR' all_suits = [spades,hearts,diamonds,clubs] suit_split = [] for suit in all_suits: if len(suit)>0: suit_split.append(suit) suit_split.sort(key=len, reverse=True) return suit_split
def output_loop(self): threading.Timer(1, self.output_loop).start() output = '' output = output + self.state[0][:self.state[0].find("|")].center( 80, ' ' ) + '\n' + "================================================================================\n" deltatime = datetime.now() - self.start output = output + Card.print_pretty_cards(self.board).center( 38, ' ') + "||" + deltatime.__str__().center(38, ' ') + '\n' output = output + Card.print_pretty_cards(self.handcards).center( 38, ' ') + "||" + "hands played" + str(len(self.hands)).center( 25 - len(self.hands) // 10, " ") + "\n" output = output + "hand %" + "".center( 32, ' ') + "||" + "won " + str(self.won).center( 25 - self.won // 10, ' ') + "\n" output = output + "win %" + self.winp.center( 32, ' ') + "||" + "folded " + str(self.folded).center( 25 - self.folded // 10, ' ') + "\n" output = output + "lose %" + self.losep.center( 32, ' ') + "||" + "P/L " + str(self.pl).center(25, ' ') + "\n" output = output + "tie %" + self.tiep.center( 32, ' ') + '||' + ''.join(self.notes).center(38, ' ') + '\n' output = output + "errors" + str(self.er).center(32, ' ') #self.clear() print(output, end='\r')
def test_check_players_have_cards(self): """Return False if at least one player have cards""" # Arrange cards1 = str(Card.new('As')) + ',' + str(Card.new('9s')) cards2 = str(Card.new('Ah')) + ',' + str(Card.new('9h')) us1 = User(username='******') us1.save() us2 = User(username='******') us2.save() us3 = User(username='******') us3.save() us4 = User(username='******') us4.save() player1 = Player(name=us1, cards=cards1) player1.save() player2 = Player(name=us2, cards=cards2) player2.save() player3 = Player(name=us3) player3.save() player4 = Player(name=us4) player4.save() table = Table(player1=player1, player2=player2, player3=player3, player4=player4) # Act result = table.check_players_have_cards() # Assertion self.assertFalse(result) table.remove_cards_from_players() result2 = table.check_players_have_cards() self.assertTrue(result2)
def get_win_prob(self,state, playerid,hand_cards, board_cards,num_players): win = 0 rounds=0 evaluator = Evaluator() for i in range(self.simulation_number): board_cards_to_draw = 5 - len(board_cards) # 2 board_sample = board_cards + self._pick_unused_card(board_cards_to_draw,hand_cards+board_cards) unused_cards = self._pick_unused_card((num_players - 1) * 2, hand_cards + board_sample) board_sample = [Card.new(i) for i in board_sample] unused_cards = [Card.new(i) for i in unused_cards] opponents_hole = [unused_cards[2 * i:2 * i + 2] for i in range(num_players - 1)] #hand_sample = self._pick_unused_card(2, board_sample + hand_cards) try: opponents_score = [1 - evaluator.evaluate(hole, board_sample)/7462 for hole in opponents_hole] myhand_cards = [Card.new(i) for i in hand_cards] my_rank = 1 - evaluator.evaluate(myhand_cards, board_sample)/7462 if my_rank >= max(opponents_score): win += 1 #rival_rank = evaluator.evaluate_hand(hand_sample, board_sample) rounds+=1 except Exception as e: #print e.message continue win_prob = win / rounds return win_prob
def endRound(self, data): try: self.total_round += 1 round_name = data['table']['roundName'] self.updateStage(round_name, data) Card.print_pretty_cards(self.board) players = data['players'] for player in (players): name = player['playerName'] isAlive = player['isSurvive'] if isAlive: message = player['hand']['message'] if player['winMoney'] > 0: print('{} has {} to win {} ({})'.format( name, message, player['winMoney'], self.showCard(player['hand']['cards']))) if name == self.player_hashed_name: self.win_round += 1 else: if name == self.player_hashed_name: print('{} has {} ({})'.format( name, message, self.showCard(player['hand']['cards']))) else: print('{} has {}'.format(name, message)) else: print("{} out".format(name)) except Exception: traceback.print_exc() print(data)
def _get_cards_rank(self, hole_card, round_state, debug_printouts): """ :param hole_card: Hole cards of own player :param round_state: Current round state, containing community cards :param debug_printouts: Parameter for debugging purpose only. Allows printing the calculated hand rank :return: Float between 0 and 1, representing the current five card rank among all possible poker hands. 0 represents the weakest five card combination, 1 the strongest (Royal Flush) """ evaluator = Evaluator() board = [] hand = [] if len(round_state['community_card']) >= len(board): for card in round_state['community_card']: board.append(Card.new(card)) for card in hole_card: hand.append(Card.new(card)) score = evaluator.evaluate(board, hand) if debug_printouts: Card.print_pretty_cards(board + hand) print(Card.print_pretty_cards(board + hand)) return 1 - evaluator.get_five_card_rank_percentage(score)
def top_royalties(cards): ranked_cards = split_by_rank(cards) top_roy=0 if len(ranked_cards) == 1: top_roy += Card.get_rank_int(ranked_cards[0][0])+10 elif len(ranked_cards) == 2: top_roy += Card.get_rank_int(ranked_cards[0][0])-3 return top_roy
def CalculateWinProb(self, hand, board): hand_string = [Card.int_to_str(card) for card in hand] hand_string.append("?") hand_string.append("?") equity = calculate([Card.int_to_str(card) for card in board], self.EXACT, self.NUM_SIMULATIONS, self.INPUT_FILE, hand_string, self.VERBOSE)[1] return equity
def hero_hole_cards(hh_preflop): #Returns a list which contains the integer representation of two hole cards belonging to hero based on treys library. hole_cards = [] hole_cards.append( Card.new(hh_preflop.split('Dealt to Hero ')[1].split()[0][1:])) hole_cards.append( Card.new(hh_preflop.split('Dealt to Hero ')[1].split()[1][:-1])) return hole_cards
def is_flush(cards): suit = Card.get_suit_int(cards[0]) is_flush = True for card in cards: if Card.get_suit_int(card) != suit: is_flush = False break return is_flush
def set_hand_card(self, cards): self.hand_cards = cards cardOne = Card.new(cards[0]['value'] + cards[0]['suit']) cardTwo = Card.new(cards[1]['value'] + cards[1]['suit']) self.is_suited = cards[0]['suit'] == cards[1]['suit'] self.is_pair = cards[0]['value'] == cards[1]['value'] self.hand_score = Card.prime_product_from_hand([cardOne, cardTwo]) self.hand_rank = evaluator.get_rank_class(self.hand_score)
def play_game_human_cpu(self): """Rollout one OFC game and return the LHS score and LHS/RHS boards.""" deck = DeckGenerator.new_deck() lhs_board = OFCBoard() rhs_board = OFCBoard() lhs_start = deck[0:5] rhs_start = deck[6:11] # Starting hand one card at a time for now. In future, give # all cards at once lhs_board.pretty() print('Player 1 starting cards;'), Card.print_pretty_cards([Card.new(card) for card in lhs_start]) for i in range(5): card = lhs_start[i] street_id = self.lhs_agent.place_new_card(card, lhs_board) lhs_board.place_card_by_id(card, street_id) lhs_board.pretty() for i in range(5): card = rhs_start[i] street_id = self.rhs_agent.place_new_card(card, rhs_board) rhs_board.place_card_by_id(card, street_id) print('') # Eight cards one at a time for i in range(8): self.print_both_boards(lhs_board, rhs_board) card = deck.pop() street_id = self.lhs_agent.place_new_card(card, lhs_board) lhs_board.place_card_by_id(card, street_id) card = deck.pop() street_id = self.rhs_agent.place_new_card(card, rhs_board) rhs_board.place_card_by_id(card, street_id) print('Final Boards') self.print_both_boards(lhs_board, rhs_board) lhs_royalties = lhs_board.get_royalties() rhs_royalties = rhs_board.get_royalties() if lhs_board.is_foul() and rhs_board.is_foul(): lhs_score = 0 elif lhs_board.is_foul(): lhs_score = (-1 * rhs_royalties) - 6 elif rhs_board.is_foul(): lhs_score = lhs_royalties + 6 else: exch = self.calculate_scoop(lhs_board, rhs_board) lhs_score = exch + lhs_royalties - rhs_royalties return lhs_score, lhs_board, rhs_board
def _pick_unused_card(self, used_card): used = [ self.CardIDmapping[Card.int_to_str(card)] for card in used_card ] unused = [ card_id for card_id in self.TotalCards.keys() if card_id not in used ] return [Card.new(self.TotalCards[card_id]) for card_id in unused]