Exemplo n.º 1
0
def test(response):

	deck = build_deck()
	board = []
	hole = []
	hole2 = []
	response = ""
	for i in range(5):
		card = compute_draw_card(deck)
		board.append(Card(card.power, card.suit))
		response = response + " " + card.name
	
	response = response + "-------- P1 "
	for i in range(2):
		card = compute_draw_card(deck)
		hole.append(Card(card.power, card.suit))
		response = response + " " + card.name
	response = response + "-------- P2 "

	for i in range(2):
		card = compute_draw_card(deck)
		hole2.append(Card(card.power, card.suit))
		response = response + " " + card.name
	
	response = response + "------------ Score "

	score = HandEvaluator.evaluate_hand(hole, board)
	score2 = HandEvaluator.evaluate_hand(hole2, board)
	return HttpResponse(response + "" + str(score) + " " + str(score2))
Exemplo n.º 2
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.º 3
0
def play_game(num_opponents, hand, community, deck):
	# Shuffle the deck and create a copy of the community cards
	shuffle(deck)
	community_copy = [Card(*c) for c in community]
	
	# Deal cards to each opponent
	opponents = []
	for i in range(num_opponents):
		c1 = deck[i * 2]
		c2 = deck[i * 2 + 1]
		opponents.append([Card(*c1), Card(*c2)])
		
	# Fill up the community cards
	for i in range(5 - len(community)):
		c = deck[num_opponents * 2 + i]
		community_copy.append(Card(*c))
	
	# Score each opponent
	max_opponent = max([HandEvaluator.evaluate_hand(opponent, community_copy) for opponent in opponents])
	
	# Score my hand
	my_hand = [Card(*c) for c in hand]
	my_score = HandEvaluator.evaluate_hand(my_hand, community_copy)

	# Calculate the winner
	if my_score > max_opponent:
		return True
	elif my_score == max_opponent:
		return random() > 0.5
	else:
		return False
Exemplo n.º 4
0
	def play(self):
		self.players[self.dealer].stack -= self.blind;
		self.players[1-self.dealer].stack -= self.blind/2;
		self.pot += 3*self.blind/2;

		while True:	
			self.deal();
			self.table.update_action('', 0);
			self.table.update_action('', 1);
			self.updateTable()
			self.printStatus();
			print self.board;
			winner = self.bid();
			if winner > -1:
				break;
			if self.state == "done":
				board = [self.deck.cardstoC[c] for c in self.board];
				hole0 = [self.deck.cardstoC[c] for c in self.players[0].cards]
				hole1 = [self.deck.cardstoC[c] for c in self.players[1].cards]
				score0 = HandEvaluator.evaluate_hand(hole0, board)
				score1 = HandEvaluator.evaluate_hand(hole1, board)
				self.state = "show_cards";
				self.updateTable();
				winner = 0;
				if score1 > score0:
					winner = 1;
				time.sleep(2);
				break;
		print self.players[winner].name + ' won the hand.\n'
		self.players[winner].stack += self.pot;
		self.players[winner].num_of_hands_won += 1;
		return winner;
Exemplo n.º 5
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.º 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 declareAction(self, hole, board, round, my_Raise_Bet, my_Call_Bet,Table_Bet,number_players,raise_count,bet_count,my_Chips,total_bet):
        # Aggresive -tight
        self.number_players=number_players

        my_Raise_Bet=(my_Chips*self.bet_tolerance)/(1-self.bet_tolerance)
        print "Round:{}".format(round)
        score = HandEvaluator.evaluate_hand(hole, board)
        hand_score = HandEvaluator.evaluate_hand(hole, [])
        print "score:{}".format(score)
        #score = math.pow(score, self.number_players)
        print "score:{}".format(score)

        if round == 'preflop':
            if score >= self.preflop_tight_loose_threshold:
                action = 'call'
                amount = my_Call_Bet
            else:
                action = 'fold'
                amount = 0
        else:
            result = self.clf.predict([[hand_score, score]])
            action = result[0]
            if score >= self.aggresive_passive_threshold:
                TableOdds = (my_Raise_Bet+total_bet) / float(my_Raise_Bet + Table_Bet)
                if score >= TableOdds and action == "raise":
                    # action = 'raise'
                    amount = my_Raise_Bet
                else:
                    TableOdds = (my_Call_Bet+total_bet) / float(my_Call_Bet + Table_Bet)
                    if score >= TableOdds and action == 'call':
                        # action = 'call'
                        amount = my_Call_Bet
                    elif action == 'fold':
                        # action = 'fold'
                        amount = 0
                    else:
                        amount = 0
            else:
                TableOdds = (my_Call_Bet+total_bet) / float(my_Call_Bet + Table_Bet)
                if score >= TableOdds and action == 'call':
                    # action = 'call'
                    amount = my_Call_Bet
                elif action == 'fold':
                    # action = 'fold'
                    amount = 0
                else:
                    amount = 0
        #if (action=='call' or action=='raise') and len(board)>=4:
            #simulation_number=1000
            #win_rate=self.get_win_prob(hole, board, simulation_number,number_players)
            #if win_rate<0.4:
                #action = 'fold'
                #amount = 0
                #print 'change'
        return action, amount
Exemplo n.º 8
0
def eval_cards(hand, table):
    """
    Returns the cards' strength value evaluated with the pokereval
    cards evaluation algorithm.

    No cards on table (only hand cards are known):
    >>> table = []
    >>> hand = [('S', '2'), ('H', 'A')]
    >>> eval_cards(hand, table)
    0.6817496229260935

    Three cards on table:
    >>> table = [('D', '3'), ('D', 'J'), ('C', 'Q')]
    >>> hand = [('S', '2'), ('H', 'A')]
    >>> eval_cards(hand, table)
    0.5074005550416282

    Four cards on table:
    >>> table = [('D', '3'), ('D', 'J'), ('C', 'Q'), ('C', 'K')]
    >>> hand = [('S', '2'), ('H', 'A')]
    >>> eval_cards(hand, table)
    0.39468599033816426

    Five cards on table:
    >>> table = [('D', '3'), ('D', 'J'), ('C', 'Q'), ('C', 'K'), ('S', '10')]
    >>> hand = [('S', '2'), ('H', 'A')]
    >>> eval_cards(hand, table)
    0.9348484848484848
    """
    hand = [Card(*card) for card in card_values(hand)]
    table = [Card(*card) for card in card_values(table)]
    chance = HandEvaluator.evaluate_hand(hand, table)
    return chance
Exemplo n.º 9
0
def get_a3c_input(hand, board, round_name, total_pot, my_stack, big_blind,
                  my_cycle_bet):
    cards_index = cards_to_index52(hand)
    cards_index = cards_to_index52(board, cards_index)

    #  covert total_pot and my_stack to big_blind
    total_pot_bb = total_pot / big_blind
    my_stack_bb = my_stack / big_blind

    percentage = HandEvaluator.evaluate_hand(hand, board)

    # E = (state.community_state.totalpot + 2 * state.community_state.to_call)
    #  * percentage # calculate EV
    E = percentage * (total_pot - my_cycle_bet) + \
        (1 - percentage) * -1 * (my_cycle_bet)
    ev = 0
    if E > 0:
        ev = 1

    #  convert round_name to num
    if round_name not in ['Deal', 'Flop', 'Turn', 'River']:
        raise Exception("Error: round_name is not correct")
    if round_name == 'Deal':
        round = 0
    elif round_name == 'Flop':
        round = 1
    elif round_name == 'Turn':
        round = 2
    else:
        round = 3
    round = round / 3  #  normalization

    # return cards_index + [my_rank, round, total_pot_bb, my_stack_bb]
    return cards_index + [round + ev]
