def declare_action(self, valid_actions, hole_card, round_state, bot_state=None): rnd = random.randint(1, 101) c1 = Card.from_str(hole_card[0]) c2 = Card.from_str(hole_card[1]) own_stack, avg_stack = self.count_starting_stacks(round_state) blinds = min(own_stack, avg_stack) / self.bb # push/fold if round_state['street'] == 'preflop' and blinds < self.ins(14): return self.push_fold(valid_actions, round_state, blinds, c1, c2) # short stack if self.short or round_state[ 'street'] == 'preflop': # and blinds < self.ins(26): return self.play_short_stack(valid_actions, round_state, c1, c2) # monster if round_state['street'] == 'preflop': return self.play_monster(valid_actions, c1, c2) return self.check_or_fold(valid_actions)
def __fill_blank_card(self, community_): community = [Card.from_id(card.to_id()) for card in community_] # deep copy need_card = 5 - len(community) card_id_range = range(1, 53) for card_id in random.sample(card_id_range, need_card): community.append(Card.from_id(card_id)) return community
def test_run_until_game_finish_when_one_player_is_left(self): uuids = [ "ruypwwoqwuwdnauiwpefsw", "sqmfwdkpcoagzqxpxnmxwm", "uxrdiwvctvilasinweqven" ] holecards = [[Card.from_str(s) for s in ss] for ss in [["C2", "C3"], ["HA", "CA"], ["D5", "H6"]]] game_state = restore_game_state(ThreePlayerGameStateSample.round_state) game_state = reduce( lambda state, item: attach_hole_card(state, item[0], item[1]), zip(uuids, holecards), game_state) sb_amount, ante = 5, 7 self.emu.set_game_rule(3, 10, sb_amount, ante) p1_acts = [("fold", 0), ("call", 10), ('call', 0), ('call', 10), ("fold", 0)] p2_acts = [] p3_acts = [("raise", 10)] players = [TestPlayer(acts) for acts in [p1_acts, p2_acts, p3_acts]] [ self.emu.register_player(uuid, player) for uuid, player in zip(uuids, players) ] game_state["table"].deck.deck.append(Card.from_str("C7")) game_state, events = self.emu.run_until_game_finish(game_state) self.eq("event_game_finish", events[-1]["type"]) self.eq(0, game_state["table"].seats.players[0].stack) self.eq(0, game_state["table"].seats.players[1].stack) self.eq(292, game_state["table"].seats.players[2].stack)
def declare_action(self, valid_actions, hole_card, round_state, bot_state=None): rnd = random.randint(1, 101) c1 = Card.from_str(hole_card[0]) c2 = Card.from_str(hole_card[1]) own_stack, avg_stack = self.count_stacks(round_state) blinds = min(own_stack, avg_stack) / self.bb if round_state['street'] == 'preflop': pair = c1.rank == c2.rank suited = c1.suit == c2.suit if blinds < 14: return self.push_fold(valid_actions, round_state, blinds, c1, c2) is_kk_plus = pair and c1.rank > 12 is_low_k = min(c1.rank, c2.rank) == 13 is_hi_a = max(c1.rank, c2.rank) == 14 is_ak = is_low_k and is_hi_a is_aks = is_ak and suited if is_kk_plus or is_aks: # print('MONSTER', c1, c2) return self.raise_or_call(valid_actions, MAX) return self.check_or_fold(valid_actions)
def test_run_until_game_finish_when_one_player_is_left(self): uuids = [ 'ruypwwoqwuwdnauiwpefsw', 'sqmfwdkpcoagzqxpxnmxwm', 'uxrdiwvctvilasinweqven' ] holecards = [[Card.from_str(s) for s in ss] for ss in [['2c', '3c'], ['Ah', 'Ac'], ['5d', '6d']]] game_state = restore_game_state(ThreePlayerGameStateSample.round_state) game_state = reduce( lambda state, item: attach_hole_card(state, item[0], item[1]), zip(uuids, holecards), game_state) sb_amount, ante = 5, 7 self.emu.set_game_rule(3, 10, sb_amount, ante) p1_acts = [('fold', 0), ('call', 10), ('call', 0), ('call', 10), ('fold', 0)] p2_acts = [] p3_acts = [('raise', 10)] players = [TestPlayer(acts) for acts in [p1_acts, p2_acts, p3_acts]] [ self.emu.register_player(uuid, player) for uuid, player in zip(uuids, players) ] game_state['table'].deck.deck.append(Card.from_str('7c')) game_state, events = self.emu.run_until_game_finish(game_state) self.eq('event_game_finish', events[-1]['type']) self.eq(0, game_state['table'].seats.players[0].stack) self.eq(0, game_state['table'].seats.players[1].stack) self.eq(292, game_state['table'].seats.players[2].stack)
def estimate_win_rate(self, hole, community): hole = [Card.from_str(c).to_id() for c in hole] community = [Card.from_str(c).to_id() for c in community] if len(community) == 0: return win_rate_estimates.estimates[hole[0] - 1][hole[1] - 1] return fast_monte_carlo.estimate_win_rate(100, hole, community)
def test_update_game_when_game_finished(self): uuid_list = ["hoge", "fuga", "boo"] name_list = ["HOGE", "FUGA", "BOO"] players_info = Engine.gen_players_info(uuid_list, name_list) game_config = Engine.gen_game_config(5, 100, 10, 1) engine = Engine.EngineWrapper() engine.start_game(players_info, game_config) # Fix cards used in the game to make game result deterministic engine.current_state['table'].deck = Deck(cheat=True, cheat_card_ids=range(6, 11)) for idx, player in enumerate( engine.current_state['table'].seats.players): player.hole_card = [ Card.from_id(idx * 2), Card.from_id(idx * 2 + 1) ] engine.update_game("raise", 99) engine.update_game("call", 99) original_msgs = engine.update_game("call", 99) hoge_msg, fuga_msg, boo_msg = [ _simplify_messages(msgs) for msgs in _classify_messages_by_destination( original_msgs, uuid_list) ] self.eq([MSG_GU, MSG_SS, MSG_SS, MSG_SS, MSG_RF, MSG_GF], hoge_msg) self.eq([MSG_GU, MSG_SS, MSG_SS, MSG_SS, MSG_RF, MSG_GF], fuga_msg) self.eq([MSG_GU, MSG_SS, MSG_SS, MSG_SS, MSG_RF, MSG_GF], boo_msg)
def test_onepair(self): hole = [Card(Card.CLUB, 3), Card(Card.CLUB, 4)] val = HandEvaluator.ONEPAIR | (5 << 4) | 0 self.false(ContributionChecker.check(hole, val)) val = HandEvaluator.ONEPAIR | (4 << 4) | 0 self.true(ContributionChecker.check(hole, val)) val = HandEvaluator.ONEPAIR | (3 << 4) | 0 self.true(ContributionChecker.check(hole, val))
def _restore_deck(str_exclude_cards): deck = Deck() exclude_ids = [Card.to_id(Card.from_str(s)) for s in str_exclude_cards] deck_cards = [ Card.from_id(cid) for cid in range(1, 53) if cid not in exclude_ids ] deck.deck = deck_cards return deck
def test_twopair(self): hole = [Card(Card.CLUB, 3), Card(Card.CLUB, 4)] val = HandEvaluator.TWOPAIR | (14 << 4) | 5 self.false(ContributionChecker.check(hole, val)) val = HandEvaluator.TWOPAIR | (14 << 4) | 3 self.true(ContributionChecker.check(hole, val)) val = HandEvaluator.TWOPAIR | (3 << 4) | 14 self.true(ContributionChecker.check(hole, val))
def test_threecard(self): hole = [Card(Card.CLUB, 3), Card(Card.CLUB, 4)] val = HandEvaluator.THREECARD | (5 << 4) | 0 self.false(ContributionChecker.check(hole, val)) val = HandEvaluator.THREECARD | (3 << 4) | 0 self.true(ContributionChecker.check(hole, val)) val = HandEvaluator.THREECARD | (4 << 4) | 0 self.true(ContributionChecker.check(hole, val))
def test_straight(self): hole = [Card(Card.CLUB, 7), Card(Card.CLUB, 8)] val = HandEvaluator.STRAIGHT | (6 << 4) | 0 self.true(ContributionChecker.check(hole, val)) val = HandEvaluator.STRAIGHT | (8 << 4) | 0 self.false(ContributionChecker.check(hole, val)) val = HandEvaluator.STRAIGHT | (3 << 4) | 0 self.false(ContributionChecker.check(hole, val))
def getScore(holeCards, commCards): # =========================================== # # Using PyPokerEngine's HandEvaluator # =========================================== # holeCards = [Card.from_str(card) for card in holeCards] commCards = [Card.from_str(card) for card in commCards] myScore = HandEvaluator.eval_hand(holeCards, commCards) return myScore
def _restore_deck(str_exclude_cards): deck = Deck() exclude_ids = [Card.to_id(Card.from_str(s)) for s in str_exclude_cards] deck_cards = [ Card.from_id(cid) for cid in Deck.GetFullDeck() if cid not in exclude_ids ] deck.cards = deck_cards return deck
def positive_potential(hole_cards, comm_cards): index = 0 ahead = 0 tied = 1 behind = 2 HP = list((0, 0, 0, 0, 0, 0, 0, 0, 0)) HPTotal = list((0, 0, 0)) deck = PlayerUtil.reduceDeck(PlayerUtil.getNewDeck(), comm_cards) deck = PlayerUtil.reduceDeck(deck, hole_cards) oppPossbileCards = PlayerUtil.getAllCombins(deck, 2) hole_cards = [Card.from_str(card) for card in hole_cards] comm_cards = [Card.from_str(card) for card in comm_cards] ourrank = HandEvaluator.eval_hand(hole_cards, comm_cards) if len(comm_cards) == 3: n = 1 elif len(comm_cards) == 4: n = 1 else: n = 0 for opp_cards in oppPossbileCards: possible_board_deck = copy.deepcopy(deck) possible_board_deck = PlayerUtil.reduceDeck( possible_board_deck, opp_cards) possible_board_cards = PlayerUtil.getAllCombins( possible_board_deck, n) opp_cards = [Card.from_str(card) for card in opp_cards] opprank = HandEvaluator.eval_hand(opp_cards, comm_cards) if ourrank > opprank: index = 0 elif ourrank == opprank: index = 1 else: index = 2 HPTotal[index] += 1 for p_board_card in possible_board_cards: p_board_card = [Card.from_str(card) for card in p_board_card] comm_cards_copy = copy.deepcopy(comm_cards) comm_cards_copy = comm_cards_copy + p_board_card ourbest = HandEvaluator.eval_hand(hole_cards, comm_cards_copy) oppbest = HandEvaluator.eval_hand(opp_cards, comm_cards_copy) if ourbest > oppbest: HP[index * 3 + ahead] += 1 elif ourbest == oppbest: HP[index * 3 + tied] += 1 else: HP[index * 3 + behind] += 1 PPot = (HP[behind * 3 + ahead] + HP[behind * 3 + tied] / 2 + HP[tied * 3 + ahead] / 2) / (HPTotal[behind] + HPTotal[tied] / 2) return PPot
def getScore(holeCards, commCards): # =========================================== # # Using PyPokerEngine's HandEvaluator # =========================================== # if not isinstance(holeCards, list): holeCards = literal_eval(holeCards) if not isinstance(commCards, list): commCards = literal_eval(commCards) holeCards = [Card.from_str(card) for card in holeCards] commCards = [Card.from_str(card) for card in commCards] myScore = HandEvaluator.eval_hand(holeCards, commCards) return myScore
def test_predict_on_flop(self): model = Neuralnet("flop") model.compile() hole = [Card(suit=Card.SPADE, rank=4), Card(suit=Card.SPADE, rank=2)] community = [ Card(suit=Card.DIAMOND, rank=12), Card(suit=Card.CLUB, rank=11), Card(suit=Card.DIAMOND, rank=10) ] prediction = model.predict(hole, community) self.almosteq(0.29, prediction, 0.01)
def to_hole_card(self, available_suits=None): if not available_suits: SUITS = np.array([2, 4, 8, 16]) cards = [] for rank in self.ranks: cards.append(Card(np.random.choice(SUITS, 1), rank)) return cards cards = [ Card(x[0], x[1]) for x in assign_suit(self.ranks, available_suits) ] # print('--') return cards
def raw_feed(self, hole, community, step): # step represent the number of community card: 0,3,4,5 assert (step in [0, 3, 4, 5]) hole_list = [] community_list = [] step_true = self.step_map[step] for card in hole: hole_list.append(Card.from_str(card)) for card in community: community_list.append(Card.from_str(card)) feature_vector = self.get_step_feature_vector(hole_list, community_list, step_true) self.step_list.append(feature_vector)
def EHS_5(self, hole_card, community_card): opp_possible_hole_cards = self.get_all_possible_opp_hole( hole_card, community_card) p_win = 0 hole_card_new = [Card.from_str(card) for card in hole_card] community_card_new = [Card.from_str(card) for card in community_card] for opp_hole_card in opp_possible_hole_cards: p_score = HandEvaluator.eval_hand(hole_card_new, community_card_new) o_score = HandEvaluator.eval_hand(opp_hole_card, community_card_new) p_win += int(p_score > o_score) return p_win / len(opp_possible_hole_cards)
def evaluateShowdown(holeCards, commCards, oppCards): # =========================================== # # Using PyPokerEngine's HandEvaluator # =========================================== # holeCards = [Card.from_str(card) for card in holeCards] commCards = [Card.from_str(card) for card in commCards] oppCards = [Card.from_str(card) for card in oppCards] myScore = HandEvaluator.eval_hand(holeCards, commCards) oppScore = HandEvaluator.eval_hand(oppCards, commCards) if myScore > oppScore: return 1 elif myScore == oppScore: return 0 else: return -1
def get_all_possible_opp_hole(self, hole_card, community_card): original_deck_set = set(range(1, 53)) hole_card_set = set( [Card.from_str(card).to_id() for card in hole_card]) community_card_set = set( [Card.from_str(card).to_id() for card in community_card]) revealed_set = hole_card_set.union(community_card_set) cheat_deck = list(original_deck_set - revealed_set) opp_possible_hole_card_id = self.combinations(cheat_deck, 2) opp_possible_hole_cards = [[ Card.from_id(id_pair[0]), Card.from_id(id_pair[1]) ] for id_pair in opp_possible_hole_card_id] return opp_possible_hole_cards
def evaluateShowdown(holeCards, commCards, oppCards, potAmt): # =========================================== # # Using PyPokerEngine's HandEvaluator # =========================================== # holeCards = [Card.from_str(card) for card in holeCards] commCards = [Card.from_str(card) for card in commCards] oppCards = [Card.from_str(card) for card in oppCards] myScore = HandEvaluator.eval_hand(holeCards, commCards) oppScore = HandEvaluator.eval_hand(oppCards, commCards) if myScore > oppScore: payout = potAmt elif myScore == oppScore: payout = potAmt / 2 else: payout = -potAmt return payout
def calculateHandValue(self, hole_cards, common_cards): properHoleCards = [] for c in hole_cards: properHoleCards.append(Card.from_str(c)) properCommunityCards = [] for c in common_cards: properCommunityCards.append(Card.from_str(c)) value = HandEvaluator.eval_hand(properHoleCards, properCommunityCards) # Massage the value to be [0-1] #adjvalue = (math.log(value,2)-14)/7 OLD FORMULA adjvalue = math.sqrt(math.sqrt(value))/37 #print(str(value) + " " + str(adjvalue)) return adjvalue
def test_run_until_game_finish_when_final_round(self): uuids = ["ruypwwoqwuwdnauiwpefsw", "sqmfwdkpcoagzqxpxnmxwm", "uxrdiwvctvilasinweqven"] holecards = [[Card.from_str(s) for s in ss] for ss in [["C2","C3"],["HA","CA"],["D5","H6"]]] game_state = restore_game_state(ThreePlayerGameStateSample.round_state) game_state = reduce(lambda state, item: attach_hole_card(state, item[0], item[1]), zip(uuids, holecards), game_state) sb_amount, ante = 5, 7 self.emu.set_game_rule(3, 10, sb_amount, ante) [self.emu.register_player(uuid, FoldMan()) for uuid in uuids] game_state["table"].deck.deck.append(Card.from_str("C7")) game_state, events = self.emu.run_until_game_finish(game_state) self.eq("event_game_finish", events[-1]["type"]) self.eq(10, game_state["round_count"]) self.eq(35, game_state["table"].seats.players[0].stack) self.eq(0, game_state["table"].seats.players[1].stack) self.eq(265, game_state["table"].seats.players[2].stack)
def test_state_after_forward_to_river(self): state, _ = self.__start_round() state, _ = RoundManager.apply_action(state, "fold", 0) state, _ = RoundManager.apply_action(state, "call", 10) state, _ = RoundManager.apply_action(state, "call", 10) state, _ = RoundManager.apply_action(state, "call", 0) state, _ = RoundManager.apply_action(state, "call", 0) state, _ = RoundManager.apply_action(state, "call", 0) state, msgs = RoundManager.apply_action(state, "call", 0) self.eq(Const.Street.RIVER, state["street"]) self.eq([Card.from_id(cid) for cid in range(7,12)], state["table"].get_community_card()) self.eq(3, len(msgs)) fetch_player = lambda uuid: [p for p in state["table"].seats.players if p.uuid==uuid][0] self.true(all(map(lambda p: len(p.action_histories)==0, state["table"].seats.players))) self.eq(2, len(fetch_player("uuid0").round_action_histories[Const.Street.PREFLOP])) self.eq(2, len(fetch_player("uuid1").round_action_histories[Const.Street.PREFLOP])) self.eq(1, len(fetch_player("uuid2").round_action_histories[Const.Street.PREFLOP])) self.eq(1, len(fetch_player("uuid0").round_action_histories[Const.Street.FLOP])) self.eq(1, len(fetch_player("uuid1").round_action_histories[Const.Street.FLOP])) self.eq(0, len(fetch_player("uuid2").round_action_histories[Const.Street.FLOP])) self.eq(1, len(fetch_player("uuid0").round_action_histories[Const.Street.TURN])) self.eq(1, len(fetch_player("uuid1").round_action_histories[Const.Street.TURN])) self.eq(0, len(fetch_player("uuid2").round_action_histories[Const.Street.TURN])) self.assertIsNone(fetch_player("uuid0").round_action_histories[Const.Street.RIVER])
def test_montecarlo_simulation(self): my_cards = U.gen_cards(["D6", "D2"]) community = U.gen_cards(['D5', 'D9', 'H6', 'CK']) mock_return = community + [Card.from_str("D7")] with patch('pypokerengine.utils.card_utils._fill_community_card', side_effect=[mock_return]): U._montecarlo_simulation(3, my_cards, community) U._fill_community_card.assert_called_with(community, used_card=my_cards + community) mock_return = [ U.gen_cards(a) for a in [["D7"], ["DK", "HK", "H8", "SA"]] ] with patch('pypokerengine.utils.card_utils._pick_unused_card', side_effect=mock_return): self.eq(1, U._montecarlo_simulation(3, my_cards, community)) U._pick_unused_card.assert_called_with(4, Any(list)) mock_return = [ U.gen_cards(a) for a in [["S7"], ["DK", "HK", "H8", "SA"]] ] with patch('pypokerengine.utils.card_utils._pick_unused_card', side_effect=mock_return): self.eq(0, U._montecarlo_simulation(3, my_cards, community)) U._pick_unused_card.assert_called_with(4, Any(list))
def draw_unknown_card(self, draw_num, known_cards): unknown_card_id = [cardid for cardid in range(1, 53)\ if cardid not in [card.to_id() for card in known_cards]] return [ Card.from_id(cardid) for cardid in random.sample(unknown_card_id, draw_num) ]
def test_replace_community_card(self): game_state = restore_game_state(TwoPlayerSample.round_state) to_card = lambda s: Card.from_str(s) cards = [to_card(c) for c in ['SA', 'DA', 'CA', 'HA']] processed = replace_community_card(game_state, cards) self.eq(cards, processed["table"].get_community_card()) self.neq(cards, game_state["table"].get_community_card())
def test_state_after_forward_to_flop(self): state, _ = self.__start_round() state, _ = RoundManager.apply_action(state, "fold", 0) state, _ = RoundManager.apply_action(state, "call", 10) state, _ = RoundManager.apply_action(state, "call", 10) self.eq(Const.Street.FLOP, state["street"]) self.eq(0, state["next_player"]) self.eq([Card.from_id(cid) for cid in range(7, 10)], state["table"].get_community_card()) fetch_player = lambda uuid: [ p for p in state["table"].seats.players if p.uuid == uuid ][0] self.true( all( map(lambda p: len(p.action_histories) == 0, state["table"].seats.players))) self.eq( 2, len( fetch_player("uuid0").round_action_histories[ Const.Street.PREFLOP])) self.eq( 2, len( fetch_player("uuid1").round_action_histories[ Const.Street.PREFLOP])) self.eq( 1, len( fetch_player("uuid2").round_action_histories[ Const.Street.PREFLOP])) self.assertIsNone( fetch_player("uuid0").round_action_histories[Const.Street.TURN])
def __fill_blank_card(self, holecard, community_): community = [Card.from_id(card.to_id()) for card in community_] # deep copy need_card = 5 - len(community) for card in self.draw_unknown_card(need_card, holecard + community): community.append(card) return community
def test_restore_game_state_three_players_game(self): restored = restore_game_state(ThreePlayerGameStateSample.round_state) table = restored["table"] players = restored["table"].seats.players self.eq(0, restored["next_player"]) self.eq(2, restored["street"]) self.eq(2, restored["round_count"]) self.eq(5, restored["small_blind_amount"]) self.eq(1, table.dealer_btn) self.eq(1, table.sb_pos()) self.eq(2, table.bb_pos()) self.eq(['HJ', 'C8', 'D2', 'H4'], [str(card) for card in table.get_community_card()]) self._assert_deck(table.deck, [Card.from_str(s) for s in ['HJ', 'C8', 'D2', 'H4']]) self.eq(3, len(players)) self._assert_player( ["p1", "ruypwwoqwuwdnauiwpefsw", [], 35, ThreePlayerGameStateSample.p1_round_action_histories, \ ThreePlayerGameStateSample.p1_action_histories, 0, 60], players[0]) self._assert_player( ["p2", "sqmfwdkpcoagzqxpxnmxwm", [], 0, ThreePlayerGameStateSample.p2_round_action_histories, \ ThreePlayerGameStateSample.p2_action_histories, 1, 50], players[1]) self._assert_player( ["p3", "uxrdiwvctvilasinweqven", [], 85, ThreePlayerGameStateSample.p3_round_action_histories, \ ThreePlayerGameStateSample.p3_action_histories, 0, 70], players[2])
def test_replace_community_card(self): game_state = restore_game_state(TwoPlayerSample.round_state) to_card = lambda s: Card.from_str(s) cards = [to_card(c) for c in ['SA', 'DA', 'CA', 'HA']] processed = replace_community_card(game_state, cards) self.eq(cards, processed["table"].get_community_card()) self.neq(cards, game_state["table"].get_community_card())
def deserialize(self, serial): hole = [Card.from_id(cid) for cid in serial[3]] player = self(serial[1], serial[2], serial[0]) if len(hole)!=0: player.add_holecard(hole) player.action_histories = serial[4] player.pay_info = PayInfo.deserialize(serial[5]) player.round_action_histories = serial[6] return player
def test_cheat_serialization(self): cards = [Card.from_id(cid) for cid in [12, 15, 17]] cheat = Deck(cheat=True, cheat_card_ids=[12, 15, 17]) serial = cheat.serialize() restored = Deck.deserialize(serial) self.eq(cheat.deck, restored.deck) self.eq(cheat.cheat, restored.cheat) self.eq(cheat.cheat_card_ids, restored.cheat_card_ids)
def gen_deck(exclude_cards=None): deck_ids = range(1, 53) if exclude_cards: assert isinstance(exclude_cards, list) if isinstance(exclude_cards[0], str): exclude_cards = [Card.from_str(s) for s in exclude_cards] exclude_ids = [card.to_id() for card in exclude_cards] deck_ids = [i for i in deck_ids if not i in exclude_ids] return Deck(deck_ids)
def test_run_until_game_finish_when_one_player_is_left(self): uuids = ["ruypwwoqwuwdnauiwpefsw", "sqmfwdkpcoagzqxpxnmxwm", "uxrdiwvctvilasinweqven"] holecards = [[Card.from_str(s) for s in ss] for ss in [["C2","C3"],["HA","CA"],["D5","H6"]]] game_state = restore_game_state(ThreePlayerGameStateSample.round_state) game_state = reduce(lambda state, item: attach_hole_card(state, item[0], item[1]), zip(uuids, holecards), game_state) sb_amount, ante = 5, 7 self.emu.set_game_rule(3, 10, sb_amount, ante) p1_acts = [("fold",0), ("call", 10), ('call', 0), ('call', 10), ("fold",0)] p2_acts = [] p3_acts = [("raise", 10)] players = [TestPlayer(acts) for acts in [p1_acts, p2_acts, p3_acts]] [self.emu.register_player(uuid, player) for uuid, player in zip(uuids, players)] game_state["table"].deck.deck.append(Card.from_str("C7")) game_state, events = self.emu.run_until_game_finish(game_state) self.eq("event_game_finish", events[-1]["type"]) self.eq(0, game_state["table"].seats.players[0].stack) self.eq(0, game_state["table"].seats.players[1].stack) self.eq(292, game_state["table"].seats.players[2].stack)
def test_attach_hole_card(self): game_state = restore_game_state(TwoPlayerSample.round_state) to_card = lambda s: Card.from_str(s) hole1, hole2 = [to_card(c) for c in ["SA", "DA"]], [to_card(c) for c in ["HK", "C2"]] processed1 = attach_hole_card(game_state, "tojrbxmkuzrarnniosuhct", hole1) processed2 = attach_hole_card(processed1, "pwtwlmfciymjdoljkhagxa", hole2) players = processed2["table"].seats.players self.eq(hole1, players[0].hole_card) self.eq(hole2, players[1].hole_card) self.eq([0,0], [len(p.hole_card) for p in game_state["table"].seats.players])
def __setup_player_for_serialization(self): player = Player("uuid", 50, "hoge") player.add_holecard([Card.from_id(cid) for cid in range(1,3)]) player.add_action_history(Const.Action.SMALL_BLIND, sb_amount=5) player.save_street_action_histories(Const.Street.PREFLOP) player.add_action_history(Const.Action.CALL, 10) player.add_action_history(Const.Action.RAISE, 10, 5) player.add_action_history(Const.Action.FOLD) player.pay_info.update_by_pay(15) player.pay_info.update_to_fold() return player
def test_run_until_round_finish_game_finish_detect(self): uuids = ["tojrbxmkuzrarnniosuhct", "pwtwlmfciymjdoljkhagxa"] holecards = [[Card.from_str(s) for s in ss] for ss in [["CA", "D2"], ["C8", "H5"]]] game_state = restore_game_state(TwoPlayerSample.round_state) game_state = reduce(lambda a,e: attach_hole_card(a, e[0], e[1]), zip(uuids, holecards), game_state) game_state = attach_hole_card_from_deck(game_state, "pwtwlmfciymjdoljkhagxa") self.emu.set_game_rule(2, 10, 5, 0) p1 = TestPlayer([("raise", 65)]) p2 = TestPlayer([("call", 15), ("call", 65)]) self.emu.register_player("tojrbxmkuzrarnniosuhct", p1) self.emu.register_player("pwtwlmfciymjdoljkhagxa", p2) game_state["table"].deck.deck.append(Card.from_str("C7")) game_state, events = self.emu.run_until_round_finish(game_state) self.eq("event_new_street", events[0]["type"]) self.eq("event_ask_player", events[1]["type"]) self.eq("event_ask_player", events[2]["type"]) self.eq("event_round_finish", events[3]["type"]) self.eq("event_game_finish", events[4]["type"]) self.eq(0, events[4]["players"][0]["stack"]) self.eq(200, events[4]["players"][1]["stack"])
def __generate_input_for_cnn(self, hole, community): to_id = lambda card: card.to_id() gen_card_rank_vec = lambda card: [1 if r == card.rank else 0 for r in range(2,15)] gen_card_suit_vec = lambda card: [1 if s == card.suit else 0 for s in [Card.CLUB, Card.DIAMOND, Card.HEART, Card.SPADE]] gen_card_vec = lambda card: gen_card_rank_vec(card) + gen_card_suit_vec(card) gen_img = lambda zipped: [gen_card_vec(Card.from_id(card_id)) for card_id in zipped[0]+zipped[1]] wrap = lambda lst: np.array(lst) to_ndarray = lambda X: wrap([wrap(x) for x in X]) hole_ids = map(to_id, hole) community_ids = map(to_id, community) x = gen_img((hole_ids, community_ids)) X = to_ndarray(x) X = np.array([X.reshape(1, X.shape[0], X.shape[1])]) return X
def setup_table(): table = Table() players = [Player("uuid%d"%i, 100, "hoge") for i in range(3)] table.seats.players = players table.add_community_card(Card.from_id(1)) table.dealer_btn = 2 table.set_blind_pos(2, 0) p1, p2, p3 = table.seats.players p3.add_action_history(Const.Action.RAISE, 10, 5) p1.add_action_history(Const.Action.FOLD) p2.add_action_history(Const.Action.RAISE, 20, 10) p3.add_action_history(Const.Action.CALL, 20) [p.save_street_action_histories(Const.Street.PREFLOP) for p in [p1, p2, p3]] p3.add_action_history(Const.Action.CALL, 5) p2.add_action_history(Const.Action.RAISE, 5, 5) return table
def test_restore_game_state_two_players_game(self): restored = restore_game_state(TwoPlayerSample.round_state) table = restored["table"] players = restored["table"].seats.players self.eq(1, restored["next_player"]) self.eq(2, restored["street"]) self.eq(3, restored["round_count"]) self.eq(5, restored["small_blind_amount"]) self.eq(0, table.dealer_btn) self.eq(0, table.sb_pos()) self.eq(1, table.bb_pos()) self.eq(['D5', 'D9', 'H6', 'CK'], [str(card) for card in table.get_community_card()]) self._assert_deck(table.deck, [Card.from_str(s) for s in ['D5', 'D9', 'H6', 'CK']]) self.eq(2, len(players)) self._assert_player(["p1", "tojrbxmkuzrarnniosuhct", [], 65, TwoPlayerSample.p1_round_action_histories,\ TwoPlayerSample.p1_action_histories, 0, 35], players[0]) self._assert_player(["p2", "pwtwlmfciymjdoljkhagxa", [], 80, TwoPlayerSample.p2_round_action_histories,\ TwoPlayerSample.p2_action_histories, 0, 20], players[1])
def test_restore_game_state_three_players_game(self): restored = restore_game_state(ThreePlayerGameStateSample.round_state) table = restored["table"] players = restored["table"].seats.players self.eq(0, restored["next_player"]) self.eq(2, restored["street"]) self.eq(2, restored["round_count"]) self.eq(5, restored["small_blind_amount"]) self.eq(1, table.dealer_btn) self.eq(1, table.sb_pos()) self.eq(2, table.bb_pos()) self.eq(['HJ', 'C8', 'D2', 'H4'], [str(card) for card in table.get_community_card()]) self._assert_deck(table.deck, [Card.from_str(s) for s in ['HJ', 'C8', 'D2', 'H4']]) self.eq(3, len(players)) self._assert_player(["p1", "ruypwwoqwuwdnauiwpefsw", [], 35, ThreePlayerGameStateSample.p1_round_action_histories,\ ThreePlayerGameStateSample.p1_action_histories, 0, 60], players[0]) self._assert_player(["p2", "sqmfwdkpcoagzqxpxnmxwm", [], 0, ThreePlayerGameStateSample.p2_round_action_histories,\ ThreePlayerGameStateSample.p2_action_histories, 1, 50], players[1]) self._assert_player(["p3", "uxrdiwvctvilasinweqven", [], 85, ThreePlayerGameStateSample.p3_round_action_histories,\ ThreePlayerGameStateSample.p3_action_histories, 0, 70], players[2])
def test_add_too_many_hole_card(self): self.player.add_holecard([Card.from_id(cid) for cid in range(1,4)])
def test_deal_holecard(self): state, _ = self.__start_round() players = state["table"].seats.players self.eq([Card.from_id(1), Card.from_id(2)], players[0].hole_card) self.eq([Card.from_id(3), Card.from_id(4)], players[1].hole_card)
def __init__(self, deck_ids=None, cheat=False, cheat_card_ids=[]): self.cheat = cheat self.cheat_card_ids = cheat_card_ids self.deck = [Card.from_id(cid) for cid in deck_ids] if deck_ids else self.__setup()
def test_add_holecard(self): cards = [Card.from_id(cid) for cid in range(1,3)] self.player.add_holecard(cards) self.true(cards[0] in self.player.hole_card) self.true(cards[1] in self.player.hole_card)
def __setup_52_cards(self): return [Card.from_id(cid) for cid in range(1,53)]
def test_add_single_hole_card(self): self.player.add_holecard([Card.from_id(1)])
# # Data Processing # ## card id -> 1-hot vector # In[63]: import numpy as np from pypokerengine.engine.card import Card fetch_hole = lambda row: [row[key] for key in ['hole1_id', 'hole2_id']] fetch_community = lambda row: [row[key] for key in ['community1_id', 'community2_id', 'community3_id']] gen_card_rank_vec = lambda card: [1 if r == card.rank else 0 for r in range(2,15)] gen_card_suit_vec = lambda card: [1 if s == card.suit else 0 for s in [Card.CLUB, Card.DIAMOND, Card.HEART, Card.SPADE]] gen_card_vec = lambda card: gen_card_rank_vec(card) + gen_card_suit_vec(card) gen_img = lambda zipped: [gen_card_vec(Card.from_id(card_id)) for card_id in zipped[0]+zipped[1]] train_hole = train_df.apply(lambda row: fetch_hole(row), axis=1) train_community = train_df.apply(lambda row: fetch_community(row), axis=1) train_df["onehot"] = map(gen_img, zip(train_hole, train_community)) test_hole = test_df.apply(lambda row: fetch_hole(row), axis=1) test_community = test_df.apply(lambda row: fetch_community(row), axis=1) test_df["onehot"] = map(gen_img, zip(test_hole, test_community)) # ## Format data (pandas.df -> numpy.ndarray) # In[65]: wrap = lambda lst: np.array(lst)
def __setup_table(self): table = Table() table.set_blind_pos(0, 1) table.seats = self.__setup_seats() table.add_community_card(Card.from_id(1)) return table
def __setup_cheat_deck(self): cards = [Card.from_id(cid) for cid in self.cheat_card_ids] return cards[::-1]
def __fill_blank_card(self, holecard, community_): community = [Card.from_id(card.to_id()) for card in community_] # deep copy need_card = 5 - len(community) for card in self.draw_unknown_card(need_card, holecard + community): community.append(card) return community
def draw_unknown_card(self, draw_num, known_cards): unknown_card_id = [cardid for cardid in range(1, 53)\ if cardid not in [card.to_id() for card in known_cards]] return [Card.from_id(cardid) for cardid in random.sample(unknown_card_id, draw_num)]
def setup_player(): player = setup_player_with_payinfo(0, "hoge", 50, PayInfo.FOLDED) player.add_holecard([Card.from_id(1), Card.from_id(2)]) player.add_action_history(Const.Action.CALL, 50) return player
def __extract_used_card(self, deck, used_cards): deck.deck = [Card.from_id(card.to_id()) for card in deck.deck \ if not card.to_id() in [used_card.to_id() for used_card in used_cards]] return deck
def test_add_hole_card_twice(self): self.player.add_holecard([Card.from_id(cid) for cid in range(1,3)]) self.player.add_holecard([Card.from_id(cid) for cid in range(1,3)])
def __setup_players(self): hole = [Card.from_id(1), Card.from_id(2)] players = [self.__setup_player() for _ in range(3)] players[1].add_holecard(hole) return players
def test_clear_holecard(self): self.player.add_holecard([Card.from_id(cid) for cid in range(1,3)]) self.player.clear_holecard() self.eq(0, len(self.player.hole_card))