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 revealCards(self, gameObject, cards): data = {} data['agenda'] = "cardReveal" data['data'] = [] for card in cards: data['data'].append(gameObject.convertNotation(Card.get_rank_int(card), Card.get_suit_int(card))) comms.broadcastToPlayers(gameObject.players, data);
def test_codes_property(self, hand, make_holding): holding = make_holding( player_id=hand.dealer.id, hand_id=hand.id, cards=[PokerCard.new('As'), PokerCard.new('Ac')]) assert holding.codes == [PokerCard.new('As'), PokerCard.new('Ac')]
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 hand_strength(hand_cards, community): if len(community) == 0: hand_cards.sort(key=order_cards) raw_score = two_card_lookup[" ".join(hand_cards)] scaled_score = (1325 - raw_score) * 2.9562264151 + 3545 return scaled_score elif len(community) == 3 and len(hand_cards) == 0: community.sort(key=order_cards) community = " ".join(community) community = transform_for_lookup(community) raw_score = three_card_lookup[community] scaled_score = (22100 - raw_score) * 0.2618552036 + 1675 return scaled_score elif len(community) == 4 and len(hand_cards) == 0: community.sort(key=order_cards) community = " ".join(community) community = transform_for_lookup(community) raw_score = four_card_lookup[community] scaled_score = (270725 - raw_score) * 0.02756526525 + 22 return four_card_lookup[community] else: deuces_cards = [Card.new(card) for card in hand_cards] deuces_community = [Card.new(card) for card in community] return evaluator.evaluate(deuces_cards, deuces_community)
def test_init(self, hand, make_holding): holding_no_cards = make_holding(player_id=hand.dealer.id, hand_id=hand.id) assert holding_no_cards.id > 0 assert len(holding_no_cards.cards) == 0 assert len(Card.query.all()) == 0 holding_cards_ints = make_holding( player_id=hand.dealer.id, hand_id=hand.id, cards=[PokerCard.new('As'), PokerCard.new('Ac')]) assert holding_cards_ints.id > 0 assert len(holding_cards_ints.cards) == 2 assert len(Card.query.all()) == 2 holding_cards_objs = make_holding(player_id=hand.dealer.id, hand_id=hand.id, cards=Card.query.all()) assert holding_cards_objs.id > 0 assert len(holding_cards_objs.cards) == 2 assert len(Card.query.all()) == 2 with pytest.raises(InvalidCardError): make_holding(player_id=hand.dealer.id, hand_id=hand.id, cards=["invalid card"]) with pytest.raises(sqlalchemy.exc.IntegrityError): make_holding(player_id=None, is_board=False, hand_id=hand.id)
def takeAction(player, action, data): global current_md5 global hand global board # print(action) # print(data) if action == "__new_peer": # calcuate md5 by player name # current_md5 = "70be3acc4a99a780e1b405e1ff7971c5" current_md5 = hashlib.md5(player).hexdigest() print('MD5 of Current User: '******'playerName']: card_list = player_info['cards'] for card in card_list: hand.append(Card.new(convertToDeucesCard(card))) print("****** My hand cards ******") Card.print_pretty_cards(hand) print("***************************") elif action == "__bet": takeActionByDeuces(player, action, data) elif action == "__action": if len(data['game']['board']) == 0: takeActionByHand(player, action, data) else: takeActionByDeuces(player, action, data)
def has_flush_draw(self): """Verifies if there is a flush draw. Returns a tuple of booleans, (high, low) (True, False) means there's a flush draw to the high card. (False, True) means the same, to the low card. (True, True) means the hand is suited, and there's a flush draw. (False, False) means no flush draw. Should return (True, False) if there's a flush draw with a pair in hand. Can be used with any() or all() """ if self.is_flush(): return (False, False) high_card = max(self._cards) hc_suit = Card.get_suit_int(high_card) low_card = min(self._cards) lc_suit = Card.get_suit_int(low_card) suits = list(map(Card.get_suit_int, self._cards + self._board._cards)) high_f_d = len([suit for suit in suits if suit == hc_suit]) == 4 low_f_d = len([suit for suit in suits if suit == lc_suit]) == 4 if any([high_f_d, low_f_d]) and self.pair_in_hand(): return (True, False) return (high_f_d, low_f_d)
def has_backdoor_flush(self): """Verifies if there is a backdoor flush. Returns a tuple of booleans, (high, low) (True, False) means there's a backdoor flush to the high card. (False, True) means the same, to the low card. (True, True) means the hand is suited, and there's a backdoor flush with a card on the flop. (False, False) means no backdoor flush draw. Can be used with any() or all() """ high_card = max(self._cards) hc_suit = Card.get_suit_int(high_card) low_card = min(self._cards) lc_suit = Card.get_suit_int(low_card) suits = list(map(Card.get_suit_int, self._cards + self._board._cards)) high_bd_f_d = len([suit for suit in suits if suit == hc_suit]) == 3 low_bd_f_d = len([suit for suit in suits if suit == lc_suit]) == 3 if any([high_bd_f_d, low_bd_f_d]) and self.pair_in_hand(): return (True, False) return (high_bd_f_d, low_bd_f_d)
def print_player_hand(self): try: Card.print_pretty_cards(self.player_cards + self.flop_cards) except TypeError, e: print( 'ERROR: Something went wrong. Make sure that all required cards are defined.' )
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 get_bet(self, data): roundnum = data['game']['roundName'] players = data['game']['players'] chips = data['self']['chips'] hands = data['self']['cards'] self.raise_count = data['game']['raiseCount'] self.my_step = data['game']['betCount'] self.my_chips = chips self.my_name = data['self']['playerName'] self.number_players = len(players) self.my_call_bet = data['self']['minBet'] self.my_raise_bet = self.my_call_bet * 2 self.hole = [] for card in (hands): card = convert_card_str(card) card = Card.new(card) self.hole.append(card) print ("...roundnum: ", format(roundnum), " -> force bet") print ('...my_call_bet:', format(self.my_call_bet), "my_raise_bet", format(self.my_raise_bet), "my_chips", format(self.my_chips), "table bet", format(self.table_bet)) Card.print_pretty_cards (self.hole) Card.print_pretty_cards (self.board) if roundnum == 'Deal' and self.my_step == 0: print ("...Force to bet!") action = 'call' amount = self.my_call_bet self.my_step += 1 self.total_bet += amount return action, amount else: return self.get_action(data)
def make_is_suited(self, hero_player): if Card.get_suit_int(hero_player.hand[0]) == Card.get_suit_int( hero_player.hand[1]): return np.array(1).reshape(1, -1) else: return np.array(0).reshape(1, -1)
def print_opponent_cards(self): try: Card.print_pretty_cards(self.opponent_cards) except TypeError, e: print( 'ERROR: Something went wrong. Make sure that all required cards are defined.' )
def bet(): actions = [] maxRaise = 0 for player in curState.curPlayers: action = player.callAI(curState, actions) actions.append([player, action]) if action[0][0] == "raise" and action[0][1] > maxRaise: maxRaise = action[0][1] for action in actions: if maxRaise > action[1][1]: curState.curPlayers.remove(action[0]) else: action[0].money -= maxRaise curState.pot += maxRaise print("Player Actions: ") for action in actions: print( str(action[0]) + ":\n " + str(action[1][0]) + ", maxbid: " + str(action[1][1])) print("Pot: " + str(curState.pot)) print("Current Players: ") for player in curState.curPlayers: print(player) print(" Hand: ") Card.print_pretty_cards(player.curHand) print(" Money: " + str(player.money))
def combat_power(self, hole, board_input, ppl, max_time = 1): Card.print_pretty_cards(hole+board_input) count = 0 count_win = 0 b_len = len(board_input) t_start = time.time() while True: self.deck.shuffle() board = board_input + self.dealer(5-b_len, hole+board_input) rank_my = self.evaluator.evaluate(hole, board) b_win = True player = [] rank = [] for i in range(ppl-1): player.append(self.dealer(2, hole+board)) rank.append(self.evaluator.evaluate(player[i], board)) if rank_my > rank[i]: b_win = False if b_win: count_win += 1 count += 1 t_end = time.time() if t_end - t_start > max_time: break return float(count_win)/float(count)
def get_action(board_cards=[],hand_cards=['AH', 'KD']): if(len(board_cards)+len(hand_cards)==0): return 'error' 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) score = get_score_by_simulate(hand,board) print(score) BAD_SCORE = 7000 BEST_SCORE = 1000 BETTER_SCORE = 2000 GOOD_SCORE = 4000 if(len(hand)+len(board)>5 and score>BAD_SCORE): action = 'fold' else: if(score<=BEST_SCORE): action = 'all_in' elif(score<=BETTER_SCORE): action = 'raise_max' elif(score>BETTER_SCORE and score<=GOOD_SCORE): action = 'raise_min' else: action = 'call' return action
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 serialize_card(card): suit_int = Card.get_suit_int(card) rank_int = Card.get_rank_int(card) s = Card.INT_SUIT_TO_CHAR_SUIT[suit_int] r = Card.STR_RANKS[rank_int] return s + r
def get_card_suite(board, hand): if not (all(hand) and all(board)): return -1 elif '-' in hand or '-' in board: return -1 board = [deucesCard.new(c) for c in board] hand = [deucesCard.new(c) for c in hand] return evaluator.evaluate(board, hand)
def test_front_lookup_aces(): strongest = [Card.new(x) for x in ['Ah', 'As', '6d']] middle = [Card.new(x) for x in ['Ah', 'As', '5d', '4d', '3d']] weakest = [Card.new(x) for x in ['Ah', 'As', '5d']] assert evaluator.evaluate(strongest, []) < \ evaluator.evaluate(middle, []) < \ evaluator.evaluate(weakest, [])
def test_front_lookup_trips(): weakest = [Card.new(x) for x in ['Kh', 'Ks', 'Kd', 'Ad', 'Qh']] middle = [Card.new(x) for x in ['Ah', 'As', 'Ad']] strongest = [Card.new(x) for x in ['Ah', 'As', 'Ad', '2d', '3d']] assert evaluator.evaluate(strongest, []) < \ evaluator.evaluate(middle, []) < \ evaluator.evaluate(weakest, [])
def test_get_hands(): '''Test that we convert a raw line of input cards into 2 hands of Cards''' raw_cards = '8C TS KC 9H 4S 7D 2S 5D 3S AC' expected_cards = ( [Card.new('8c'), Card.new('Ts'), Card.new('Kc'), Card.new('9h'), Card.new('4s')], [Card.new('7d'), Card.new('2s'), Card.new('5d'), Card.new('3s'), Card.new('Ac')], ) assert get_hands(raw_cards) == expected_cards
def deal(cardAmt): draw = deck.draw(cardAmt) if isinstance(draw, int): curState.board.append(deck.draw(cardAmt)) else: curState.board.extend(deck.draw(cardAmt)) print "Board: " print Card.print_pretty_cards(curState.board)
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 holding(hand): return Holding.create(id=1, player_id=hand.dealer_id, hand_id=hand.id, is_board=False, active=True, created_utc=datetime.datetime(2019, 7, 31), cards=[PokerCard.new('As'), PokerCard.new('Ac')])
def evaluate(evaluator, allCardsObjectOnBoard, cardObject1, cardObject2): try: # return 1 return evaluator.evaluate(allCardsObjectOnBoard, [cardObject1, cardObject2]) except: Card.print_pretty_cards(allCardsObjectOnBoard) Card.print_pretty_cards([cardObject1, cardObject2]) raise ValueError("chcek last cards, some problem with eval")
def __init__(self, new_deck, player_hand_string, flop=False): self.my_hand = [Card.new(i) for i in player_hand_string] self.deck = new_deck self.deck.cards.remove(self.my_hand[0]) self.deck.cards.remove(self.my_hand[1]) if flop: for new_card in flop: self.board_cards.append(Card.new(new_card)) self.deck.cards.remove(self.board_cards[-1])
def deal_hole_cards(self): for p in self.players: p.hand = self.deck.draw(2) p.hand = sorted(p.hand, reverse=False) if p.id == "HUMAN": print("Your hand: \t") Card.print_pretty_cards(p.hand) print("")
def test_front_lookup_very_low(): weakest = [Card.new(x) for x in ['2h', '3s', '4d']] middle = [Card.new(x) for x in ['2h', '3s', '5d']] stronger = [Card.new(x) for x in ['2h', '4s', '5d']] strongest = [Card.new(x) for x in ['2h', '3s', '7d']] assert evaluator.evaluate(strongest, []) < \ evaluator.evaluate(stronger, []) < \ evaluator.evaluate(middle, []) < \ evaluator.evaluate(weakest, [])
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 encode(self, plyr_board, oppo_board, current_card, plyr_cards, game_over, score): current_card = [Card.new(current_card)] plyr_cards = [Card.new(x) for x in plyr_cards] plyr_front_ranks = self.cards_to_ranks(plyr_board.front.cards, 3) plyr_mid_ranks = self.cards_to_ranks(plyr_board.mid.cards, 5) plyr_back_ranks = self.cards_to_ranks(plyr_board.back.cards, 5) oppo_front_ranks = self.cards_to_ranks(plyr_board.front.cards, 3) oppo_mid_ranks = self.cards_to_ranks(plyr_board.mid.cards, 5) oppo_back_ranks = self.cards_to_ranks(plyr_board.back.cards, 5) plyr_front_suits = self.cards_to_suits(plyr_board.front.cards) plyr_mid_suits = self.cards_to_suits(plyr_board.mid.cards) plyr_back_suits = self.cards_to_suits(plyr_board.back.cards) oppo_front_suits = self.cards_to_suits(plyr_board.front.cards) oppo_mid_suits = self.cards_to_suits(plyr_board.mid.cards) oppo_back_suits = self.cards_to_suits(plyr_board.back.cards) current_card_rank = self.cards_to_ranks(current_card, 1) current_card_suit = self.cards_to_suits(current_card) remaining_card_ranks = self.cards_to_ranks(plyr_cards, 4) remaining_card_suits = self.cards_to_suits(plyr_cards) free_streets = np.array(plyr_board.get_free_streets()) free_streets_std = (free_streets - 0.5) * 2 # Hacky "standardisation" encoding = np.hstack([ plyr_front_ranks, plyr_mid_ranks, plyr_back_ranks, plyr_front_suits, plyr_mid_suits, plyr_back_suits, oppo_front_ranks, oppo_mid_ranks, oppo_back_ranks, oppo_front_suits, oppo_mid_suits, oppo_back_suits, current_card_rank, current_card_suit, remaining_card_ranks, remaining_card_suits, free_streets_std ]) return encoding
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 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 test_front_royalties(): front = [Card.new(x) for x in ['2h', '2c', '3d']] assert RoyaltyCalculator.score_front_royalties(front) == 0 front = [Card.new(x) for x in ['6h', '6c', '3d']] assert RoyaltyCalculator.score_front_royalties(front) == 1 front = [Card.new(x) for x in ['Ah', 'Ac', '3d']] assert RoyaltyCalculator.score_front_royalties(front) == 9 front = [Card.new(x) for x in ['2h', '2c', '2d']] assert RoyaltyCalculator.score_front_royalties(front) == 10 front = [Card.new(x) for x in ['Ah', 'Ac', 'Ad']] assert RoyaltyCalculator.score_front_royalties(front) == 22
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))
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 get_probabilities(card_1, card_2, other_players, trials=10000): """ for a given preflop hand, compute the probabilities of winning or tying. Note that we've got a very important design decision here: we could obtain the probabilities in a combinatorial fashion -- it's possible to mathematically reason to obtain the exact probability of winning or tying, but this seems quite involved. It's much easier to use a Monte Carlo simulation to approximate the probabilities. With a large number of trials (e.g. 10k or 100k) the approximations should be sufficiently close to the theoretical "true" values for all practical intents and purposes. """ deck = map(lambda (x,y): Card.new(y+x), list(product(suits,ranks))) wins = 0 ties = 0 deck.remove(card_1) deck.remove(card_2) for i in range(trials): # Randomly shuffling the deck and slicing the first few cards to get hands # seems computationally cheaper than using random.choice to select subsets as hands shuffle(deck) shared_cards = deck[:5] # hands held by other players other_hands = [deck[5+(2*x):7+(2*x)] for x in range(other_players)] result = eval_table([card_1, card_2], shared_cards, other_hands) if result == WIN: wins +=1 elif result == TIE: ties +=1 return wins/float(trials), ties/float(trials)
def query_state(self): ret = 'pies = %d, cards = ' % self.pies for c in self.cards: ret += Card.int_to_pretty_str(c) if self.game is None: ret += ', currently not in-game' else: ret += ', ' + self.game.query_state() return ret
def parse_cards(cardstr): #have to replace 10 with T for deuces cardstr = cardstr.replace('10', 'T') cardlist = cardstr.split(' ') hand = [] for card in cardlist: dcard = Card.new(card) hand.append(dcard) return hand
def cards_to_suits(cards): suit_dummy = np.zeros(4) suit_binaries = np.array([Card.get_suit_int(x) for x in cards]) suit_dummy[0] = sum(suit_binaries == 1) suit_dummy[1] = sum(suit_binaries == 2) suit_dummy[2] = sum(suit_binaries == 4) suit_dummy[3] = sum(suit_binaries == 8) suit_dummy_std = (suit_dummy - 1.5) / 2 # Hacky "standardisation" return suit_dummy_std
def reveal(self): msg = "%s's cards are" % self.tag for c in self.cards: msg += ' ' + Card.int_to_pretty_str(c) self.cards = [] if self.game is not None: self.game.message_players(msg) else: return 'Not in game' return 'Revealed and discarded hand'
def cards_to_ranks(cards, pad): rank_dummy = np.zeros(pad) # Add one to distinguish deuce from missing cards = sorted([Card.get_rank_int(x) for x in cards]) for i, card in enumerate(cards): if i >= pad: continue rank_dummy[i] = card + 1 rank_dummy_std = (rank_dummy - 8) / 14 # Hacky "standardisation" return rank_dummy_std
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_lowest_unpairing_card(hand): """Add the worst possible card to an incomplete hand. Something that cannot pair up or make a flush or make a straight.""" existing_ranks = set([Card.get_rank_int(x) for x in hand]) remaining_ranks = list(set(range(12)) - existing_ranks) selected_rank = remaining_ranks[0] would_be_hand = hand + [Card.new(Card.STR_RANKS[selected_rank] + 'h')] if is_straight(would_be_hand): selected_rank = remaining_ranks[1] # Don't make a straight selected_rank_str = Card.STR_RANKS[selected_rank] last_suit = Card.get_suit_int(hand[-1]) last_suit_index = [1, 2, 4, 8].index(last_suit) selected_suit = [1, 2, 4, 8][(last_suit_index + 1) % 4] selected_suit_str = Card.INT_SUIT_TO_CHAR_SUIT[selected_suit] selected_card_str = selected_rank_str + str(selected_suit_str) return Card.new(selected_card_str)
def setUpDeucesCards(cardsList): # Take a list of cards numbered 1-52 and put them into the form #used by deuces evaluator. # Convert card numbers to a deuces form string. cardStrings = [] for i in range (0,len(cardsList)): cardStrings.append(convertToDeuces(cardsList[i])) # Put cards into a deuces form hand. deucesCards = [] for i in range (0,len(cardsList)): deucesCards.append(Card.new(cardStrings[i])) return deucesCards
def pretty(self): print 'Front:' Card.print_pretty_cards(self.front.cards) print 'Mid:' Card.print_pretty_cards(self.mid.cards) print 'Back:' Card.print_pretty_cards(self.back.cards)
def main(other_players, trials): with open("lookup-table-" + str(other_players), "w") as f: # iterate over all 169 equivalent starting hands. If you're curious about # why there are only 169 equivalent starting hands, see: # https://en.wikipedia.org/wiki/Texas_hold_'em_starting_hands#Essentials count = 0 for c1 in range(len(ranks)): for c2 in range(c1,len(ranks)): # note that the way we iterate means that r1 <= r2 always. # knowing this makes it easier to get data from the output lookup table. r1 = ranks[c1] r2 = ranks[c2] # We only ever use Spades and Clubs as suits because all that matters # is whether your starting cards are suited or off-suit. The suits # themselves are all equivalent, so the nominal choice doesn't matter. if r1==r2: wins,ties = get_probabilities((Card.new(r1 + "s")), Card.new(r2 + "c"), other_players, trials) write_to_file(f, r1, r2, "offsuit", wins, ties) count +=1 else: wins,ties = get_probabilities((Card.new(r1 + "s")), Card.new(r2+ "c"), other_players, trials) write_to_file(f, r1, r2, "offsuit", wins, ties) count +=1 wins,ties = get_probabilities((Card.new(r1 + "s")), Card.new(r2+ "s"), other_players, trials) write_to_file(f, r1, r2, "suited", wins, ties) count +=1 # Log the script's progress. For a given number of players, every simulation # should take roughly equally long. However, the more players you have, # the longer the entire process takes. (More hands to evaluate.) print "Simulated " + str(count) +" / 169"
def score_front_royalties(cards): if len(cards) != 3: raise ValueError("Incorrect number of cards!") ranks = [Card.get_rank_int(x) for x in cards] ctr = collections.Counter(ranks) rank, count = ctr.most_common()[0] if count < 2: return 0 if count == 2: return max(0, rank - 3) if count == 3: return 10 + rank
def encode(self, plyr_board, oppo_board, current_card, plyr_cards, game_over, score): if current_card is not None: current_card = Card.new(current_card) current_card_binary = self.card_to_ranks_binary(current_card) else: current_card_binary = np.zeros(13) free_streets = np.array(plyr_board.get_free_streets()) free_streets_std = (free_streets - 0.5) * 2 # Hacky "standardisation" encoding = np.hstack([ current_card_binary, free_streets_std ]) return encoding
def add_card(self, new_card_str): self.cards.append(Card.new(new_card_str))
def __init__(self, card_strs): self.cards = [Card.new(x) for x in card_strs]
from rlofc.royalty_calculator import RoyaltyCalculator from deuces import Card no_pair = [Card.new(x) for x in ['2h', '9c', '3d', '4d', '5d']] one_pair = [Card.new(x) for x in ['Ah', 'Th', '8h', '5h', '5c']] two_pair = [Card.new(x) for x in ['Ah', 'Th', 'Th', '5h', '5c']] trips = [Card.new(x) for x in ['Ah', 'Th', '8h', '8d', '8c']] straight = [Card.new(x) for x in ['Ah', 'Kh', 'Qh', 'Jh', 'Tc']] flush = [Card.new(x) for x in ['Ah', 'Th', '8h', '5h', '4h']] boat = [Card.new(x) for x in ['Ah', 'As', 'Ac', '8d', '8c']] quads = [Card.new(x) for x in ['Ah', 'As', 'Ac', 'Ad', 'Kc']] sf = [Card.new(x) for x in ['Ah', '2h', '3h', '4h', '5h']] royal = [Card.new(x) for x in ['Ah', 'Kh', 'Qh', 'Jh', 'Th']] def test_back_royalties(): assert RoyaltyCalculator.score_back_royalties(no_pair) == 0 assert RoyaltyCalculator.score_back_royalties(one_pair) == 0 assert RoyaltyCalculator.score_back_royalties(two_pair) == 0 assert RoyaltyCalculator.score_back_royalties(trips) == 0 assert RoyaltyCalculator.score_back_royalties(straight) == 2 assert RoyaltyCalculator.score_back_royalties(flush) == 4 assert RoyaltyCalculator.score_back_royalties(boat) == 6 assert RoyaltyCalculator.score_back_royalties(quads) == 10 assert RoyaltyCalculator.score_back_royalties(sf) == 15 assert RoyaltyCalculator.score_back_royalties(royal) == 35 def test_mid_royalties(): assert RoyaltyCalculator.score_mid_royalties(no_pair) == 0
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 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)
def str_to_cards(cardsstr): cards = [] for cardstr in cardsstr: card = Card.new(cardstr) cards.append(card) return cards
from __future__ import division import pickle from deuces import Card, Evaluator, Deck test = pickle.load(open("preflop_scores.p", "rb")) pre_flop = test.copy() for key in pre_flop: pre_flop[key] = pre_flop[key][0] / pre_flop[key][1] results = sorted(pre_flop.items(), key=lambda x: x[1], reverse=True) for i in range(0, 30): Card.print_pretty_cards(list(results[i][0])) print "Winning Percentage: " + str(results[i][1] * 100)
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) 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 + \
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
# 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 Card.print_pretty_cards(hand3) print "\n%s TEAM has hand " % team4 Card.print_pretty_cards(hand4) print "\nWow nice hands!" ans4 = raw_input("\nHit <enter> to continue: ") _=os.system("clear") # simulate boards print "Now let's simulate boards..." # win/tie counts wins1 = 0 wins2 = 0 wins3 = 0