Exemplo n.º 10
0
	def finish_hand(self):
		winner = ""

		if self.active_players > 1:
			self.compute_players()
			score = 0
			board = [Card(self.flop1.power, self.flop1.suit), Card(self.flop2.power, self.flop2.suit) , Card(self.flop3.power, self.flop3.suit), Card(self.turn.power, self.turn.suit), Card(self.river.power, self.river.suit)]
			for player in self.players:

				hole = [Card(player.card1[0].power, player.card1[0].suit), Card(player.card2[0].power, player.card2[0].suit)]
				new_score = HandEvaluator.evaluate_hand(hole, board)
				if new_score > score:
					score = new_score
					winner = player
		else:
			winner = self.players[0]

		winner.stack = winner.stack + self.pot
		self.pot = 0
		self.phase = 0
		self.current_player = 0
		self.active_players = len(self.all_players)
		self.checked_players = 0
		self.to_pay = 0
		self.players = []
		self.deck = build_deck()
		for player in self.all_players:
			player.card1 = [compute_draw_card(self.deck)]
			player.card2 = [compute_draw_card(self.deck)]
		self.flop1 = compute_draw_card(self.deck)
		self.flop2 = compute_draw_card(self.deck)
		self.flop3 = compute_draw_card(self.deck)
		self.players = self.all_players[:]
Exemplo n.º 11
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.º 12
0
 def get_hand_strength(self):
     # poker eval uses a different representation, we must convert it first
     hole = [_get_pokereval_representation(card) for card in self.hole]
     community = [
         _get_pokereval_representation(card) for card in self.community
     ]
     score = HandEvaluator.evaluate_hand(hole, community)
     LOG.info("Score %f" % score)
     return score
Exemplo n.º 13
0
 def evaluate(self):
     # if self.evaluate_flag:
     #     return self.score
     hole = [Card(self.points[p], self.colors[c]) for c, p in self.cards]
     board = [Card(self.points[p], self.colors[c]) for c, p in self.flops]
     score = HandEvaluator.evaluate_hand(hole, board)
     self.evaluate_flag = True
     # print(score)
     return score
Exemplo n.º 14
0
Arquivo: state.py Projeto: WRMM/poker
 def get_hand_strength(self):
     # poker eval uses a different representation, we must convert it first
     hole = [_get_pokereval_representation(card)
             for card in self.hole]
     community = [_get_pokereval_representation(card)
                  for card in self.community]
     score = HandEvaluator.evaluate_hand(hole, community)
     LOG.info("Score %f" % score)
     return score
Exemplo n.º 15
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.º 16
0
    def act(self,observation, actionList):
        if observation['state'] != "pre-flop":
            possible_cards = [card for card in cardsList if (card not in observation['board'] and
                                                            card not in observation['player'].cards)];
            possible_cards = [cardstoC[card] for card in possible_cards];
            scores = []
            board = [cardstoC[c] for c in observation['board']]
            for (card1, card2) in itertools.combinations(possible_cards,2):
                hole = [card1,card2]
                scores.append(HandEvaluator.evaluate_hand(hole, board))
            agent_cards = [cardstoC[c] for c in observation['player'].cards]
            agent_score = HandEvaluator.evaluate_hand(agent_cards,board)
            confidence = 1 - float(sum(np.greater(scores,agent_score)))/len(scores)
            if (confidence > .7):
                if ("bet" in actionList):
                    action =  "bet"
                else:
                    action = "call"
            elif "check" in actionList:
                action =  "check"
            else:
                if confidence > .5:
                    action =  "call"
                else:
                    action = "fold"
        else:
            if "check" in actionList:
                action =  "check"
            else:
                action =  "call"
        if np.random.rand() < .2:
	    print "--------------------"
            print "I'm bluffing: bet"
	    print "--------------------"
            return "bet"
	print "--------------------"
        print action
	print "--------------------"
        return action
Exemplo n.º 17
0
 def pontuacao(self, j, mesa):
     score = 0
     for i in range(len(j)):
         if ((j[i].noJogo == True) and (j[i].naRodada == True)):
             j[i].score = HandEvaluator.evaluate_hand(j[i].mao, mesa.cartas)
     for i in range(len(j)):
         if ((j[i].noJogo == True) and (j[i].naRodada == True)):
             if j[i].score > score:
                 score = j[i].score
     for i in range(len(j)):
         if ((j[i].noJogo == True) and (j[i].naRodada == True)):
             if score == j[i].score:
                 j[i].venceuRodada()
                 print("Jogador %d venceu rodada" % (j[i].n))
Exemplo n.º 18
0
def calculate_hand(request):

	table = cache.get('table')
	player = table.players[0]
	board = []
	for card in table.cards:
		board.append(Card(card.power, card.suit))
	
	hole = [Card(player.card1[0].power, player.card1[0].suit),
			Card(player.card2[0].power, player.card2[0].suit)]

	score = HandEvaluator.evaluate_hand(hole, board)

	return HttpResponse(str(score))
Exemplo n.º 19
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.º 20
0
    def declareAction(self, state, minBet, seat_num):
        hole = state.player_state[seat_num].cards
        board = state.table_state.board
        my_rank = HandEvaluator.evaluate_hand(hole, board)

        big_blind = state.table_state.big_blind_amount
        chips = state.player_state[seat_num].chips
        my_Raise_Bet = min(big_blind, int(chips / 4))

        if my_rank > 0.85:
            action = 'raise'
            amount = my_Raise_Bet
        elif my_rank > 0.6:
            action = 'call'
            amount = minBet
        else:
            action = 'fold'
            amount = 0
        return action, amount
Exemplo n.º 21
0
from pokereval.card import Card
from pokereval.hand_evaluator import HandEvaluator

hole = [Card(2, 1), Card(2, 2)]
board = []
score = HandEvaluator.evaluate_hand(hole, board)
Exemplo n.º 22
0
 def hand_value(self, table):
     hand = [Card(*card) for card in utils.card_values(self.hand)]
     table = [Card(*card) for card in utils.card_values(table)]
     score = HandEvaluator.evaluate_hand(hand, table)
     return score
