Exemplo n.º 1
0
    def get_win_prob(self, hand_cards, board_cards, simulation_number,
                     num_players):
        win = 0
        round = 0
        evaluator = HandEvaluator()
        for i in range(simulation_number):

            board_cards_to_draw = 5 - len(board_cards)  # 2
            board_sample = board_cards + self._pick_unused_card(
                board_cards_to_draw, board_cards + hand_cards)
            unused_cards = self._pick_unused_card((num_players - 1) * 2,
                                                  hand_cards + board_sample)
            opponents_hole = [
                unused_cards[2 * i:2 * i + 2] for i in range(num_players - 1)
            ]
            opponents_score = [
                pow(evaluator.evaluate_hand(hole, board_sample), num_players)
                for hole in opponents_hole
            ]
            my_rank = pow(evaluator.evaluate_hand(hand_cards, board_sample),
                          num_players)
            if my_rank >= max(opponents_score):
                win += 1
            round += 1
        # The large rank value means strong hand card
        win_prob = win / float(round)
        print "win_prob:{}".format(win_prob), "Win:{}".format(win)
        return win_prob
Exemplo n.º 2
0
 def declareAction(self, state, minBet, seat_num):
     # X_feature = ["round", "number_players", "total_pot", "chips", "rank", "big_blind",
     #              "round_bet", "phase_bet", "isSB", "isBB"]
     # d = get_log_data(state, seat_num)
     phase = ROUND_NAME_TO_NUM[state.table_state.round]
     number_players = state.table_state.number_players
     big_blind = state.table_state.big_blind_amount
     total_pot = state.table_state.total_pot / big_blind
     chips = state.player_state[seat_num].chips / big_blind
     evaluator = HandEvaluator()
     rank = evaluator.evaluate_hand(state.player_state[seat_num].hand,
                                    state.table_state.board)
     round_bet = state.player_state[seat_num].round_bet / big_blind
     phase_bet = state.player_state[seat_num].bet / big_blind
     isSB = 1 if state.player_state[
         seat_num].player_name == state.table_state.small_blind else 0
     isBB = 1 if state.player_state[
         seat_num].player_name == state.table_state.big_blind else 0
     features = [
         phase, number_players, total_pot, chips, rank, big_blind,
         round_bet, phase_bet, isSB, isBB
     ]
     action = self.model[phase].predict([features])
     if action == 1:
         action = 'call'
     else:
         action = 'fold'
     print action
     amount = 0
     return action, amount
Exemplo n.º 3
0
    def get_win_prob(self, hand_cards, board_cards, simulation_number, num_players):
        """Calculate the win probability from your board cards and hand cards by using simple Monte Carlo method.
        Args:
            board_cards: The board card list.
            hand_cards: The hand card list
        Examples:
#            >>> get_win_prob(["8H", "TS", "6C"], ["7D", "JC"])
        """
        win = 0
        round = 0
        evaluator = HandEvaluator()
        for i in range(simulation_number):

            board_cards_to_draw = 5 - len(board_cards)  # 2
            board_sample = board_cards + self._pick_unused_card(board_cards_to_draw, board_cards + hand_cards)
            unused_cards = self._pick_unused_card((num_players - 1) * 2, hand_cards + board_sample)
            opponents_hole = [unused_cards[2 * i:2 * i + 2] for i in range(num_players - 1)]

            try:
                opponents_score = [pow(evaluator.evaluate_hand(hole, board_sample), num_players) for hole in
                                   opponents_hole]
                # hand_sample = self._pick_unused_card(2, board_sample + hand_cards)
                my_rank = pow(evaluator.evaluate_hand(hand_cards, board_sample), num_players)
                if my_rank >= max(opponents_score):
                    win += 1
                # rival_rank = evaluator.evaluate_hand(hand_sample, board_sample)
                round += 1
            except Exception, e:
                print e.message
                continue
Exemplo n.º 4
0
    def get_win_prob(self, hand_cards, board_cards, num_players):

        win = 0
        round = 0
        evaluator = HandEvaluator()

        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, board_cards + hand_cards)

            unused_cards = self._pick_unused_card((num_players - 1) * 2,
                                                  hand_cards + board_sample)
            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 = [
                    evaluator.evaluate_hand(hole, board_sample)
                    for hole in opponents_hole
                ]
                my_rank = evaluator.evaluate_hand(hand_cards, board_sample)
                if my_rank >= max(opponents_score):
                    win += 1
                #rival_rank = evaluator.evaluate_hand(hand_sample, board_sample)
                round += 1
            except Exception, e:
                #print e.message
                continue
