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 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.º 3
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.º 4
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.º 5
0
def get_rank(hand, board):
    from card import Card
    hand = [
        Card(CARD_MAPPING[h_card[:1]], SUIT_MAPPING[h_card[1:].lower()])
        for h_card in hand
    ]
    board = [
        Card(CARD_MAPPING[b_card[:1]], SUIT_MAPPING[b_card[1:].lower()])
        for b_card in board
    ]
    return HandEvaluator.evaluate_handboard_rank(hand, board)
Exemplo n.º 6
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.º 7
0
def getCard(card):
    card_type = card[1]
    cardnume_code = card[0]
    card_num = 0
    card_num_type = 0
    if card_type == 'H':
        card_num_type = 1
    elif card_type == 'S':
        card_num_type = 2
    elif card_type == 'D':
        card_num_type = 3
    else:
        card_num_type = 4

    if cardnume_code == 'T':
        card_num = 10
    elif cardnume_code == 'J':
        card_num = 11
    elif cardnume_code == 'Q':
        card_num = 12
    elif cardnume_code == 'K':
        card_num = 13
    elif cardnume_code == 'A':
        card_num = 14
    else:
        card_num = int(cardnume_code)

    return Card(card_num, card_num_type)
Exemplo n.º 8
0
def getCard(card):
    card_type = card[1].lower()
    cardnume_code = card[0]
    card_num = 0
    card_num_type = 0
    if card_type == 's':
        card_num_type = 1
    elif card_type == 'h':
        card_num_type = 2
    elif card_type == 'd':
        card_num_type = 3
    elif card_type == 'c':
        card_num_type = 4

    if cardnume_code == 'T':
        card_num = 10
    elif cardnume_code == 'J':
        card_num = 11
    elif cardnume_code == 'Q':
        card_num = 12
    elif cardnume_code == 'K':
        card_num = 13
    elif cardnume_code == 'A':
        card_num = 14
    else:
        card_num = int(cardnume_code)

    return Card(card_num, card_num_type)
Exemplo n.º 9
0
def convert_list_to_card_list(lst):
    """
    lst has entries like (N, M), and will convert it to Card(N, M)
    """

    card_lst = []
    for i in lst:
        card_lst.append(Card(i[0], i[1]))

    return card_lst
Exemplo n.º 10
0
    def genCardFromId(self, cardID):
        if int(cardID) > 13:
            rank = int(cardID) % 13
            if rank == 0:
                suit = int((int(cardID) - rank) / 13)
            else:
                suit = int((int(cardID) - rank) / 13) + 1

            if (rank == 1):
                rank = 14
                suit -= 1
            elif (rank == 0):
                rank = 13
            return Card(rank, suit)
        else:
            suit = 1
            rank = int(cardID)
            if (rank == 1):
                rank = 14
            return Card(rank, suit)
Exemplo n.º 11
0
def _map_integer_to_card(n):
    '''
	Maps an integer (or a list of integers) in range [0, 51] to a Card object
	Goes in order of rank, then suit (so all the 2's, then all the 3's, etc.)

	@n: an integer or list of integers in range [0, 51]
	'''
    if type(n) == list:
        result = []
        for num in n:
            assert num in range(
                52), "Error: integer to be mapped must be in range [0, 51]"
            r = int(num / 4) + 2  # converts ranks from [0, 12] to [2, 14]
            s = int(num % 4) + 1  # converts suits from [0, 3] to [1, 4]
            result.append(Card(r, s))
        return result
    else:
        r = int(n / 4) + 2
        s = int(n % 4) + 1
        return Card(r, s)
Exemplo n.º 12
0
def genCardFromId(cardID):
    if int(cardID) > 13:
        rank = int(cardID) % 13
        if rank == 0:
            suit = int((int(cardID) - rank) / 13)
        else:
            suit = int((int(cardID) - rank) / 13) + 1

        if (rank == 0):
            rank = 14
        else:
            rank += 1
        return Card(rank, suit)
    else:
        suit = 1
        rank = int(cardID)
        if (rank == 0):
            rank = 14
        else:
            rank += 1
        return Card(rank, suit)
Exemplo n.º 13
0
def main():

    # pre-load images on startup
    # C D H S
    cardLibrary = {}
    rollSuit = ["C", "D", "H", "S"]

    for i in range(0, 5):
        COMMUNITY_XPOS.append(COMMUNITY_XPOS_START + (COMMUNITY_OFFSET_X * i))

    for n in range(0, 13):
        reverser = 5
        for s in range(0, 4):
            reverser -= 1
            nS = reverser
            cNum = n + 2
            lS = rollSuit[s]
            archedImg = Image.open("cardDeck\\community\\{}{}.png".format(
                cNum, lS))

            archedImg = archedImg.crop((0, 40, 35, 80))

            fatHash = imagehash.phash(archedImg)

            cardLibrary["{}{}".format(
                cNum, lS)] = [fatHash, Card(cNum, nS), archedImg]

    # x = COMMUNITY_XPOS
    # y = COMMUNITY_YPOS + OFFSET
    x = LHU_XPOS - 5
    y = SU_YPOS + COMMUNITY_OFFSET_Y

    w = x + WIDTH
    h = (y + HEIGHT)
    imt = getRectAsImage((x, y, w, h))
    # imt = getRectAsImage(
    #     (RHC_XPOS, CANT_YPOS, RHC_XPOS+WIDTH,CANT_YPOS+HEIGHT)).rotate(
    #         10,Image.BILINEAR,fillcolor="white")
    imt.show()
    testImageHash = imagehash.phash(imt)

    winningKey = 0
    lowestDiff = 9999999
    for k, v in cardLibrary.items():
        diff = abs(v[0] - testImageHash)
        print(k, diff, lowestDiff)
        if diff < lowestDiff:
            lowestDiff = diff
            winningKey = k

    print(winningKey, cardLibrary[winningKey][1])
    cardLibrary[winningKey][2].show()