Exemplo n.º 23
0
    def declareAction(self, state, minBet, seat_num):
        hole = state.player_state[seat_num].cards
        board = state.table_state.board
        chips = state.player_state[seat_num].chips
        round = state.table_state.round
        # Aggresive -tight
        self.number_players = len(
            [player for player in state.player_state if player.isSurvive])

        my_Raise_Bet = (chips * self.bet_tolerance) / (1 - self.bet_tolerance)
        my_Call_Bet = minBet
        Table_Bet = state.table_state.total_bet
        total_bet = state.player_state[
            seat_num].roundBet  # how many chips you bet in this round

        print "Round:{}".format(round)
        score = HandEvaluator.evaluate_hand(hole, board)
        print "score:{}".format(score)
        # score = math.pow(score, self.number_players)
        print "score:{}".format(score)

        if round == 'Deal':
            if score >= self.preflop_tight_loose_threshold:
                action = 'call'
                amount = my_Call_Bet
            else:
                action = 'fold'
                amount = 0
        else:
            if score >= self.aggresive_passive_threshold:
                TableOdds = (my_Raise_Bet + total_bet) / (my_Raise_Bet +
                                                          Table_Bet)
                if score >= TableOdds:
                    action = 'raise'
                    amount = my_Raise_Bet
                else:
                    TableOdds = (my_Call_Bet + total_bet) / (my_Call_Bet +
                                                             Table_Bet)
                    if score >= TableOdds:
                        action = 'call'
                        amount = my_Call_Bet
                    else:
                        action = 'fold'
                        amount = 0
            else:
                TableOdds = (my_Call_Bet + total_bet) / (my_Call_Bet +
                                                         Table_Bet)
                if score >= TableOdds:
                    action = 'call'
                    amount = my_Call_Bet
                else:
                    action = 'fold'
                    amount = 0
        # if (action=='call' or action=='raise') and len(board)>=4:
        # simulation_number=1000
        # win_rate=self.get_win_prob(hole, board, simulation_number,number_players)
        # if win_rate<0.4:
        # action = 'fold'
        # amount = 0
        # print 'change'
        return action, amount
Exemplo n.º 24
0
    def run(self, input_socket):
        # Get a file-object for reading packets from the socket.
        # Using this ensures that you get exactly one packet per read.
        f_in = input_socket.makefile()
        conv = create_pbots_hand_to_twohandeval_dict()
        while True:
            # Block until the engine sends us a packet.
            data = f_in.readline().strip()
            # If data is None, connection has closed.
            if not data:
                print "Gameover, engine disconnected."
                break

            # Here is where you should implement code to parse the packets from
            # the engine and act on it. We are just printing it instead.
            print data

            # When appropriate, reply to the engine with a legal action.
            # The engine will ignore all spurious responses.
            # The engine will also check/fold for you if you return an
            # illegal action.
            # When sending responses, terminate each response with a newline
            # character (\n) or your bot will hang!
            data = data.split() # Split data into list
            command = data[0]

            if command == "NEWGAME":
                hand = [""]*4 # Initialize hand to be empty
                risk = 1
                max_preflop_equity, max_flop_equity, max_turn_equity, max_river_equity = 0, 0, 0, 0 # Flush all equities

            elif command == "NEWHAND":
                if PLOT_FLAG == True:
                    MADBot_delta.append(str(data[-3]))
                    otherbot_delta.append(str(data[-2]))
                hand = data[3:7]
                two_pairs = return_pairs(hand)
                convs_two_pairs = [(convert_pbots_hand_to_twohandeval(hole[0], conv), convert_pbots_hand_to_twohandeval(hole[1], conv)) for hole in two_pairs]
                max_preflop_equity = max([HandEvaluator.evaluate_hand([Card(h[0][0], h[0][1]), Card(h[1][0], h[1][1])], []) for h in convs_two_pairs])

            elif command == "GETACTION":
                # Currently CHECK on every move. You'll want to change this.
                print 'risk', risk
                info = parse_GETACTION(data)
                if info['numBoardCards'] == 0:
                    l, u = get_lower_and_upper_bounds(info["legalActions"][-1])[1]
                    if max_preflop_equity >= 0.99:
                        s.send("RAISE:" + str(u) + "\n")
                    elif max_preflop_equity >= 0.97:
                        avg = int((u+l)/2)
                        s.send("RAISE:" + str(avg) + "\n")
                    elif max_preflop_equity >= 0.95:
                        s.send("RAISE:" + str(l) + "\n")
                    else:
                        s.send("CALL\n")

                elif info['numBoardCards'] == 3:
                    conv_all_cards = []
                    conv_board_cards = convert_list_to_card_list([convert_pbots_hand_to_twohandeval(card, conv) for card in info['boardCards']]) # in Card form
                    max_flop_equity = max([HandEvaluator.evaluate_hand([Card(h[0][0], h[0][1]), Card(h[1][0], h[1][1])], conv_board_cards) for h in convs_two_pairs])
                    cmd, (l, u) = get_lower_and_upper_bounds(info["legalActions"][-1])
                    if cmd != "CALL":
                        rand = random.random()
                        if risk < 0.1:
                            if (rand >= 0.05):
                                s.send("FOLD\n")
                        else:
                            if max_flop_equity >= 0.95:
                                if (rand < 0.05):
                                    s.send("CHECK\n")
                                elif (risk < 0.2):
                                    s.send(cmd + ":" + str(u) + "\n")
                                else:
                                    s.send(cmd + ":" + str(u) + "\n")
                            elif max_flop_equity >= 0.90:
                                if (risk < 0.2):
                                    if (rand < 0.1):
                                        s.send("CALL\n")
                                elif (rand < 0.10):
                                    s.send("CHECK\n")
                                else:
                                    avg = int((2*u+l)/3)
                                    s.send(cmd + ":" + str(avg) + "\n")
                            elif max_flop_equity >= 0.75:
                                if (risk < 0.2):
                                    if (rand < 0.1):
                                        s.send("CALL\n")
                                elif (rand < 0.10):
                                    s.send("CHECK\n")
                                else:
                                    avg = int((u+l)/2)
                                    s.send(cmd + ":" + str(avg) + "\n")
                            elif max_flop_equity >= 0.60:
                                if (rand < 0.15) or risk < 0.2:
                                    s.send("FOLD\n")
                                else:
                                    s.send("CALL\n")
                            else:
                                if (rand < 0.05):
                                    s.send("CALL\n")
                                else:
                                    s.send("FOLD\n")
                    else:
                        s.send("CALL\n")


                elif info['numBoardCards'] == 4:
                    conv_all_cards = []
                    conv_board_cards = convert_list_to_card_list([convert_pbots_hand_to_twohandeval(card, conv) for card in info['boardCards']]) # in Card form
                    max_flop_equity = max([HandEvaluator.evaluate_hand([Card(h[0][0], h[0][1]), Card(h[1][0], h[1][1])], conv_board_cards) for h in convs_two_pairs])
                    cmd, (l, u) = get_lower_and_upper_bounds(info["legalActions"][-1])
                    if cmd != "CALL":
                        rand = random.random()
                        if risk < 0.1:
                            if (rand >= 0.1):
                                s.send("FOLD\n")
                        else:
                            if max_flop_equity >= 0.95:
                                if (rand < 0.05):
                                    s.send("CHECK\n")
                                elif (risk < 0.01):
                                    s.send(cmd + ":" + str(u) + "\n")
                                else:
                                    s.send(cmd + ":" + str(u) + "\n")
                            elif max_flop_equity >= 0.80:
                                if (risk < 0.2):
                                    if (rand < 0.1):
                                        s.send("FOLD\n")
                                    else:
                                        s.send("CHECK\n")
                                elif (rand < 0.10):
                                    s.send("CHECK\n")
                                else:
                                    avg = int((u+l)/2)
                                    s.send(cmd + ":" + str(avg) + "\n")
                            elif max_flop_equity >= 0.50:
                                if (rand < 0.15) or risk < 0.2:
                                    s.send("CHECK\n")
                                else:
                                    s.send("FOLD\n")
                            else:
                                s.send("FOLD\n")
                    else:
                        s.send("CALL\n")

                elif info['numBoardCards'] == 5:
                    conv_all_cards = []
                    conv_board_cards = convert_list_to_card_list([convert_pbots_hand_to_twohandeval(card, conv) for card in info['boardCards']]) # in Card form
                    max_flop_equity = max([HandEvaluator.evaluate_hand([Card(h[0][0], h[0][1]), Card(h[1][0], h[1][1])], conv_board_cards) for h in convs_two_pairs])
                    cmd, (l, u) = get_lower_and_upper_bounds(info["legalActions"][-1])
                    if cmd != "CALL":
                        rand = random.random()
                        if risk < 0.1:
                            if (rand >= 0.05):
                                s.send("FOLD\n")
                        else:
                            if max_flop_equity >= 0.95:
                                if (rand < 0.05):
                                    s.send("CHECK\n")
                                elif (risk < 0.01):
                                    s.send("CALL\n")
                                else:
                                    s.send(cmd + ":" + str(u) + "\n")
                            elif max_flop_equity >= 0.85:
                                if (risk < 0.2):
                                    if (rand < 0.1):
                                        s.send("CALL\n")
                                elif (rand < 0.10):
                                    s.send("CHECK\n")
                                else:
                                    avg = int((u+l)/2)
                                    s.send(cmd + ":" + str(avg) + "\n")
                            elif max_flop_equity >= 0.50:
                                if (rand < 0.15) or risk < 0.2:
                                    s.send("CHECK\n")
                                else:
                                    s.send("\n")
                            else:
                                if (rand < 0.15):
                                    s.send("CALL\n")
                                else:
                                    s.send("FOLD\n")
                    else:
                            s.send("CALL\n")
                else:
                    s.send("CALL\n")

            elif command == "REQUESTKEYVALUES":
                # At the end, the engine will allow your bot save key/value pairs.
                # Send FINISH to indicate you're done.
                s.send("FINISH\n")

            elif command == "HANDOVER":
                hand = [""]*4 # Empty the hand
                bankroll = int(data[1])
                risk = 1
                if bankroll < 100:
                    diff = 100 - bankroll
                    if (float(math.log(diff)/math.log(10))) == 0:
                        risk = 1
                    elif bankroll > -50:
                        risk = 1.0 / (float(math.log(diff)/math.log(10)))**(2)
                    else:
                        risk = 1.0 / (float(math.log(diff)/math.log(10)))**2

                max_preflop_equity, max_flop_equity, max_turn_equity, max_river_equity = 0, 0, 0, 0 # Flush all equities

        # Clean up the socket.
        print MADBot_delta
        print otherbot_delta
        print "\n".join(MADBot_delta)
        print "=================================================="
        print "\n".join(otherbot_delta)
        s.close()