Exemplo n.º 5
0
    def get_win_prob(self, hand_cards, board_cards, simulation_number, num_players):
        win = 0
        round=0
        evaluator = HandEvaluator()
        for i in range(simulation_number):

            board_cards_to_draw = 5 - len(board_cards)  # 2
            board_sample = board_cards + self._pick_unused_card(board_cards_to_draw, board_cards + hand_cards)
            unused_cards = self._pick_unused_card((num_players - 1)*2, hand_cards + board_sample)
            opponents_hole = [unused_cards[2 * i:2 * i + 2] for i in range(num_players - 1)]
            temp = []

            try:
                for hole in opponents_hole:
                    temp = hole + board_sample
                    opponents_score = pow(evaluator.evaluate_hand(hole, board_sample), num_players)
                #opponents_score = [pow(evaluator.evaluate_hand(hole, board_sample), num_players) for hole in opponents_hole]
                # hand_sample = self._pick_unused_card(2, board_sample + hand_cards)
                my_rank = pow(evaluator.evaluate_hand(hand_cards, board_sample), num_players)
                if my_rank > max(opponents_score):
                    win += 1
                elif my_rank == max(opponents_score):
                    win += 0.5
                #rival_rank = evaluator.evaluate_hand(hand_sample, board_sample)
                round += 1
            except Exception, e:
                self.logger.error('exception={}, temp={}'.format(e.message, temp))
                continue
Exemplo n.º 6
0
def get_log_data(state, player_index):
    # 'log_data', ['player_name', 'round', 'number_players', 'round_count', 'board', 'total_pot', 'action',
    #              'amount', 'chips', 'hand', 'rank', 'big_blind', 'round_bet', 'phase_bet', 'win_money',
    #              'isSB', 'isBB']
    evaluator = HandEvaluator()
    rank = evaluator.evaluate_hand(state.player_state[player_index].hand,
                                   state.table_state.board)
    alive_players = [
        player for player in state.player_state if player.isSurvive
    ]

    phase = ROUND_NAME_TO_NUM[state.table_state.round]
    phase_raise = state.player_state[player_index].phase_raise[phase]
    phase_raise = phase_raise - 1 if state.player_state[
        player_index].action == 2 else phase_raise
    last_phase_raise = -1 if phase == 0 else state.player_state[
        player_index].phase_raise[phase - 1]
    # isBTN
    isSB = 1 if state.player_state[
        player_index].player_name == state.table_state.small_blind else 0
    isBB = 1 if state.player_state[
        player_index].player_name == state.table_state.big_blind else 0
    log_data = LOG_DATA(
        state.player_state[player_index].player_name,
        int(state.table_state.table_number),
        int(state.table_state.round_count),
        int(ROUND_NAME_TO_NUM[state.table_state.round]),
        int(state.table_state.number_players),
        state.table_state.board,
        float((state.table_state.total_pot -
               state.player_state[player_index].amount) /
              state.table_state.big_blind_amount),
        int(state.player_state[player_index].action),
        float(state.player_state[player_index].amount /
              state.table_state.big_blind_amount),
        float((state.player_state[player_index].chips +
               state.player_state[player_index].amount) /
              state.table_state.big_blind_amount),
        state.player_state[player_index].hand,
        float(rank),
        int(state.table_state.big_blind_amount),
        float((state.player_state[player_index].round_bet -
               state.player_state[player_index].amount) /
              state.table_state.big_blind_amount),
        float((state.player_state[player_index].bet -
               state.player_state[player_index].amount) /
              state.table_state.big_blind_amount),
        int(phase_raise),
        int(last_phase_raise),
        int(state.player_state[player_index].last_action),
        float(state.player_state[player_index].last_amount /
              state.table_state.big_blind_amount),
        0.0,  # win_money
        # isBTN,
        int(isSB),
        int(isBB))
    return log_data