Exemplo n.º 14
0
    def genCardFromId(self, cardID):
        #LOG.info("------------MontecarloPokerBot genCardFromId---------------------")
        if int(cardID) > 13:
            rank = int(cardID) % 13
            if rank == 0:
                suit = int((int(cardID) - rank) / 13)
            else:
                suit = int((int(cardID) - rank) / 13) + 1

            if (rank == 0):
                rank = 14
            else:
                rank += 1
            return Card(rank, suit)
        else:
            suit = 1
            rank = int(cardID)
            if (rank == 0):
                rank = 14
            else:
                rank += 1
            return Card(rank, suit)
Exemplo n.º 15
0
def BUILD_DECK():
	"""
	Returns a deck of 52 cards in order of 2c-As

	@vals: corresponds 2-14 to 2-A
	@suits: correspond 1-4 to [s, h, d, c] # congruent to pokereval Card
	"""
	vals = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
	suits = [1, 2, 3, 4]

	for s in suits:
		for v in vals:
			deck.append(Card(v, s))
	return deck
Exemplo n.º 16
0
 def genCardFromId(self, cardID):
     if int(cardID) > 13:
         suit = (int(cardID) - 1) / 13 + 1
         rank = int(cardID) % 13
         if rank == 1:
             rank = 14
         elif rank == 0:
             rank = 13
     else:
         suit = 1
         if int(cardID) == 1:
             rank = 14
         else:
             rank = int(cardID)
     # print "rank", rank, "suit", suit
     return Card(rank, suit)
Exemplo n.º 17
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.º 18
0
def getCard(cards):
    from card import Card
    return [
        Card(CARD_MAPPING[h_card[:1]], SUIT_MAPPING[h_card[1:].lower()])
        for h_card in cards
    ]
Exemplo n.º 19
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.º 20
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 False == True:  # Logging
                    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 = [
                        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.90:
                                if (rand < 0.05):
                                    s.send("CHECK\n")
                                elif (risk < 0.2):
                                    s.send("CALL\n")
                                else:
                                    s.send(cmd + ":" + str(u) + "\n")
                            elif max_flop_equity >= 0.80:
                                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("CHECK\n")
                                else:
                                    s.send(cmd + ":" + str(l) + "\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 = [
                        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("CHECK\n")
                            else:
                                if (rand < 0.05):
                                    s.send("CALL\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 = [
                        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("CHECK\n")
                            else:
                                if (rand < 0.05):
                                    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.º 21
0
import random
import itertools

from baralho import Baralho
from jogador import Jogador
from mesa import Mesa
from regras import Regras
from pokereval.card import Card
from pokereval.hand_evaluator import HandEvaluator

bars = [Card(2,"s"),Card(3,"s"),Card(4,"s"),Card(5,"s"),Card(6,"s"),Card(7,"s"),Card(8,"s"),Card(9,"s"),Card(10,"s"),Card("J","s"),Card("Q","s"),Card("K","s"),Card("A","s")]
barh = [Card(2,"h"),Card(3,"h"),Card(4,"h"),Card(5,"h"),Card(6,"h"),Card(7,"h"),Card(8,"h"),Card(9,"h"),Card(10,"h"),Card("J","h"),Card("Q","h"),Card("K","h"),Card("A","h")]
barc = [Card(2,"c"),Card(3,"c"),Card(4,"c"),Card(5,"c"),Card(6,"c"),Card(7,"c"),Card(8,"c"),Card(9,"c"),Card(10,"c"),Card("J","c"),Card("Q","c"),Card("K","c"),Card("A","c")]
bard = [Card(2,"d"),Card(3,"d"),Card(4,"d"),Card(5,"d"),Card(6,"d"),Card(7,"d"),Card(8,"d"),Card(9,"d"),Card(10,"d"),Card("J","d"),Card("Q","d"),Card("K","d"),Card("A","d")]

bar = bars + barh + barc + bard

j = []
for k in range(1,9):
    player = Jogador(k)
    j.append(player)
baralho = Baralho(bar)
baralho2 = Baralho(bar)
mesa = Mesa()
regras = Regras()

while True:
    for i in range(0,8):
        j[i].reset()
    print("Digite o numero de jogadores entre 8 a 2 ou '0' para sair: ", end='')
    nj = int(input())
Exemplo n.º 22
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.º 23
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.º 24
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()