Exemplo n.º 25
0
    def declareAction(self, hole, board, round, my_Raise_Bet, my_Call_Bet, Table_Bet, number_players, raise_count,
                      bet_count, my_Chips, total_bet):

        score = HandEvaluator.evaluate_hand(hole, board)
        print "score:{}".format(score)
        allin_static_rate = 0.95
        preflop_raise_static_rate = 0.98
        preflop_call_static_rate = 0.95
        flop_raise_static_rate = 0.9
        flop_call_static_rate = 0.85
        in_montecarlo_rate = 0.69
        in_montecarlo_card = 4
        if my_Chips + total_bet < 3000:
            aggressive_by_chip = 3 - (my_Chips + total_bet) / 1000
        else:
            aggressive_by_chip = 1

        if my_Call_Bet == 0:
            action = 'call'
            amount = my_Call_Bet
        else:
            if my_Call_Bet > my_Chips:
                my_Call_Bet = my_Chips
            call_odd = (((my_Call_Bet + total_bet) / float(my_Chips + total_bet)) ** 0.5) ** aggressive_by_chip
            raise_odd = (call_odd ** 0.5) ** aggressive_by_chip

            if round == 'preflop' or round == 'Deal':
                if score >= raise_odd and score >= self.preflop_threshold or score >= preflop_raise_static_rate:
                    action = 'raise'
                    amount = my_Raise_Bet
                elif score >= call_odd and score >= self.preflop_threshold or score >= preflop_call_static_rate:
                    action = 'call'
                    amount = my_Call_Bet
                else:
                    action = 'fold'
                    amount = 0
            else:
                call_odd *= allin_static_rate
                raise_odd *= allin_static_rate
                if score >= allin_static_rate and len(board) >= in_montecarlo_card:
                    action = 'allin'
                    amount = 0
                elif score >= allin_static_rate:
                    action = 'bet'
                    bet = ((my_Chips + total_bet) / 2) - total_bet
                    if bet <= total_bet:
                        bet = my_Call_Bet
                    amount = bet
                elif score >= raise_odd and score >= self.flop_threshold or score >= flop_raise_static_rate:
                    action = 'raise'
                    amount = my_Raise_Bet
                elif score >= call_odd and score >= self.flop_threshold or score >= flop_call_static_rate:
                    action = 'call'
                    amount = my_Call_Bet
                else:
                    action = 'fold'
                    amount = 0
            print "call=%s, raise=%s, score=%s, action=%s" % (call_odd, raise_odd, score, action)
        if (action == 'call' or action == 'raise') and len(board) >= in_montecarlo_card and score <= in_montecarlo_rate:
            simulation_number = 50
            win_rate = self.get_win_prob(hole, board, simulation_number, number_players)
            if win_rate < 0.20:
                action = 'fold'
                amount = 0
            elif win_rate < 0.25:
                action = 'call'
                amount = my_Call_Bet
            elif win_rate < 0.30:
                action = 'raise'
                amount = my_Raise_Bet
            else:
                action = 'allin'
                amount = 0
            print 'change'
        return action, amount