Exemplo n.º 7
0
    def get_win_prob(self, hand_cards, board_cards, num_players):
        """Calculate the win probability from your board cards and hand cards by using simple Monte Carlo method.

        Args:
            board_cards: The board card list.
            hand_cards: The hand card list

        Examples:
            >>> get_win_prob(["8H", "TS", "6C"], ["7D", "JC"])
        """
        LOG.info(
            "------------MontecarloPokerBot get_win_prob---------------------")
        win = 0
        round = 0
        evaluator = HandEvaluator()

        for i in range(self.simulation_number):
            board_cards_to_draw = 5 - len(board_cards)  # 2
            LOG.info("board_cards_to_draw:{}".format(board_cards_to_draw))
            board_sample = board_cards + self._pick_unused_card(
                board_cards_to_draw, board_cards + hand_cards)
            LOG.info("board_sample:{}".format(board_sample))
            unused_cards = self._pick_unused_card((num_players - 1) * 2,
                                                  hand_cards + board_sample)
            opponents_hole = [
                unused_cards[2 * i:2 * i + 2] for i in range(num_players - 1)
            ]
            LOG.info("opponents_hole:{}".format(opponents_hole))
            hand_sample = self._pick_unused_card(2, board_sample + hand_cards)
            LOG.info("hand_sample:{}".format(hand_sample))

            try:
                opponents_score = [
                    evaluator.evaluate_hand(hole, board_sample)
                    for hole in opponents_hole
                ]
                LOG.info("opponents_score:{}".format(opponents_score))
                my_rank = evaluator.evaluate_hand(hand_cards, board_sample)
                LOG.info("my_rank:{}".format(my_rank))
                if my_rank >= max(opponents_score):
                    win += 1
                rival_rank = evaluator.evaluate_hand(hand_sample, board_sample)
                LOG.info("rival_rank:{}".format(rival_rank))
                round += 1
            except Exception, e:
                print "get_win_prob exception:{},{}".format(i, e)
                continue
Exemplo n.º 8
0
    def simulation(self, my_score, data, sim_num=1000):

        return self.calc_win_prob_by_sampling_eval7(self.cards, self.board, data, sim_num)

        eval_hand = getCard(self.cards)
        eval_board = getCard(self.board)
        evaluator = HandEvaluator()
        win = 0
        sampling = 0
        for _ in range(sim_num):
            board_cards_to_draw = 5 - len(eval_board)
            board_sample = eval_board + pick_unused_card(board_cards_to_draw, eval_hand + eval_board)

            unused_cards = pick_unused_card(2, eval_hand + board_sample)
            opponents_hole = unused_cards[0:2]
            try:
                opponents_score = evaluator.evaluate_hand(opponents_hole, board_sample)
                if opponents_score > my_score:  # opponent win probability
                    win += 1
                sampling += 1
            except Exception:
                continue

        return win / float(sampling)
Exemplo n.º 9
0
    def takeAction(self, action, data):
        # Get number of players and table info
        if action == "__game_start":
            # print("Game Start")
            table_number = data['tableNumber']
            self.table = Table(table_number)
            return False
        elif action == "__new_round":
            print("New Round")
            self.predict_rank_data = []
            table_data = data['table']
            players_data = data['players']
            if self.table is None:
                # raise ("Error: Table is None.")
                table_number = table_data['tableNumber']
                self.table = Table(table_number)
            self.table.update_table_status(data)

            if len(self.players) == 0:  # first time join the game
                for i, p in enumerate(players_data):
                    if p['playerName'] == self.md5_name:
                        self.players.append(
                            Player(p['playerName'], p['chips'], self.pokerbot))
                    else:
                        self.players.append(Player(p['playerName'],
                                                   p['chips']))
            for i, p in enumerate(self.players):
                p.update_by_state(players_data[i])
            return False
        elif action == "__show_action":
            player_index = utils.get_index_from_player_list(
                data['action']['playerName'], self.players)
            self.players[player_index].update_action(data['action'])
            #  get predict rank data
            state = utils.get_current_state(self.table, self.players)
            rank_info = utils.get_rank_data(state, player_index)
            self.predict_rank_data.append(rank_info)

            #  update table and player
            self.table.update_table_status(data)
            for i, p in enumerate(self.players):
                p.update_by_state(data['players'][i])
            #  record some states
            return False
        elif action == "__bet":
            print("Bet")
            action, amount = self.getAction(data)
            print "action: {}".format(action)
            print "action amount: {}".format(amount)
            self.ws.send(
                json.dumps({
                    "eventName": "__action",
                    "data": {
                        "action": action,
                        "playerName": self.playerName,
                        "amount": amount
                    }
                }))
            return False
        elif action == "__action":
            print("Action")
            action, amount = self.getAction(data)
            print "action: {}".format(action)
            print "action amount: {}".format(amount)
            self.ws.send(
                json.dumps({
                    "eventName": "__action",
                    "data": {
                        "action": action,
                        "playerName": self.playerName,
                        "amount": amount
                    }
                }))
            return False
        elif action == "__deal":
            print "Deal Cards"
            self.table.update_table_status(data)
            for i, p in enumerate(self.players):
                p.update_by_state(data['players'][i])
            return False
        elif action == "__start_reload":
            print "Reload"
            # self.ws.send(json.dumps({
            #     "eventName": "__reload",
            # }))
            # self.ws.send(json.dumps({
            #     "eventName": "__reload",
            # }))
            return False
        elif action == "__round_end":
            print "Round End"
            # update card and rank for each player
            evaluator = HandEvaluator()
            for player in data['players']:
                for i, rank_data in enumerate(self.predict_rank_data):
                    if rank_data.player_name == player['playerName']:
                        if not player[
                                'isOnline']:  # if player is not online, delete the record
                            self.predict_rank_data.remove(rank_data)
                        else:
                            hand = []
                            for card in player['cards']:
                                hand.append(utils.getCard(card))
                            board = self.predict_rank_data[i].board
                            self.predict_rank_data[i] = self.predict_rank_data[
                                i]._replace(cards=hand)
                            # hand, board = utils.str_list_to_card(self.predict_rank_data[i].cards,
                            #                                      self.predict_rank_data[i].board)
                            rank = evaluator.evaluate_hand(hand, board)
                            # print("rank: {}".format(rank))
                            self.predict_rank_data[i] = self.predict_rank_data[
                                i]._replace(rank=rank)
            utils.state_to_csv(utils.PREDICT_RANK_DATA, "log/",
                               self.predict_rank_data)
            return False
        elif action == "__game_over":
            print "Game Over"
            self.table = None
            self.players = []
            self.ws.send(
                json.dumps({
                    "eventName": "__join",
                    "data": {
                        "playerName": self.playerName
                    }
                }))
            return True