Exemplo n.º 26
0
def main():
    game_file = 'HandLogs4/MADbot_vs_StraightOuttaCam'
    player_1 = game_file.split('_vs_')[0][10:]
    player_2 = game_file.split('_vs_')[1]

    f = open(game_file, 'r')
    lines = [line for line in f][1:]

    full_game_string = ''
    for line in lines:
        full_game_string += line

    game_buckets = full_game_string.split('\n\n')[:-1]
    categories = defaultdict(list)
    winner = defaultdict(list)

    # Buckets all of the games into one of 6 categories:
    # (1)full_game (players show their cards)
    # Player 1 folds ((2)fold_after_river, (3)fold_after_turn, (4)fold_after_flop, (5)fold_before_flop)
    # (2)opponent_folds (player 2 folds at some point in the game)
    for game in game_buckets:
        if player_1 + " shows" in game:
            categories['full_game'] += [game]
        elif player_1 + " folds" in game:
            if "*** RIVER ***" in game:
                categories['fold_after_river'] += [game]
            elif "*** TURN ***" in game:
                categories['fold_after_turn'] += [game]
            elif "*** FLOP ***" in game:
                categories['fold_after_flop'] += [game]
            else:
                categories['fold_before_flop'] += [game]
        elif player_2 + " folds" in game:
            categories['opponent_folds'] += [game]
        if player_1 + " wins the pot" in game:
            winner[player_1].append(game)
        else:
            winner[player_2].append(game)

    preflops = []
    p1_equities = []
    for game in winner[player_1]:
        if game not in categories['full_game']:
            continue
        player_1_hand, player_2_hand = get_players_hands(
            game, player_1, player_2)

        # Getting pre-flop statistics
        # max_preflop = max([HandEvaluator.evaluate_hand([Card(h[0][0], h[0][1]), Card(h[1][0], h[1][1])], []) for h in player_1_hand])
        # preflops.append(max_preflop)

        # Getting post-flop statistics

        game = game[game.index("*** RIVER ***"):]
        table_cards = game[game.index("[") + 1:game.index("[") + 12].split()
        table_cards_last = game[game.index("]") + 3:game.index("]") +
                                5].split()
        # table_cards = game[game.index("[")+1:game.index("[")+9].split()
        # table_cards_last = game[game.index("]")+3:game.index("]")+5].split()
        table_cards = table_cards + table_cards_last

        conv = create_pbots_hand_to_twohandeval_dict()
        converted_board_cards = convert_list_to_card_list([
            convert_pbots_hand_to_twohandeval(card) for card in table_cards
        ])  # in pbotseval form
        max_flop_equity = max([
            HandEvaluator.evaluate_hand(
                [Card(h[0][0], h[0][1]),
                 Card(h[1][0], h[1][1])], converted_board_cards)
            for h in player_1_hand
        ])
        # if max_flop_equity > 0.99:
        #     print table_cards
        #     print player_1_hand
        #     print [HandEvaluator.evaluate_hand([Card(h[0][0], h[0][1]), Card(h[1][0], h[1][1])], converted_board_cards) for h in player_1_hand]
        #     print player_2_hand
        #     print [HandEvaluator.evaluate_hand([Card(h[0][0], h[0][1]), Card(h[1][0], h[1][1])], converted_board_cards) for h in player_2_hand]
        p1_equities.append(max_flop_equity)

    print len(p1_equities)
    n, bins, patches = plt.hist(p1_equities,
                                100,
                                normed=1,
                                facecolor='green',
                                alpha=0.75)
    plt.title('We won post river')
    plt.show()
Exemplo n.º 27
0
        '8': 8,
        '9': 9,
        'T': 10,
        'J': 11,
        'Q': 12,
        'K': 13,
        'A': 14,
        'O': -1,
        'P': 0,
        'S': 1
    }
    n_card1 = y[c_1]
    n_card2 = y[c_2]
    n_suited = y[suit]
    ev_c = np.where(n_suited == 1,
                    ev.evaluate_hand([c(n_card1, 1),
                                      c(n_card2, 1)]),
                    ev.evaluate_hand([c(n_card1, 1),
                                      c(n_card2, 2)]))

    df = df[df['ev'] == ev_c]
    df = df[df['position'] == position]
    df = df[df['action'] == action]
    df_o = df.output_preflop.to_numpy()
    df_c = df.class_preflop.to_numpy()
    code = '''{}  >  {}  >  {} > {} > {}'''.format(
        (c_1 + c_2 + suit), position, action, df_c[-1], df_o[-1])
    st.code(code, language='python')
    if st.button("{}".format(df_o[-1])):
        session.run_id += 1
    st.write("_" * 20)
Exemplo n.º 28
0
QC KC 3S JC KD 2C 8D AH QS TS
AS KD 3D JD 8H 7C 8C 5C QD 6C"""


short_games = """5H 5C 6S 7S KD 2C 3S 8S 8D TD
5D 8C 9S JS AC 2C 5C 7D 8S QH
2D 9C AS AH AC 3D 6D 7D TD QD
4D 6S 9H QH QC 3D 6D 7H QD QS
2H 2D 4C 4D 4S 3C 3D 3S 9S 9D"""

from pokereval.card import Card
from pokereval.hand_evaluator import HandEvaluator

def card_from_string(s):
	rank = list("xx23456789TJQKA").index(s[0])
	suit = list("xSHDC").index(s[1])
	return Card(rank, suit)

if __name__=="__main__":
	count = 0
	for game in games.splitlines():
		cards = list(map(card_from_string, game.split()))
		hand1 = cards[:5]
		hand2 = cards[5:]
		score1 = HandEvaluator.evaluate_hand(hand1)
		score2 = HandEvaluator.evaluate_hand(hand2)
		print("{0}:{1}\n{2}:{3}".format(hand1, score1, hand2, score2))
		if score1 < score2:
			count +=1
	print(count)
Exemplo n.º 29
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
Exemplo n.º 30
0
    def run(self, input_socket):
        # Get a file-object for reading packets from the socket.
        # Using this ensures that you get exactly one packet per read.
        f_in = input_socket.makefile()
        conv = create_pbots_hand_to_twohandeval_dict()
        while True:
            # Block until the engine sends us a packet.
            data = f_in.readline().strip()
            # If data is None, connection has closed.
            if not data:
                print "Gameover, engine disconnected."
                break

            # Here is where you should implement code to parse the packets from
            # the engine and act on it. We are just printing it instead.
            print data

            # When appropriate, reply to the engine with a legal action.
            # The engine will ignore all spurious responses.
            # The engine will also check/fold for you if you return an
            # illegal action.
            # When sending responses, terminate each response with a newline
            # character (\n) or your bot will hang!
            data = data.split() # Split data into list
            command = data[0]

            if command == "NEWGAME":
                hand = [""]*4 # Initialize hand to be empty
                risk = 1
                max_preflop_equity, max_flop_equity = 0, 0 # Flush all equities

            elif command == "NEWHAND":
                info = parse_NEWHAND(data)
                myBank = info['myBank']
                if PLOT_FLAG == True:
                    MADBot_delta.append(myBank)
                    otherbot_delta.append(info['otherBank'])

                hand = info['holeCards']
                hand_pairs = get_all_pairs(hand)
                # converts engine's format to pokereval's format
                converted_hand_pairs = [(convert_pbots_hand_to_twohandeval(hole[0], conv), convert_pbots_hand_to_twohandeval(hole[1], conv)) for hole in hand_pairs]
                max_preflop_equity = max([HandEvaluator.evaluate_hand([Card(h[0][0], h[0][1]), Card(h[1][0], h[1][1])], []) for h in converted_hand_pairs])

            elif command == "GETACTION":
                info = parse_GETACTION(data)
                rand = random.random()
                if info['numBoardCards'] == 0:
                    safe = myBank > -3000
                    l, u = get_lower_and_upper_bounds(info["legalActions"][-1])[1]
                    if safe:
                        if info['potSize'] > 50:
                            s.send("CHECK\n")
                        else:
                            if max_preflop_equity > 0.99:
                                if rand >= 0.4:
                                    s.send("RAISE:" + str(l) + "\n")
                            s.send("CALL\n")
                    else:
                        if max_preflop_equity >= 0.99 and info['potSize'] < 50:
                            s.send("CALL\n")
                        else:
                            s.send("CHECK\n")

                elif info['numBoardCards'] == 3:
                    conv_all_cards = []
                    # converts engine's format to pokereval's format
                    converted_board_cards = convert_list_to_card_list([convert_pbots_hand_to_twohandeval(card, conv) for card in info['boardCards']]) # in Card form
                    max_flop_equity = max([HandEvaluator.evaluate_hand([Card(h[0][0], h[0][1]), Card(h[1][0], h[1][1])], converted_board_cards) for h in converted_hand_pairs])
                    cmd, (l, u) = get_lower_and_upper_bounds(info["legalActions"][-1])
                    if cmd != "CALL":
                        if max_flop_equity >= 0.97:
                            if rand > 0.7:
                                s.send(cmd+":" + str(u) + "\n")
                            elif rand > 0.3:
                                s.send(cmd+":" + str(l) + "\n")
                            else:
                                s.send("CALL\n")
                        elif max_flop_equity >= 0.90:
                            if rand > 0.5:
                                s.send(cmd+":" + str(l) + "\n")
                            else:
                                s.send("CALL\n")
                        elif max_flop_equity >= 0.80:
                            s.send("CALL\n")
                        else:
                            s.send("CHECK\n")
                    else:
                        if max_flop_equity >= 0.90:
                            s.send("CALL\n")
                        else:
                            s.send("CHECK\n")

                elif info['numBoardCards'] == 4:
                    conv_all_cards = []
                    converted_board_cards = convert_list_to_card_list([convert_pbots_hand_to_twohandeval(card, conv) for card in info['boardCards']]) # in Card form
                    max_flop_equity = max([HandEvaluator.evaluate_hand([Card(h[0][0], h[0][1]), Card(h[1][0], h[1][1])], converted_board_cards) for h in converted_hand_pairs])
                    cmd, (l, u) = get_lower_and_upper_bounds(info["legalActions"][-1])
                    if cmd != "CALL":
                        if max_flop_equity >= 0.96:
                            if rand > 0.5:
                                s.send(cmd+":" + str(u) + "\n")
                            else:
                                s.send("CALL\n")
                        elif max_flop_equity >= 0.90:
                            s.send("CALL\n")
                        else:
                            s.send("CHECK\n")
                    else:
                        print "PRINTING THE COMMANDDDDDD"
                        print cmd
                        if max_flop_equity >= 0.90:
                            s.send("CALL\n")
                        else:
                            s.send("CHECK\n")

                elif info['numBoardCards'] == 5:
                    conv_all_cards = []
                    conv_board_cards = convert_list_to_card_list([convert_pbots_hand_to_twohandeval(card, conv) for card in info['boardCards']]) # in Card form
                    max_flop_equity = max([HandEvaluator.evaluate_hand([Card(h[0][0], h[0][1]), Card(h[1][0], h[1][1])], conv_board_cards) for h in converted_hand_pairs])
                    cmd, (l, u) = get_lower_and_upper_bounds(info["legalActions"][-1])
                    if cmd != "CALL":
                        if max_flop_equity >= 0.95:
                            s.send(cmd+":" + str(u) + "\n")
                        elif max_flop_equity >= 0.90:
                            s.send("CALL\n")
                        else:
                            s.send("CHECK\n")
                    else:
                        print "PRINTING THE COMMANDDDDDD"
                        print cmd
                        if max_flop_equity >= 0.90:
                            s.send("CALL\n")
                        else:
                            s.send("CHECK\n")
                else:
                    s.send("CALL\n")

            elif command == "REQUESTKEYVALUES":
                # At the end, the engine will allow your bot save key/value pairs.
                # Send FINISH to indicate you're done.
                s.send("FINISH\n")

            elif command == "HANDOVER":
                hand = [""]*4 # Empty the hand
                bankroll = int(data[1])
                # risk = 1
                # if bankroll < 100:
                #     diff = 100 - bankroll
                #     if (float(math.log(diff)/math.log(10))) == 0:
                #         risk = 1
                #     elif bankroll > -50:
                #         risk = 1.0 / (float(math.log(diff)/math.log(10)))**(2)
                #     else:
                #         risk = 1.0 / (float(math.log(diff)/math.log(10)))**2

                # max_preflop_equity, max_flop_equity, max_turn_equity, max_river_equity = 0, 0, 0, 0 # Flush all equities
                max_preflop_equity, max_flop_equity = 0, 0

        # Clean up the socket.
        print MADBot_delta
        print otherbot_delta
        # print "\n".join(MADBot_delta)
        # print "=================================================="
        # print "\n".join(otherbot_delta)
        s.close()
Exemplo n.º 31
0
def main():
    game_file = 'HandLogs4/MADbot_vs_StraightOuttaCam'
    player_1 = game_file.split('_vs_')[0][10:]
    player_2 = game_file.split('_vs_')[1]

    f = open(game_file, 'r')
    lines = [line for line in f][1:]

    full_game_string = ''
    for line in lines:
        full_game_string += line

    game_buckets = full_game_string.split('\n\n')[:-1]
    categories = defaultdict(list)
    winner = defaultdict(list)

    # Buckets all of the games into one of 6 categories:
    # (1)full_game (players show their cards)
    # Player 1 folds ((2)fold_after_river, (3)fold_after_turn, (4)fold_after_flop, (5)fold_before_flop)
    # (2)opponent_folds (player 2 folds at some point in the game)
    for game in game_buckets:
        if player_1 + " shows" in game:
            categories['full_game'] += [game]
        elif player_1 + " folds" in game:
            if "*** RIVER ***" in game:
                categories['fold_after_river'] += [game]
            elif "*** TURN ***" in game:
                categories['fold_after_turn'] += [game]
            elif "*** FLOP ***" in game:
                categories['fold_after_flop'] += [game]
            else:
                categories['fold_before_flop'] += [game]
        elif player_2 + " folds" in game:
            categories['opponent_folds'] += [game]
        if player_1 + " wins the pot" in game:
            winner[player_1].append(game)
        else:
            winner[player_2].append(game)


    preflops = []
    p1_equities = []
    for game in winner[player_1]:
        if game not in categories['full_game']:
            continue
        player_1_hand, player_2_hand = get_players_hands(game, player_1, player_2)
        
        # Getting pre-flop statistics
        # max_preflop = max([HandEvaluator.evaluate_hand([Card(h[0][0], h[0][1]), Card(h[1][0], h[1][1])], []) for h in player_1_hand])
        # preflops.append(max_preflop)

        # Getting post-flop statistics

        game = game[game.index("*** RIVER ***"):]
        table_cards = game[game.index("[")+1:game.index("[")+12].split()
        table_cards_last = game[game.index("]")+3:game.index("]")+5].split()
        # table_cards = game[game.index("[")+1:game.index("[")+9].split()
        # table_cards_last = game[game.index("]")+3:game.index("]")+5].split()
        table_cards = table_cards + table_cards_last


        conv = create_pbots_hand_to_twohandeval_dict()
        converted_board_cards = convert_list_to_card_list([convert_pbots_hand_to_twohandeval(card) for card in table_cards]) # in pbotseval form
        max_flop_equity = max([HandEvaluator.evaluate_hand([Card(h[0][0], h[0][1]), Card(h[1][0], h[1][1])], converted_board_cards) for h in player_1_hand])
        # if max_flop_equity > 0.99:
        #     print table_cards
        #     print player_1_hand
        #     print [HandEvaluator.evaluate_hand([Card(h[0][0], h[0][1]), Card(h[1][0], h[1][1])], converted_board_cards) for h in player_1_hand]
        #     print player_2_hand
        #     print [HandEvaluator.evaluate_hand([Card(h[0][0], h[0][1]), Card(h[1][0], h[1][1])], converted_board_cards) for h in player_2_hand]
        p1_equities.append(max_flop_equity)


    print len(p1_equities)
    n, bins, patches = plt.hist(p1_equities, 100, normed=1, facecolor='green', alpha=0.75)
    plt.title('We won post river')
    plt.show()
Exemplo n.º 32
0
    def declareAction(self, state, minBet, seat_num):
        holes = state.player_state[seat_num].cards
        boards = state.table_state.board
        my_chips = state.player_state[seat_num].chips
        this_round = state.table_state.round
        # Aggresive -tight
        number_players = len([player for player in state.player_state if player.isSurvive])

        my_raise_bet = (my_chips * self.bet_tolerance) / (1 - self.bet_tolerance)
        my_call_bet = minBet
        table_bet = state.table_state.total_bet
        total_bet = state.player_state[seat_num].roundBet  # how many chips you bet in this round

        action = 'fold'
        amount = 0
        my_rank = HandEvaluator.evaluate_hand(holes, boards)
        print "this_round:{}".format(this_round)
        print "evaluate_hand:{}".format(my_rank)
        print "pre_player_action:{}".format(state.table_state.last_action)

        # if this_round == 'preflop':
        if this_round == 'Deal':
            table_odds = (1.0 * my_call_bet + total_bet) / (my_call_bet + table_bet)
            print "call table_odds:{}".format(table_odds)
            if my_rank > table_odds:
                if my_rank > 0.5:
                    action = 'call'
                    amount = my_call_bet
                # elif my_rank > 0.5 and my_call_bet <= my_chips * 0.7:
                #    action = 'call'
                #   amount = my_call_bet
                #    print "prevent allin"
                elif my_rank > 0.3 and my_call_bet <= my_chips / 50.0:
                    action = 'call'
                    amount = my_call_bet
                    print "aggressive call"
            else:
                action = 'fold'
                amount = 0
        elif this_round == 'River':
            # win_rate = self.get_win_prob(holes, boards, 80, number_players)
            # print "win_rate:{}".format(win_rate)
            # if win_rate > 0.9 or my_rank > 0.9:
            if my_rank > 0.96:
                action = 'allin'
                amount = 0
            elif my_rank > 0.9:
                action = 'raise'
                amount = my_raise_bet
            # elif win_rate > 0.5 or my_rank > 0.75:
            elif my_rank > 0.75:
                action = 'call'
                amount = my_call_bet
            elif my_rank > 0.6:
                table_odds = (1.0 * my_call_bet + total_bet) / (my_call_bet + table_bet)
                print "call table_odds:{}".format(table_odds)
                if my_rank > table_odds:
                    action = 'call'
                    amount = my_call_bet
                else:
                    action = 'fold'
                    amount = 0
            else:
                action = 'fold'
                amount = 0
        else:
            if my_rank > 0.55:
                print "total_bet:{}".format(total_bet)
                print "table_bet:{}".format(table_bet)
                table_odds = (1.0 * my_raise_bet + total_bet) / (my_raise_bet + table_bet)
                print "raise table_odds:{}".format(table_odds)
                if my_rank > 0.85 and my_rank > table_odds:
                    action = 'raise'
                    amount = my_raise_bet
                else:
                    table_odds = (1.0 * my_call_bet + total_bet) / (my_call_bet + table_bet)
                    print "call table_odds:{}".format(table_odds)
                    if my_rank > table_odds:
                        action = 'call'
                        amount = my_call_bet
                    else:
                        action = 'fold'
                        amount = 0
            else:
                action = 'fold'
                amount = 0

        # handle check
        print("state.table_state.last_action: {}".format(state.table_state.last_action))
        if action == 'fold':
            if my_call_bet == 0:
                action = 'call'
                amount = my_call_bet
                print "call for bet 0"
            # elif self.pre_player_action == 'check' or self.pre_player_action == '':
            elif state.table_state.last_action == 'check' or state.table_state.last_action == '':
                action = 'check'
                amount = 0
                print "go check"
            # elif this_round == 'preflop' and self.data['game']['bigBlind']['playerName'] == self.data['self']['playerName']:
            #    action = 'check'
            #    amount = 0
            #    print "go check for preflop"

        return action, amount
from pokereval.card import Card
from pokereval.hand_evaluator import HandEvaluator

# Rank is 2-14 representing 2-A, while suit is 1-4 representing spades, hearts, diamonds, clubs
# aceOfSpades = Card(14, 1)
# twoOfDiamonds = Card(2, 3)

hole = [Card(10, 2), Card(11, 2)]
board = [Card(12, 2), Card(13, 1), Card(14, 2),Card(4, 1)]
score = HandEvaluator.evaluate_hand(hole, board)
print(score)
Exemplo n.º 34
0
    def run(self, input_socket, get_flop_probs, get_turn_probs, get_river_probs):
        # Get a file-object for reading packets from the socket.
        # Using this ensures that you get exactly one packet per read.
        f_in = input_socket.makefile()
        conv = create_pbots_hand_to_twohandeval_dict()
        while True:
            # Block until the engine sends us a packet.
            data = f_in.readline().strip()
            # If data is None, connection has closed.
            if not data:
                print "Gameover, engine disconnected."
                break

            # Here is where you should implement code to parse the packets from
            # the engine and act on it. We are just printing it instead.
            print data
            data = data.split() # Split data into list
            command = data[0]

            if command == "NEWGAME":
                hand = [""]*4 # Initialize hand to be empty
                risk = 1
                max_preflop_equity, max_flop_equity = 0, 0 # Flush all equities

            elif command == "NEWHAND":
                info = parse_NEWHAND(data)
                myBank = info['myBank']
                if PLOT_FLAG == True:
                    MADBot_delta.append(myBank)
                    otherbot_delta.append(info['otherBank'])

                hand = info['holeCards']
                hand_pairs = get_all_pairs(hand)
                # converts engine's format to pokereval's format
                converted_hand_pairs = [(convert_pbots_hand_to_twohandeval(hole[0], conv), convert_pbots_hand_to_twohandeval(hole[1], conv)) for hole in hand_pairs]
                max_preflop_equity = max([HandEvaluator.evaluate_hand([Card(h[0][0], h[0][1]), Card(h[1][0], h[1][1])], []) for h in converted_hand_pairs])

            elif command == "GETACTION":
                info = parse_GETACTION(data)
                rand = random.random()
                if info['numBoardCards'] == 0:
                    safe = myBank > -3000
                    l, u = get_lower_and_upper_bounds(info["legalActions"][-1])[1]
                    if safe:
                        if info['potSize'] > 50:
                            s.send("CHECK\n")
                        else:
                            if max_preflop_equity > 0.99:
                                if rand >= 0.4:
                                    s.send("RAISE:" + str(l) + "\n")
                            s.send("CALL\n")
                    else:
                        if max_preflop_equity >= 0.99 and info['potSize'] < 50:
                            s.send("CALL\n")
                        else:
                            s.send("CHECK\n")

                elif info['numBoardCards'] == 3:
                    table_cards = info['boardCards']
                    features = get_omaha_features(hand, table_cards, convolution_function, play = 'flop')
                    probs = get_turn_probs(features.reshape(1,27))[0]
                    prob_winning = probs[0]
                    print "###### FLOP #####"
                    print hand
                    print table_cards
                    print prob_winning
                    cmd, (l, u) = get_lower_and_upper_bounds(info["legalActions"][-1])
                    if cmd == 'BET':
                        if prob_winning >= 0.8:
                            if rand > 0.3:
                                s.send(cmd+":" + str(u) + "\n")
                            else:
                                s.send(cmd+":" + str(l) + "\n")
                        elif prob_winning >= 0.7:
                            if rand < 0.2:
                                s.send(cmd+":" + str(u) + "\n")
                            elif rand < 0.6:
                                s.send(cmd+":" + str(l) + "\n")
                            else:
                                s.send("CALL\n")
                        elif prob_winning >= 0.6:
                            s.send("CALL\n")
                        else:
                            s.send("CHECK\n")

                    elif cmd == 'RAISE':
                        if prob_winning >= 0.85:
                            if rand > 0.3:
                                s.send(cmd+":" + str(u) + "\n")
                            else:
                                s.send(cmd+":" + str(l) + "\n")
                        elif prob_winning >= 0.75:
                            if rand < 0.2:
                                s.send(cmd+":" + str(u) + "\n")
                            elif rand < 0.6:
                                s.send(cmd+":" + str(l) + "\n")
                            else:
                                s.send("CALL\n")
                        elif prob_winning >= 0.7:
                            s.send("CALL\n")
                        else:
                            s.send("CHECK\n")
                    else:
                        if prob_winning >= 0.7:
                            s.send("CALL\n")
                        else:
                            s.send("CHECK\n")

                elif info['numBoardCards'] == 4:
                    table_cards = info['boardCards']
                    features = get_omaha_features(hand, table_cards, convolution_function, play = 'turn')
                    probs = get_turn_probs(features.reshape(1,27))[0]
                    prob_winning = probs[0]
                    print "###### TURN #####"
                    print hand
                    print table_cards
                    print prob_winning

                    cmd, (l, u) = get_lower_and_upper_bounds(info["legalActions"][-1])
                    if cmd == 'BET':
                        if prob_winning >= 0.8:
                            if rand > 0.3:
                                s.send(cmd+":" + str(u) + "\n")
                            else:
                                s.send(cmd+":" + str(l) + "\n")
                        elif prob_winning >= 0.7:
                            if rand < 0.2:
                                s.send(cmd+":" + str(u) + "\n")
                            elif rand < 0.6:
                                s.send(cmd+":" + str(l) + "\n")
                            else:
                                s.send("CALL\n")
                        elif prob_winning >= 0.5:
                            s.send("CALL\n")
                        else:
                            s.send("CHECK\n")

                    elif cmd == 'RAISE':
                        if prob_winning >= 0.9:
                            if rand > 0.3:
                                s.send(cmd+":" + str(u) + "\n")
                            else:
                                s.send(cmd+":" + str(l) + "\n")
                        elif prob_winning >= 0.85:
                            if rand < 0.2:
                                s.send(cmd+":" + str(u) + "\n")
                            elif rand < 0.6:
                                s.send(cmd+":" + str(l) + "\n")
                            else:
                                s.send("CALL\n")
                        elif prob_winning >= 0.7:
                            s.send("CALL\n")
                        else:
                            s.send("CHECK\n")
                    else:
                        if prob_winning >= 0.7:
                            s.send("CALL\n")
                        else:
                            s.send("CHECK\n")

                elif info['numBoardCards'] == 5:
                    table_cards = info['boardCards']
                    features = get_omaha_features(hand, table_cards, convolution_function, play = 'river')
                    probs = get_turn_probs(features.reshape(1,27))[0]
                    prob_winning = probs[0]
                    print "###### RIVER #####"
                    print hand
                    print table_cards
                    print prob_winning

                    cmd, (l, u) = get_lower_and_upper_bounds(info["legalActions"][-1])
                    print cmd
                    if cmd == 'BET':
                        if prob_winning >= 0.75:
                            if rand > 0.3:
                                s.send(cmd+":" + str(u) + "\n")
                            else:
                                s.send(cmd+":" + str(l) + "\n")
                        elif prob_winning >= 0.7:
                            if rand < 0.2:
                                s.send(cmd+":" + str(u) + "\n")
                            elif rand < 0.6:
                                s.send(cmd+":" + str(l) + "\n")
                            else:
                                s.send("CALL\n")
                        elif prob_winning >= 0.6:
                            s.send("CALL\n")
                        else:
                            s.send("CHECK\n")

                    elif cmd == 'RAISE':
                        if prob_winning >= 0.95:
                            if rand > 0.3:
                                s.send(cmd+":" + str(u) + "\n")
                            else:
                                s.send(cmd+":" + str(l) + "\n")
                        elif prob_winning >= 0.8:
                            if rand < 0.2:
                                s.send(cmd+":" + str(u) + "\n")
                            elif rand < 0.6:
                                s.send(cmd+":" + str(l) + "\n")
                            else:
                                s.send("CALL\n")
                        elif prob_winning >= 0.7:
                            s.send("CALL\n")
                        else:
                            s.send("CHECK\n")
                    else:
                        if prob_winning >= 0.7:
                            s.send("CALL\n")
                        else:
                            s.send("CHECK\n")
                else:
                    s.send("CALL\n")

            elif command == "REQUESTKEYVALUES":
                # At the end, the engine will allow your bot save key/value pairs.
                # Send FINISH to indicate you're done.
                s.send("FINISH\n")

            elif command == "HANDOVER":
                hand = [""]*4 # Empty the hand
                bankroll = int(data[1])
                # risk = 1
                # if bankroll < 100:
                #     diff = 100 - bankroll
                #     if (float(math.log(diff)/math.log(10))) == 0:
                #         risk = 1
                #     elif bankroll > -50:
                #         risk = 1.0 / (float(math.log(diff)/math.log(10)))**(2)
                #     else:
                #         risk = 1.0 / (float(math.log(diff)/math.log(10)))**2

                # max_preflop_equity, max_flop_equity, max_turn_equity, max_river_equity = 0, 0, 0, 0 # Flush all equities
                max_preflop_equity, max_flop_equity = 0, 0


        # Clean up the socket.
        print MADBot_delta
        print otherbot_delta
        # print "\n".join(MADBot_delta)
        # print "=================================================="
        # print "\n".join(otherbot_delta)
        s.close()
Exemplo n.º 35
0
    #print board
    board = []
    players = []
    scores = []
    hands = []
    
    for p in tab.players:
<<<<<<< HEAD
        print p.player_number, p.hand.cards, Handevaluator.evalueate_hand(p.hand
=======
        card1 = p.hand.cards[0]
        card2 = p.hand.cards[1]
        hand = [Card(card1[0],card1[1]), Card(card2[0],card2[1])]
        

        score = HandEvaluator.evaluate_hand(hand, board)
        players.append(p.player_number)
        hands.append(hand)
        scores.append(score)

        
    #print(scores)
    #print(hands)
 #   print(players)
   # orbit[i] = np.column_stack((players,scores,hand))
        print p.player_number,score, p.hand.cards
        
    tab.flop()
    flop1 = tab.community_cards[0]
    flop2 = tab.community_cards[1]
    flop3 = tab.community_cards[2]