Exemplo n.º 10
0
    def takeAction(self, action, data):
        # Get number of players and table info
        if action == "__game_start":
            # print("Game Start")
            table_number = data['tableNumber']
            self.table = Table(table_number)
            return False
        elif action == "__new_round":
            # print("New Round")
            table_data = data['table']
            players_data = data['players']
            if self.table is None:
                # raise ("Error: Table is None.")
                table_number = table_data['tableNumber']
                self.table = Table(table_number)
            self.table.update_table_status(data)

            if len(self.players) == 0:  # first time join the game
                for i, p in enumerate(players_data):
                    if p['playerName'] == self.md5_name:
                        self.players.append(
                            Player(p['playerName'], p['chips'], self.pokerbot))
                    else:
                        self.players.append(Player(p['playerName'],
                                                   p['chips']))
            for i, p in enumerate(self.players):
                p.new_round()
                p.update_by_state(players_data[i])
            return False
        elif action == "__show_action":
            player_index = utils.get_index_from_player_list(
                data['action']['playerName'], self.players)
            self.players[player_index].update_action(
                data['action'], data['table']['roundName'])
            #  update table and player
            self.table.update_table_status(data)
            for i, p in enumerate(self.players):
                p.update_by_state(data['players'][i])
            return False
        elif action == "__bet":
            # print("Bet")
            action, amount = self.getAction(data)
            # print "action: {}".format(action)
            # print "action amount: {}".format(amount)
            self.ws.send(
                json.dumps({
                    "eventName": "__action",
                    "data": {
                        "action": action,
                        "playerName": self.playerName,
                        "amount": amount
                    }
                }))
            return False
        elif action == "__action":
            # print("Action")
            action, amount = self.getAction(data)
            # print "action: {}".format(action)
            # print "action amount: {}".format(amount)
            self.ws.send(
                json.dumps({
                    "eventName": "__action",
                    "data": {
                        "action": action,
                        "playerName": self.playerName,
                        "amount": amount
                    }
                }))
            return False
        elif action == "__deal":
            print "Deal Cards"
            self.table.update_table_status(data)
            for i, p in enumerate(self.players):
                p.update_by_state(data['players'][i])
            player_index = utils.get_index_from_player_list(
                self.md5_name, self.players)
            print "hands: {}, board: {}".format(
                data['players'][player_index]['cards'], data['table']['board'])
            return False
        elif action == "__start_reload":
            # print "Reload"
            # self.ws.send(json.dumps({
            #     "eventName": "__reload",
            # }))
            # self.ws.send(json.dumps({
            #     "eventName": "__reload",
            # }))
            return False
        elif action == "__round_end":
            print "Round End"
            state = utils.get_current_state(self.table, self.players)
            player_index = utils.get_index_from_player_list(
                self.md5_name, self.players)
            player_data = data['players']
            win_money = player_data[player_index]['winMoney']
            evaluator = HandEvaluator()
            rank = evaluator.evaluate_hand(
                state.player_state[player_index].hand, state.table_state.board)
            chips = player_data[player_index]['chips']
            print "hands: {}, board: {}, rank: {}".format(
                state.player_state[player_index].hand, state.table_state.board,
                rank)
            print "win money: {}, remain chips: {}".format(win_money, chips)

            return False
        elif action == "__game_over":
            print "Game Over"
            self.table = None
            self.players = []
            return True