Beispiel #1
0
    def calc_hand_strength(self, game):
        score = [0, 0]
        table = game.table[:]
        for i in range(0, 500):
            deck = Deck()
            new = 0
            player1_hand = self.hand
            player2_hand = deck.draw(2)
            if table == []:
                table = deck.draw(3)
                while len(set(player1_hand + player2_hand + table)) < len(player1_hand) + len(player2_hand) + len(table):
                    player2_hand = deck.draw(2)
                    table = deck.draw(3)
                new = 1
            if len(player1_hand) + len(player2_hand) + len(table) == len(set(player1_hand + player2_hand + table)):
                p1_score = game.evaluator.evaluate(table, player1_hand)
                p2_score = game.evaluator.evaluate(table, player2_hand)

                if p1_score < p2_score:
                    score[0] += 1
                    score[1] += 1
                elif p2_score < p1_score:
                    score[1] += 1
                else:
                    score[0] += 1
                    score[1] += 2
                if new == 1:
                    table = []
        strength = score[0] / score[1]
        return strength
Beispiel #2
0
class Game():
    """
    Contains a deck of cards that can be accessed by players to play
    various card games.
    """

    def __init__(self, bot, name='kiwi'):
        self.players = []
        self.name = name
        self.deck = Deck()
        self.visible_cards = []
        self.bot = bot
        self.potpies = 0

    def add_player(self, player):
        self.players.append(player)

    def shuffle(self):
        self.deck.shuffle()
        self.visible_cards = []

    def deal(self, ncards):
        for i in range(ncards):
            for p in self.players:
                p.cards.append(self.deck.draw())

    def flip_flop(self):
        """Create flop.
        Flips over 3 cards and makes them publicly visible, as would
        happen when creating the flop in Texas Hold'em.
        """
        self.visible_cards += self.deck.draw(3)

    def flip_cards(self, ncards=1):
        """Like flip_flop, but allows variable number of cards."""
        if ncards == 1:
            self.visible_cards.append(self.deck.draw(ncards))
        else:
            self.visible_cards += self.deck.draw(ncards)

    def query_players(self):
        players = '%s players: ' % self.name
        for p in self.players:
            players += '%s ' % p.tag
        return players

    def query_state(self):
        info = '%s visible cards: ' % self.name
        for c in self.visible_cards:
            info += Card.int_to_pretty_str(c)
        info += ', potpies: %d' % self.potpies
        return info

    def message_players(self, message):
        uids = []
        for p in self.players:
            uids.append(p.uid)
        self.bot.message_players(uids, message)
Beispiel #3
0
def setup(n, m):
    deck = Deck()

    boards = []
    hands = []

    for i in range(n):
        boards.append(deck.draw(m))
        hands.append(deck.draw(2))
        deck.shuffle()

    return boards, hands
def setup(n, m):

    deck = Deck()

    boards = []
    hands = []

    for i in range(n):
        boards.append(deck.draw(m))
        hands.append(deck.draw(2))
        deck.shuffle()

    return boards, hands
Beispiel #5
0
def is_win(hand, board, player_num):
    '''
    模拟一局游戏,判断自己是否获胜
    :param hand:
    :param board:
    :param player_num:
    :return: True or False
    '''

    # 生产一副新牌
    deck = Deck()
    # 去除目前自己的手牌
    deck.cards.remove(hand[0])
    deck.cards.remove(hand[1])

    # 去除目前已知桌牌
    for board_card in board:
        deck.cards.remove(board_card)

    # 随机获取剩余桌牌
    new_board_cards = deck.draw(5 - len(board))

    # 如果 (5 - len(board)) 等于 1,那么取出的会是一个int
    if type(new_board_cards) == int:
        new_board_cards = [new_board_cards]

    # 5 张桌面牌
    draw_board = board + new_board_cards

    # 计算自己牌的大小,值越小牌越好
    my_cards_evaluate = evaluator.evaluate(draw_board, hand)
    # 最大值是7432
    other_cards_evaluate = 10000
    for i in range(player_num - 1):
        # 为其他玩家随机发两张牌
        player_cards = deck.draw(2)

        # 机器玩家牌的大小
        random_other_cards_evaluate = evaluator.evaluate(draw_board, player_cards)

        # 更新其他玩家最大牌
        if random_other_cards_evaluate < other_cards_evaluate:
            other_cards_evaluate = random_other_cards_evaluate

        # 如果已有一个玩家的牌大于自己,判断自己输
        if other_cards_evaluate < my_cards_evaluate:
            return False

    # 没有玩家牌大于自己,判定自己赢
    return True
Beispiel #6
0
def run(number):
    """
    This function generates a population sample with size sample.
    It also computes probabilities for each hand, considering a
    frequentist approach.

    Arguments:
        - number (int): run ID

    Returns:
        - stats (str): returns a JSON formatted string containing
            probabilities for each poker hand
    """
    print 'starting run #{0}'.format(number)
    evaluator = Evaluator()
    poker_hands = defaultdict(int)

    for _ in range(SAMPLE_SIZE):
        deck = Deck()
        p1_hand = deck.draw(5)
        p1_score = evaluator.evaluate(p1_hand, [])
        if p1_score == 1:  # just a little hack
            poker_hands['Royal Flush'] += 1
        else:
            p1_class = evaluator.get_rank_class(p1_score)
            poker_hands[evaluator.class_to_string(p1_class)] += 1

    stats = dict((k, round(float(v)/SAMPLE_SIZE, 7))
                 for k, v in poker_hands.items())
    return json.dumps(stats)
Beispiel #7
0
def sample_win_probability_dumb(board,
                                value_to_beat,
                                deck,
                                left_to_deal,
                                nsamples=100):
    nwins = 0
    cards = deck.cards
    copied_deck = Deck()
    for _ in xrange(nsamples):
        shuffle(cards)
        copied_deck.cards = list(cards)
        won = False
        decided = False
        best_value = value_to_beat
        chosen_value = 10**10
        for x in range(left_to_deal):
            hand = copied_deck.draw(2)
            value = evaluator.evaluate(board, hand)
            if value < value_to_beat and not decided:
                # have to decide whether to stay!
                win_prob = chance_to_win_given_choice(board, value, deck,
                                                      left_to_deal - x - 1)
                if win_prob > 0.5:
                    chosen_value = value
                    decided = True
            best_value = min(best_value, value)

        if chosen_value < best_value:
            nwins += 1

    return nwins * 1.0 / nsamples
Beispiel #8
0
def possibility_of_getting_burnt(board,
                                 chosen_value,
                                 deck,
                                 left_to_deal,
                                 nsamples=100):
    # the only way that keeping the hand with a <50% chance of winning
    # is the correct move is if there is at least some possibility that
    # there will be *two* hands that beat you, and moreover they come in
    # the wrong order

    if left_to_deal <= 1:
        # you IDIOT, of course keep your hand
        return 0

    nburns = 0
    cards = deck.cards
    copied_deck = Deck()
    for _ in xrange(nsamples):
        shuffle(cards)
        copied_deck.cards = list(cards)
        got_beat = False
        value_to_beat = -1
        for x in range(left_to_deal):
            hand = copied_deck.draw(2)
            value = evaluator.evaluate(board, hand)
            if got_beat and value < value_to_beat:
                nburns += 1
                break
            if value < chosen_value:
                got_beat = True
                value_to_beat = value
    return nburns * 1.0 / nsamples
def run_basic_strategy_game(manual=False):
    deck = Deck()

    player_hand = deck.draw(3)
    dealer_hand = deck.draw(3)

    action_computer = decision_basic_strategy(player_hand, dealer_hand)
    result_computer = determine_payout(player_hand, dealer_hand,
                                       action_computer)

    # let the user try to play (if requested). user can play after the computer
    # since we are not holecarding
    if manual:
        print(f"\n\n\n\n===========[New Three Card Poker Hand]===========")
        print(f"Player Hand: {player_hand}")
        action_human = bool(int(input("0-Fold or 1-Call >>> ")))
        result_human = determine_payout(player_hand, dealer_hand, action_human)

        sort_hand(player_hand)
        sort_hand(dealer_hand)
        print(f"\n----------- Summary -----------")
        print(f"Player Hand: {player_hand}")
        print(f"Dealer Hand: {dealer_hand}")
        print(f"Computer's Decision: {action_string(action_computer)}")
        print(
            f"Result: Computer got {result_computer} units and you got {result_human} units"
        )

        return (result_computer, result_human)

    return result_computer
Beispiel #10
0
def is_good(board_cards=[], hand_cards=['AH', 'KD']):
    if (len(board_cards) + len(hand_cards) == 0):
        return False

    board = []
    for x in board_cards:
        c = Card.new('{0}{1}'.format(x[0], x[1].lower()))
        board.append(c)

    hand = []
    for x in hand_cards:
        c = Card.new('{0}{1}'.format(x[0], x[1].lower()))
        hand.append(c)

    evaluator = Evaluator()
    deck = Deck()
    random_cards = deck.draw(5 - len(board) - len(hand))
    score = evaluator.evaluate(board + random_cards, hand)
    rank_class = evaluator.get_rank_class(score)

    print_cards(board + random_cards + hand, rank_class)

    if (rank_class < 9):
        return True
    return False
    def cross_over_aux(self,chromosome1,chromosome2,position):
        cross_over = 0
        crossed = False
        deck = Deck()
        hand = deck.draw(5)
        new_chromosome = Player(hand)
        for gene in range(NUMBER_OF_PLAYERS-1):
            if (not(crossed)):
                if (position == cross_over):
                    crossed = True
                #Mutation
                random_mutation = random.randint(0,100)
                if (0 < random_mutation <= MUTATION_PROBABILITY*100):
                    mutated = self.mutate()
                    new_chromosome.hand[cross_over] = mutated
                    # new_chromosome.hand[cross_over] = chromosome1.hand[cross_over]
                else:
                    new_chromosome.hand[cross_over] = chromosome1.hand[cross_over]


            else:
                #Mutation
                random_mutation = random.randint(0,100)
                if (0 < random_mutation <= MUTATION_PROBABILITY*100):
                    mutated = self.mutate()
                    new_chromosome.hand[cross_over] = mutated
                        # new_chromosome.hand[cross_over] = chromosome1.hand[cross_over]
                else:
                    new_chromosome.hand[cross_over] = chromosome2.hand[cross_over]


            cross_over += 1
        return new_chromosome
Beispiel #12
0
class Table:
    '''
    Creates a poker table containing the deck, and a means to store the cards.
    '''
    def __init__(self):
        self.deck = Deck()
        self.cards = []
        self.pot = 0
        self.ante = 0

    '''
    Adds a card to the cards on the table.
    '''

    def addCard(self, card):
        self.cards.append(card)

    '''
    Adds to the current pot on the table.
    '''

    def addToPot(self, amt):
        self.pot += amt

    '''
    Gets the current pot.
    '''

    def getPot(self):
        return self.pot

    '''
    Gets the community cards on the table.
    '''

    def getCards(self):
        return self.cards

    '''
    Draws from the deck.
    '''

    def draw(self):
        return self.deck.draw()

    def setAnte(self, ante):
        self.ante = ante

    def getAnte(self):
        return self.ante

    '''
    Resets the table.
    '''

    def reset(self):
        self.deck.shuffle()
        del self.cards[:]
        self.ante = 0
        self.pot = 0
def run_holecarding_strategy_game(manual=False):
    deck = Deck()

    player_hand = deck.draw(3)
    dealer_hand = deck.draw(3)

    dealer_holecard = dealer_hand[0]

    # now the computer can play out the hand (and possibly sort dealer's hand)
    action_computer = decision_holecarding(player_hand, dealer_hand)
    result_computer = determine_payout(player_hand, dealer_hand,
                                       action_computer)

    # print hand summary
    if manual:
        print(f"\n\n\n\n===========[New Three Card Poker Hand]===========")
        print(f"Player Hand: {player_hand}")
        print(f"Dealer's Holecard: {dealer_holecard}")
        action_human = bool(int(input("0-Fold or 1-Call >>> ")))
        result_human = determine_payout(player_hand, dealer_hand, action_human)

        sort_hand(player_hand)
        sort_hand(dealer_hand)
        print(f"\n----------- Summary -----------")
        print(f"Player Hand: {player_hand}")
        print(f"Dealer Hand: {dealer_hand}")
        print(f"Computer's Decision: {action_string(action_computer)}")
        print(
            f"Result: Computer got {result_computer} units and you got {result_human} units"
        )

        return (result_computer, result_human)

    return result_computer
Beispiel #14
0
def sample_win_probability(board,
                           value_to_beat,
                           deck,
                           left_to_deal,
                           nsamples=50):
    pwin = 0.
    cards = deck.cards
    copied_deck = Deck()
    for _ in xrange(nsamples):
        shuffle(cards)
        copied_deck.cards = list(cards)
        new_hand = copied_deck.draw(2)
        value = evaluator.evaluate(board, new_hand)
        if value > value_to_beat:
            # the new hand is worse, so no decision to be made
            if left_to_deal > 1:
                # just burn the cards and keep going
                pwin += sample_win_probability(board, value_to_beat,
                                               copied_deck, left_to_deal - 1)
            elif left_to_deal == 1:
                # this was our last chance, we lost
                pwin += 0
        else:
            if left_to_deal == 1:
                # this was our last hand.  We won!
                pwin += 1
            else:
                # we have a choice.  What do we do??
                prob_if_stayed, prob_burn = chance_to_win_given_choice(
                    board,
                    value,
                    copied_deck,
                    left_to_deal - 1,
                    return_burns=True)
                # we have the inequality
                #       P(there is a better hand) - P(you get "burnt")
                #           < P(win if you pass) < P(there is a better hand)
                # also,
                #  P(there is a better hand) = 1 - P(win if you stay)
                # If P(win if you pass) < P(win if you stay) then you should stay
                # and if P(win if you pass) > P(win if you stay) then you should continue
                if prob_if_stayed > 0.5:
                    # definitely should stay
                    pwin += prob_if_stayed
                    continue
                if prob_burn <= 0.1:
                    # if burns are pretty rare, then let's just say that
                    # the win probability is well approximated by the
                    # "dumb" strategy.
                    prob_if_passed = sample_win_probability_dumb(
                        board, value, copied_deck, left_to_deal - 1)
                else:
                    prob_if_passed = sample_win_probability(
                        board, value, copied_deck, left_to_deal - 1)
                pwin += max(prob_if_stayed, prob_if_passed)

    return pwin * 1. / nsamples
Beispiel #15
0
def setup(n, m):
    _hands = []
    _boards = []

    for i in range(n):

        deck = Deck()
        hand = []
        board = []
        for j in range(2):
            hand.append(deck.draw())
        for j in range(m):
            board.append(deck.draw())

        _hands.append(hand)
        _boards.append(board)

    return _boards, _hands
Beispiel #16
0
	def callAI(self, state): #CHANGE THIS FUNCTION. NEVER REFERENCE OTHER PLAYER'S CARDS. You are not allowed to cheat! (obviously) e.g. If we see curState.players[x].curHand, that's unacceptable.
		MAX_SCORE= 7462
		score = 0
		# we evaluate the score of the current situation and based on the estimated score, pick an acion
		# We randomly generate the board N times and get the average score
		N = 5
		i = 0

		if curState.curStage == "river":
			score = score + evaluator.evaluate(curState.board, self.curHand)
		else:
			while i < N:
				my_deck = Deck()
				my_board = my_deck.draw(0)

				if curState.curStage == "preflop":
					exclude = copy.deepcopy(self.curHand)
					my_board = self.draw(5, exclude, my_deck)

				elif curState.curStage == "flop":
					exclude = copy.deepcopy(self.curHand) + copy.deepcopy(curState.board)
					my_board = curState.board + self.draw(2, exclude, my_deck)

				elif curState.curStage == "turn":
					exclude = copy.deepcopy(self.curHand) + copy.deepcopy(curState.board)
					my_board = curState.board +  self.draw(1, exclude, my_deck)


				score = score + evaluator.evaluate(self.curHand, my_board)
				i = i + 1
			score = score / N
		#raiseAmount = random.randint(0, 100)
		#maxbid = max(raiseAmount, random.randint(0, 100))
		#if maxbid > self.money: #do not remove
		#	maxbid = self.money
		#if raiseAmount > self.money: #do not remove
		#	raiseAmount = self.money
		#possibleActions = ["check", ["raise", raiseAmount]] #can only check or raise, since only one action is processed. Fold if max bid is lower than the biggest raise.

		#There are 7462 scores in total (smaller is better). We choose an action based on the estimated score
		if score > MAX_SCORE * 9 / 10: # the score is too high, choose fold
			raiseAmount = 0
			action = ["raise", 0]
			maxbid = 0           # maxbid = 0, means fold
		elif score > MAX_SCORE / 2:
			action = ["check"]
			maxbid = 0
		else:
			raiseAmount = random.randint(0, self.money * (1 - score / MAX_SCORE) / 2)
			maxbid = max(raiseAmount, random.randint(0, self.money * (1 - score / MAX_SCORE)) )
			action = ["raise",raiseAmount ]
		return [ action, maxbid ]
Beispiel #17
0
def fast_eval(hole_card, public_card, players=9, simulations=1000):
    for i in range(0, len(hole_card)):
        hole_card[i] = Card.new(conv(hole_card[i]))
    for i in range(0, len(public_card)):
        public_card[i] = Card.new(conv(public_card[i]))
    win_rate = 0
    evaluator = Evaluator()
    for _ in range(simulations):
        deck = Deck()
        for c in hole_card:
            deck.cards.remove(c)
        for c in public_card:
            deck.cards.remove(c)
        player_hands = []
        for _ in range(players):
            player_hands.append(deck.draw(2))
        board = []
        board.extend(public_card)
        if 5 - len(public_card) == 1:
            board.append(deck.draw(1))
        else:
            board.extend(deck.draw(5 - len(public_card)))
        flag = True
        num = 0
        for p in player_hands:
            if evaluator.evaluate(board, p) < evaluator.evaluate(
                    board, hole_card):
                flag = False
                break
            elif evaluator.evaluate(board, p) > evaluator.evaluate(
                    board, hole_card):
                flag = False
                win_rate += 1
                break
            else:
                num += 1
        if flag:
            win_rate += 1.0 / num
    return 1.0 * win_rate / simulations
Beispiel #18
0
def get_score_by_simulate(board_cards, hand_cards, iteration=5):

    try:
        score_min = 10000  # deuces evaluate score, the small, the better
        board = []
        for x in board_cards:
            x = x.encode('ascii', 'ignore')
            c = Card.new('{0}{1}'.format(x[0], x[1].lower()))
            board.append(c)

        hand = []
        for x in hand_cards:
            x = x.encode('ascii', 'ignore')
            c = Card.new('{0}{1}'.format(x[0], x[1].lower()))
            hand.append(c)
        if (len(hand) + len(board) < 5):
            score_list = []
            for i in range(iteration):
                evaluator = Evaluator()
                deck = Deck()
                random_cards = deck.draw(5 - len(board) - len(hand))
                if (isinstance(random_cards, int)):
                    random_cards = [random_cards]
                score = evaluator.evaluate(board + random_cards, hand)
                score_list.append(score)

            score_list.remove(max(score_list))
            score_list.remove(min(score_list))

            return sum(score_list) / float(len(score_list))
        else:

            for board_five_match in combinations(board, 5 - len(hand)):
                evaluator = Evaluator()
                score = evaluator.evaluate(tuple(board_five_match),
                                           tuple(hand))
                if (score < score_min):
                    score_min = score
            return score_min
    except Exception as e:
        traceback.print_exc()
        printtolog('EXCEPTION={0}'.format(e))
        return score_min
Beispiel #19
0
    def calc_hand_strength(self, game):
        score = [0, 0]
        for i in range(0, 1000):
            deck = Deck()
            player1_hand = self.hand
            player2_hand = deck.draw(2)
            if len(list(set(player1_hand + game.table).intersection(player2_hand))) == 0:
                p1_score = game.evaluator.evaluate(game.table, player1_hand)
                p2_score = game.evaluator.evaluate(game.table, player2_hand)

                if p1_score < p2_score:
                    score[0] += 1
                    score[1] += 1
                elif p2_score < p1_score:
                    score[1] += 1
                else:
                    score[0] += 1
                    score[1] += 2
        strength = score[0] / score[1]
        return strength
def main():
    deck = Deck()
    board = deck.draw(5)
    solution = Solution()
    currentPopulation = 0
    #Generate initial population
    #Add the new population to the solution
    population = initial_population(NUMBER_OF_PLAYERS,deck)

    init_pop = Population(population, currentPopulation+1)
    solution.add_population(init_pop)

    while (currentPopulation < 10):
        # select chromosomes from the current population to apply cross_over and mutation
        solution.populations[currentPopulation].select_random_chromosomes()
        #Cross over and mutation
        new_population = solution.populations[currentPopulation].cross_over()
        currentPopulation += 1
        pop = Population(new_population, currentPopulation+1)
        solution.add_population(pop)
    print (solution)
Beispiel #21
0
    def __init__(self, checkpoint_dir):
        with open(checkpoint_dir + "encode_config.yaml", 'r') as yaml_file:
            self.encoding_config = yaml.load(yaml_file, Loader=yaml.FullLoader)

        all_card_rank_values = np.array([x for x in range(14)]).reshape(14, 1)
        # All possible suit values (0 - 4 inclusive)
        # +  9 - used for board cards when they have not been dealt
        all_card_suit_values = np.array([0, 1, 2, 4, 8]).reshape(5, 1)

        self.rank_enc = OneHotEncoder(handle_unknown='error',
                                      categories='auto')
        self.rank_enc.fit(all_card_rank_values)

        self.suit_enc = OneHotEncoder(handle_unknown='error',
                                      categories='auto')
        self.suit_enc.fit(all_card_suit_values)

        deck = Deck()
        all_card_raw_values = deck.draw(52)
        all_card_raw_values.sort()
        all_card_raw_values = np.array(all_card_raw_values).reshape(52, 1)
        self.raw_card_enc = OneHotEncoder(handle_unknown='error',
                                          categories='auto')
        self.raw_card_enc.fit(all_card_raw_values)

        # Put in  dummy variables for undealt cards
        self.table_card_ranks = [0 for x in range(5)]
        self.table_card_suits = [0 for x in range(5)]

        self.evaluator = Evaluator()

        self.min_max_scaling = lambda a, b, min_x, max_x, x: a + (
            (x - min_x) * (b - a)) / (max_x - min_x)

        self.preflop_suited_array = np.loadtxt(
            "./preflop_odds/suited_pair_scores.csv", delimiter=',')
        self.preflop_unsuited_array = np.loadtxt(
            "./preflop_odds/unsuited_pair_scores.csv", delimiter=',')
        self.normalise_preflop_arrays()
Beispiel #22
0
def get_score_by_simulate(hand, board, iteration=100):
    if(len(hand)+len(board)<=5):
        score_list = []
        for i in range(iteration):
            evaluator = Evaluator()
            deck = Deck()
            random_cards = deck.draw(5-len(board)-len(hand))
            score = evaluator.evaluate(board+random_cards, hand)
            score_list.append(score)
            
        score_list.remove(max(score_list))    
        score_list.remove(min(score_list))    
        
        return sum(score_list)/float(len(score_list))
    else:
        score_min = 9999999
        for board_five_match in combinations(board,5-len(hand)):
            evaluator = Evaluator()
            score = evaluator.evaluate(tuple(board_five_match), tuple(hand))
            if(score<score_min):
                score_min=score
        return score_min
Beispiel #23
0
def rank(evaluator, holeCards, boardCards):
    deck = Deck()

    allCards = holeCards.union(boardCards)
    while len(allCards) < 9:
        card = deck.draw(1)
        if len(allCards) != len(allCards.union([card])):
            allCards.add(card)
            boardCards.add(card)

    all2CardCombos = itertools.combinations(holeCards,2)
    all3CardCombos = itertools.combinations(boardCards,3)

    min_rank = 10000

    for handCombo in all2CardCombos:
        for boardCombo in all3CardCombos:
            rank = evaluator.evaluate(boardCombo, handCombo)
            if rank < min_rank:
                min_rank = rank

    return min_rank
Beispiel #24
0
def chance_to_win_given_choice(board,
                               chosen_value,
                               deck,
                               left_to_deal,
                               nsamples=100,
                               return_burns=False):
    if left_to_deal == 0:
        if return_burns:
            return (1., 0.)
        return 1.
    nwins = 0
    nburns = 0
    cards = deck.cards
    copied_deck = Deck()
    for _ in xrange(nsamples):
        shuffle(cards)
        copied_deck.cards = list(cards)
        won = True
        burnt = False

        value_to_beat = -1
        for x in range(left_to_deal):
            hand = copied_deck.draw(2)
            value = evaluator.evaluate(board, hand)
            if not won and value < value_to_beat:
                burnt = True
                break
            if value < chosen_value:
                won = False
                value_to_beat = value
        if won:
            nwins += 1
        if burnt:
            nburns += 1

    if return_burns:
        return (nwins * 1.0 / nsamples, nburns * 1.0 / nsamples)
    return nwins * 1.0 / nsamples
Beispiel #25
0
# Main training loop
# The program will conduct no_rounds training rounds, and then check if the file "quit" is present in
# the same folder as this script
# Note that bot 1 is treated as "player" and bot 2 is treated as the opponent
gs = Game_State()
learning_rate = 0.0001
#epsilon = 0.20

no_training_rounds = 100000
no_completed_epochs = 0
while True:
    for training_round in range(no_training_rounds):
        # Start new round and deal cards
        gs.clear_state()
        deck = Deck()
        gs.set_player_cards(deck.draw(2))
        gs.set_opponent_cards(deck.draw(2))
        gs.set_flop(deck.draw(3))
        pot = 0.0
        player_turn = training_round % 2  # Player 1 starts if 0, otherwise player 2 starts

        # Go through betting
        visited_action_states_1 = []
        visited_action_states_2 = []
        intermediate_payoffs_1 = []
        intermediate_payoffs_2 = []
        player_1_fold_f = False  # Flag for keeping track of if player 1 has folded
        player_2_fold_f = False  # Flag for keeping track of if player 2 has folded
        raise_f = False  # Flag for keeping track of if any subsequent "bets" are in fact raises
        while gs.get_possible_actions():
            if player_turn == 0:
Beispiel #26
0
class PokerMon(PokerBot):
	def __init__(self, preflop_tight_loose_threshold, aggresive_passive_threshold, bet_tolerance):
		self.preflop_tight_loose_threshold = preflop_tight_loose_threshold
		self.aggresive_passive_threshold = aggresive_passive_threshold
		self.bet_tolerance = bet_tolerance
		# deuces
		self.evaluator = Evaluator()
		self.deck = Deck()

	def game_over(self, isWin, winChips, data):
		print "Game Over"

	def dealer(self, n, used = []):
		# draw n cards not in used
		cards = []
		for i in range(n):
			while True:
				c = self.deck.draw(1)
				if c not in used:
					break
			cards.append(c)
		return cards

	def combat_power(self, hole, board_input, ppl, max_time = 1):
		Card.print_pretty_cards(hole+board_input)
		count = 0
		count_win = 0
		b_len = len(board_input)
		t_start = time.time()
		while True:
			self.deck.shuffle()
			board = board_input + self.dealer(5-b_len, hole+board_input)
			rank_my = self.evaluator.evaluate(hole, board)

			b_win = True
			player = []
			rank = []
			for i in range(ppl-1):
				player.append(self.dealer(2, hole+board))
				rank.append(self.evaluator.evaluate(player[i], board))
				if rank_my > rank[i]:
					b_win = False

			if b_win:
				count_win += 1

			count += 1
			t_end = time.time()
			if t_end - t_start > max_time:
				break

		return float(count_win)/float(count)

	def declareAction(self, hole, board, round, my_Raise_Bet, my_Call_Bet, Table_Bet, number_players, raise_count, bet_count, my_Chips, total_bet, players):
		out = []
		for i in players:
			if i['folded'] or not i['isSurvive']:
				out.append(i['playerName'])
		o_l = len(out)
		ppl = number_players
		if o_l > 0:
			print "Folders & Deads: {}".format(', '.join(out))
			ppl -= o_l

		if round == 'Deal':
			win_rate = self.combat_power(hole, [], 2)
		else:
			win_rate = self.combat_power(hole, board, ppl)
		print "Round:{}, Players:{}, WinRate:{}".format(round, ppl, win_rate)

		if round == 'Deal':
			if win_rate >= 0.50:
				action = 'check'
				amount = 0
			else:
				action = 'fold'
				amount = 0
		else:
			if win_rate >= 0.90:
				action = 'raise'
				amount = my_Chips
			elif win_rate >= 0.80:
				action = 'raise'
				amount = my_Raise_Bet
			elif win_rate >= 0.70:
				action = 'call'
				amount = my_Call_Bet
			elif win_rate >= 0.50:
				action = 'check'
				amount = 0
			else:
				action = 'fold'
				amount = 0
		return action, amount
Beispiel #27
0
i = 0
while len(players) > 1:
    print "-----------------"
    print ""
    i += 1
    curState.pot = 0
    #ante
    for player in curState.players:
        ante = min(player.money, 50)
        player.money -= ante
        curState.pot += ante
    #prepare board and deck
    deck = Deck()
    deck.shuffle()
    curState.board = deck.draw(0)
    for player in curState.players:
        player.curHand = []
        player.curHand = deck.draw(2)
    #create players for this round
    curState.curPlayers = curState.players[:]
    #go through betting stages
    for stage in range(0, len(curState.stages)):
        curState.curStage = curState.stages[stage]
        if curState.curStage == "flop":
            deal(3)
        elif curState.curStage == "turn":
            deal(1)
        elif curState.curStage == "river":
            deal(1)
        bet()
Beispiel #28
0
def generate_odds():
    card_ints = [i for i in range(13)]
    pair_combos = combinations_with_replacement(card_ints, 2)
    eval = Evaluator()

    pair_scores = np.zeros(shape=(13, 13))

    pair_suits = [8, 8]
    for x in pair_combos:
        deck = Deck()
        deck_match_idxs = []
        hero_cards = [None, None]

        if x[0] == x[1]:
            continue

        # Find cards in deck
        for deck_idx, card in enumerate(deck.cards):

            if x[0] == Card.get_rank_int(card) and pair_suits[0] == Card.get_suit_int(card):
                hero_cards[0] = card
                deck_match_idxs.append(deck_idx)

            if x[1] == Card.get_rank_int(card) and pair_suits[1] == Card.get_suit_int(card):
                hero_cards[1] = card
                deck_match_idxs.append(deck_idx)

        # Remove hero cards from deck
        deck.cards = [i for idx, i in enumerate(deck.cards) if idx not in deck_match_idxs]

        # Repeat x times
        num_wins = 0
        num_losses = 0
        while num_wins + num_losses < 10000:
            # Draw villan cards
            villan_cards = deck.draw(2)

            # Draw five card board
            board = deck.draw(5)


            # Find winner
            hero_rank = eval.evaluate(hero_cards, board)
            villan_rank = eval.evaluate(villan_cards, board)

            if hero_rank < villan_rank:
                num_wins += 1

            elif hero_rank > villan_rank:
                num_losses += 1

            else:
                None

            # Put villan and board cards back into deck
            deck.cards.extend(villan_cards)
            deck.cards.extend(board)


            # Shuffle deck for next draw
            shuffle(deck.cards)


        pair_scores[x[0], x[1]] = num_wins / (num_wins + num_losses)
        pair_scores[x[1], x[0]] = num_wins / (num_wins + num_losses)
        np.savetxt('./suited_pair_scores.csv', pair_scores, delimiter=',', fmt='%5f')
        print(pair_scores)
Beispiel #29
0
class Game:
    def __init__(self, player_list, chips, blinds):
        self.player_list = player_list
        self.player_num = len(player_list)
        #self.hands = [[] for i in range(len(player_list))]
        self.deck = Deck()
        self.evaluator = Evaluator()
        self.blinds = blinds
        self.chips = chips
        self.pot = [0 for x in range(0,self.player_num)]
        self.table_chips = 0
        self.raise_counter = 0
        self.table = []
        self.strengths =[[], []]

    def dealCards(self):
        for i in range(0, self.player_num):
            self.player_list[i].hand = self.deck.draw(2)
            Card.print_pretty_cards(self.player_list[i].hand)

    def resetChips(self):
        for i in range(0, self.player_num):
            self.player_list[i].chips = self.chips
            self.player_list[i].resetBets

    def shuffleCards(self):
        self.deck = Deck()

    def clearTableChips(self):
        self.table_chips = 0

    def resetPot(self):
        self.pot = 0

    def rounds(self, round_num):
        if round_num == 1:
            print("The Flop")
            self.table += self.deck.draw(3)
        elif round_num == 2:
            print("The Turn")
            self.table += [self.deck.draw(1)]
        elif round_num == 3:
            print("The River")
            self.table += [self.deck.draw(1)]
        else:
            print("Showdown")
        Card.print_pretty_cards(self.table)
        for i in range(len(self.player_list)):
            self.strengths[i].append(self.player_list[i].calc_hand_strength(self))

    #returns list of players remaining in hand in order of hand strength
    def handRank(self):
        scores = []
        for i in range(0, self.player_num):
            if self.player_list[i].folded == False:
                strength = self.evaluator.evaluate(self.table, self.player_list[i].hand)
                scores.append([i, strength])
                print self.player_list[i].name + ": " + self.evaluator.class_to_string(self.evaluator.get_rank_class(strength))
                Card.print_pretty_cards(self.player_list[i].hand)
        scores = sorted(scores,key=itemgetter(1))
        groups = groupby(scores, itemgetter(1))
        result = [[item[0] for item in data] for (key, data) in groups]
        for i in result[0]:
            print self.player_list[i].name + " wins!"
        return result

    def play(self):
        # Gameplay is initilalized
        self.resetChips()
        # Position of dealer at the beginning
        dealer = 0
        while True:
            self.shuffleCards()
            self.pot = [0 for x in range(0,self.player_num)]
            self.table_chips = 0
            self.raise_counter = 0
            self.table = []
            self.strengths =[[], []]
            counter = 0
            for i in range(self.player_num):
                if self.player_list[i].chips <= 0:
                    counter += 1
                else:
                    self.player_list[i].folded = False
            if counter == self.player_num - 1:
                print "Game Over"
                break
            print "Next Round"
            self.player_list = np.roll(self.player_list, 1)
            min_bet = 0
            # Round starts
            # People are dealt cards at the start of the round
            self.dealCards()
            # Small and Big blinds are put on the table
            self.player_list[(dealer + 1) % self.player_num].chips -= self.blinds[0]
            #self.player_list[(dealer + 1) % self.player_num].current_bet = self.blinds[0]
            print(self.player_list[(dealer + 1) % self.player_num].name + " pays small blind of " + str(self.blinds[0]))
            self.pot[(dealer + 1) % self.player_num] = self.blinds[0]
            self.player_list[(dealer + 2) % self.player_num].chips -= self.blinds[1]
            #self.player_list[(dealer + 2) % self.player_num].current_bet = self.blinds[1]
            print(self.player_list[(dealer + 2) % self.player_num].name + " pays big blind of " + str(self.blinds[1]))
            self.pot[(dealer + 2) % self.player_num] = self.blinds[1]
    #self.table_chips += self.blinds[1] + self.blinds[0]
            min_bet = self.blinds[1]
            people_in = self.player_num
            turn = 0
            # Rounds of betting
            for j in xrange(0, 4):
                raise_counter = -10
                place = dealer + 2
                raise_const = 1
                counter = 0
                for i in range(self.player_num):
                    if self.player_list[i].chips > 0:
                        counter += 1
                while raise_counter != min_bet:
                    raise_counter = min_bet
                    for i in xrange(place + 1, place + people_in + raise_const):
                        if self.player_list[i % people_in].folded == True or self.player_list[i % people_in].chips == 0 or counter == 1:
                            continue
                        print("Current bet: " + str(min_bet))
                        self.player_list[i % people_in].printName()
                        amount_bet = self.player_list[i % people_in].bet(min_bet,self.pot[i % people_in])
                        #still have to verify correct bet
                        self.pot[i % people_in] += amount_bet
                        tot = self.pot[i % people_in]
                        '''
                        self.table_chips += amount_bet
                        tot = amount_bet + self.player_list[i % people_in].current_bet
                        self.player_list[i % self.player_num].current_bet += amount_bet
                        print(self.player_list[i % people_in].chips)
                        '''
                        if min_bet < tot:
                            min_bet = tot
                            place = i
                            raise_const = 0
                            break
                #self.pot += self.table_chips
                #self.clearTableChips()
                #for i in xrange(0, self.player_num):
                #    self.player_list[i].resetBets()
                turn += 1
                self.rounds(turn)

            #distribute chips to winner(s)
            print self.strengths
            handRank = self.handRank()
            #print repr(handRank) + '\n'
            for winner in handRank:
                #print repr(winner) + '\n'
                #for tied winners, sort by the amount they've bet (least first)
                winner.sort(key = lambda x: self.pot[x])
                #loop over tied winners, resolve smaller sidepots first
                for i in range(0,len(winner)):
                #loop over pot and grab their bet size from every other player
                    amount_bet = self.pot[winner[i]]
                    chips_won = 0
                    for j in range(0,len(self.pot)):
                        if self.pot[j] > amount_bet:
                            self.pot[j] -= amount_bet
                            chips_won += amount_bet
                        else:
                            chips_won += self.pot[j]
                            self.pot[j] = 0
                    #split chips proportionally among players that bet enough for this pot
                    for j in range(i,len(winner)):
                        self.player_list[winner[j]].chips += int(chips_won*(1/(len(winner)-i)))
                        #print "player %d won %d chips \n" % (winner[j],chips_won*(1/(len(winner)-i)))
                        print "Player %s won %d chips" % (self.player_list[winner[j]].name,chips_won*(1/(len(winner)-i)))
            for i in range(self.player_num):
                print self.player_list[i].chips
            print "\n"
Beispiel #30
0
import argparse
import time
from deuces import Card, Deck, Evaluator

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-i', help='iteration')
    parser.add_argument('-n', help='number_hash_bins')

    i = int(parser.parse_args().i)
    N = int(parser.parse_args().n)

    start_time = time.time()
    for _ in range(100):
        board = None
        while board == None:
            deck = Deck()
            b = deck.draw(5)
            if hash(str(b)) % N == i:
                board = b
    print(
        "Average time to find a board hash match is %f seconds using %s bins" %
        ((time.time() - start_time) / 100., N))
 def mutate(self):
     deck = Deck()
     card = deck.draw()
     return card
Beispiel #32
0
class Game:
    def __init__(self, player_list, chips, blinds, num_hands=100):
        self.player_list = player_list
        self.player_num = 2
        self.num_hands = num_hands
        self.deck = Deck()
        self.evaluator = Evaluator()
        self.blinds = blinds
        self.chips = chips
        self.pot = [0 for x in range(0, 2)]
        self.table_chips = 0
        self.raise_counter = 0
        self.table = []
        self.bet_round = 0
        self.strengths =[[], []]
        self.last_bets = [None,None]
        self.times = dict([('main',{'total':0,'count':0}),('strength',{'total':0,'count':0})]+[(player.name,{'total':0,'count':0}) for player in player_list])

    # Function for dealing cards to every player
    def dealCards(self):
        for i in range(2):
            self.player_list[i].hand = self.deck.draw(2)
            print self.player_list[i].name
            Card.print_pretty_cards(self.player_list[i].hand)

    # Reset player chip amounts and bets
    def resetChips(self):
        for i in range(2):
            self.player_list[i].chips = self.chips
            self.player_list[i].resetBets

    # Shuffle deck
    def shuffleCards(self):
        self.deck = Deck()

    # Clear chips off table
    def clearTableChips(self):
        self.table_chips = 0

    # Reset the pot to 0
    def resetPot(self):
        self.pot = 0

    # Reset every player's flag that indicates folding
    def resetFolds(self):
        for player in self.player_list:
            player.folded = False

    # Adds one card to the table and prints cards each time the round ends
    def rounds(self):
        round_num = self.bet_round
        if round_num == 1:
            print("The Flop")
            self.table += self.deck.draw(3)
        elif round_num == 2:
            print("The Turn")
            self.table += [self.deck.draw(1)]
        elif round_num == 3:
            print("The River")
            self.table += [self.deck.draw(1)]
        else:
            print("Showdown")
        Card.print_pretty_cards(self.table)
        for i in range(2):
            self.strengths[i].append(self.player_list[i].calc_hand_strength(self))

    #returns list of players remaining in hand in order of hand strength
    def handRank(self):
        scores = []
        for i in range(2):
            if self.player_list[i].folded == False:
                strength = self.evaluator.evaluate(self.table, self.player_list[i].hand)
                scores.append([i, strength])
                print self.player_list[i].name + ": " + self.evaluator.class_to_string(self.evaluator.get_rank_class(strength))
                Card.print_pretty_cards(self.player_list[i].hand)
        scores = sorted(scores,key=itemgetter(1))
        groups = groupby(scores, itemgetter(1))
        result = [[item[0] for item in data] for (key, data) in groups]
        for i in result[0]:
            print self.player_list[i].name + " wins!"
        return result

    def distribute_chips(self, order=0):
        #keep track of winnings for each player so we can pass it to bots
        winnings = self.player_num*[0]

        if order == 0:
            handRank = self.handRank()
        else:
            handRank = order
        if self.player_list[0].folded == False and self.player_list[1].folded == False:
            if self.pot[0] > self.pot[1]:
                self.player_list[0].chips += self.pot[0] - self.pot[1]
                self.pot = [min(self.pot), min(self.pot)]
            elif self.pot[0] < self.pot[1]:
                self.player_list[1].chips += self.pot[1] - self.pot[0]
                self.pot = [min(self.pot), min(self.pot)]
        #print repr(handRank) + '\n'
        if len(handRank[0]) ==1:
            print "Player %s won %d chips" % (self.player_list[handRank[0][0]].name,self.pot[handRank[1][0]])
            self.player_list[handRank[0][0]].chips += sum(self.pot)
            winnings[handRank[0][0]] = self.pot[handRank[1][0]]
            print "Player %s lost %d chips" % (self.player_list[handRank[1][0]].name,self.pot[handRank[1][0]])
            #self.player_list[handRank[1][0]].chips -= self.pot[handRank[1][0]]
            winnings[handRank[1][0]] = -self.pot[handRank[1][0]]

        else:
            print "Player %s won %d chips" % (self.player_list[handRank[0][0]].name,0)
            print "Player %s won %d chips" % (self.player_list[handRank[0][1]].name,0)
            self.player_list[0].chips += self.pot[0]
            self.player_list[1].chips += self.pot[1]
        for i in range(2):
            print self.player_list[i].name + ': ' + str(self.player_list[i].chips)
        print "\n"
        for j,i in enumerate(self.player_list):
                i.end_round(self, winnings[j])

    # Starts one game of poker
    def play(self):
        t1 = time.time()

        # Gameplay is initilalized
        self.resetChips()
        # Position of dealer at the beginning
        dealer = 0
        for num_hand in range(self.num_hands):
            self.shuffleCards()
            self.pot = [0 for x in range(2)]
            self.table_chips = 0
            self.raise_counter = 0
            self.table = []
            self.strengths =[[], []]
            counter = 0
            for i in range(2):
                if self.player_list[i].chips > 0:
                    self.player_list[i].folded = False
                else:
                    self.player_list[i].folded = True
            if self.player_list[0].folded == True or self.player_list[1].folded == True:
                print "Game Over"
                for j,i in enumerate(self.player_list):
                    if isinstance(i, Bot):
                        i.end()
                break
            for j,i in enumerate(test.player_list):
                if isinstance(i, rl_bot.RLBot):
                    i.learner.round = 0
            print "Next Round"
            self.player_list = np.roll(self.player_list, 1)
            self.last_bets = np.roll(self.last_bets,1)
            # Round starts
            # People are dealt cards at the start of the round
            self.dealCards()

            # Small and Big blinds are put on the table
            print(self.player_list[(dealer + 1) % 2].name + " pays small blind of " + str(self.blinds[0]))
            self.player_list[(dealer + 1) % 2].chips -= self.blinds[0]
            self.pot[(dealer + 1) % 2] = self.blinds[0]
            print(self.player_list[dealer % 2].name + " pays big blind of " + str(self.blinds[1]))
            self.pot[dealer % 2] = min([self.player_list[dealer % 2].chips,self.blinds[1]])
            self.player_list[dealer % 2].chips -= min([self.player_list[dealer % 2].chips,self.blinds[1]])
            min_bet = self.blinds[1]
            self.bet_round = 0
            # Rounds of betting
            for j in range(4):
                raise_counter = -10
                raise_const = 1
                counter = 0
                if self.player_list[0].folded == True:
                    self.distribute_chips([[1],[0]])
                    break
                elif self.player_list[1].folded == True:
                    self.distribute_chips([[0],[1]])
                    break
                for i in range(2):
                    if self.player_list[i].chips > 0:
                        counter += 1
                while raise_counter != min_bet:
                    raise_counter = min_bet
                    for i in xrange(dealer + 1, dealer + 2 + raise_const):
                        if self.player_list[i % 2].folded == True or self.player_list[i % 2].chips == 0 or counter == 1:
                            continue
                        print("Current bet: " + str(min_bet))
                        self.player_list[i % 2].printName()

                        #track amount of time for player
                        t2 = time.time()
                        amount_bet = self.player_list[i % 2].bet(min_bet, self.pot[i % 2], self.times, self)
                        self.times[self.player_list[i % 2].name]['count'] += 1
                        self.times[self.player_list[i % 2].name]['total'] += time.time() - t2

                        self.last_bets[i % 2] = amount_bet
                        if self.player_list[0].folded == True or self.player_list[1].folded == True :
                            break
                        #still have to verify correct bet
                        self.pot[i % 2] += amount_bet
                        self.player_list[i%2].chips -= amount_bet
                        if min_bet < self.pot[i % 2]:
                            min_bet = self.pot[i % 2]
                            dealer = i
                            raise_const = 0
                            break
                self.bet_round += 1
                self.rounds()

            #distribute chips to winner(s)
            if self.player_list[0].folded == False and self.player_list[1].folded == False:
                self.distribute_chips()
            self.resetFolds()

        #update times
        self.times['main']['count'] += 1
        self.times['main']['total'] += time.time() - t1
Beispiel #33
0
class Table:
    def __init__(self, players_list):
        self.hand_idx = 0

        self.current_pot = 0
        self.current_bet = 0

        self.players = players_list

        self.total_chips = sum([p.stack for p in self.players])

        self.d_chip_pos = 0

        self.stage = None
        self.big_blind = 200
        self.small_blind = 100
        self.ante = 100

        self.deck = Deck()
        self.board = []

        self.reset_player_position_indexes()

        self.eval = Evaluator()

    ##
    # Deals two cards to each player
    ##
    def deal_hole_cards(self):
        for p in self.players:
            p.hand = self.deck.draw(2)
            p.hand = sorted(p.hand, reverse=False)

            if p.id == "HUMAN":
                print("Your hand: \t")
                Card.print_pretty_cards(p.hand)
                print("")


    def generate_table_state(self):
        table_state = {
        'stage': self.stage,
        'big_blind': self.big_blind,
        'small_blind': self.small_blind,
        'd_chip_pos': self.d_chip_pos,
        'board': self.board,
        'current_bet': self.current_bet, 
        }

        return table_state

    def reset_player_position_indexes(self):
        for idx, p in enumerate(self.players):
            p.playing_position = idx

    ##
    # Sets the hand rank for each player based
    # on the players current hand and board
    ##
    def evaluate_player_hands(self):
        for p in self.players:
            p.evaluate_hand(self.board, self.eval)

    ##
    # Returns the stack of each player
    ##
    def get_player_stacks(self):
        stacks = []

        for p in self.players:
            stacks.append(p.stack)

        return stacks

    def get_active_players(self):
        active_players = [p for p in self.players if p.active]
        return active_players


    def request_player_actions(self):
        self.current_bet = 0
        
        if len(self.get_active_players()) <= 1:
            no_further_action = True

        else:
            no_further_action = False

        stage_actions = []
        last_raiser = None

        while no_further_action is False:
            round_actions = []

            no_further_action = False
            for p in self.get_active_players():
                if p.all_in:
                    no_further_action = True

            if no_further_action:
                continue

            for p in self.get_active_players():
                if p == last_raiser:
                    no_further_action = True
                    break

                if len(self.get_active_players()) == 1:
                    no_further_action = True
                    break

                if p.all_in:
                    continue

                if p.active:
                    player_action = p.get_action(self, self, round_actions)
                    self.current_pot += player_action[2]

                    if human_player:
                        print(p.id, player_action[1], player_action[2])

                    if player_action[2] > self.current_bet:
                        self.current_bet = player_action[2]

                    if player_action[1] == "RAISE":
                        last_raiser = p

                    round_actions.append(player_action)

            stage_actions.append(round_actions)

            if last_raiser == None:
                no_further_action = True

        for p in self.get_active_players():
            p.hand_actions += stage_actions

        if debug == "SHOW_ACTIONS":
            if len(stage_actions) > 2:
                print(stage_actions)
                print(len(stage_actions))
                exit()


    def take_blinds_and_ante(self):
        ## TODO check success of taking blinds

        # Take small blind
        self.players[0].stack -= self.small_blind
        self.current_pot += self.small_blind
        self.players[0].contribution_to_pot += self.small_blind

        # Take big blind
        self.players[1].stack -= self.big_blind
        self.current_pot += self.big_blind
        self.players[1].contribution_to_pot += self.big_blind

        if human_player:
            print(self.players[0].id, "Small blind: ", self.small_blind)
            print(self.players[1].id, "Big blind: ", self.big_blind)
            print("")


        # Take ante
        for p in self.players:
            p.stack  -= self.ante
            self.current_pot += self.ante
            p.contribution_to_pot += self.ante


    ##
    # Returns a list of winners from active players
    # and the current board.
    ##
    def identify_winners(self, players):
        best_rank = 7463  # rank one worse than worst hand
        winners = []

        for p in players:
            p_rank = self.eval.evaluate(p.hand, self.board)

            if p_rank == best_rank:
                winners.append(p)

            elif p_rank < best_rank:
                best_rank = p_rank
                winners = [p]

        return winners
    
    def redistribute_pot(self):
        # Sort players by their contribution to the pot
        all_players = sorted(self.players, key=lambda p:p.contribution_to_pot, reverse=False)

        making_side_pots = True
        pots = []

        for p_1 in all_players:
            this_pot_val = 0
            this_pot_players = []

            player_contrib = p_1.contribution_to_pot

            # Subtract the player contribution for all players if balance > 0
            for p_2 in all_players:
                if p_2.contribution_to_pot > 0:
                    p_2.contribution_to_pot -= player_contrib
                    this_pot_val += player_contrib
                    this_pot_players.append(p_2)

            # Add pot
            if this_pot_val > 0:
                pots.append([this_pot_val, this_pot_players])

        # For each pot compare the hands of active players to identify the winner
        active_players = self.get_active_players()

        # For each pot compare the hands of active players to identify the winner
        for pot in pots:
            pot_members = pot[1]
            active_pot_members = [p for p in pot_members if p in active_players]

            pot_winners = []

            # No active winners
            if len(active_pot_members) == 0:
                pot_winners = pot_members

            # Find the winners in the pot
            else:
                pot_winners = self.identify_winners(active_pot_members)


            # Split pot equally beween the winners
            distributed_pot_val = pot[0] / len(pot_winners)

            for winner in pot_winners:
                winner.stack += distributed_pot_val


    ##
    # Resets the table and moves dealerchip to the left by one position.
    # 
    ##
    def prepare_next_hand(self, update_action_data=False):
        self.board = []
        self.current_pot = 0

        # Reorder players by moving first to back
        player_0 = self.players[0]
        self.players.pop(0)
        self.players.append(player_0)
        self.reset_player_position_indexes()

        # Set players with no stack to inactive
        for p in self.players:
            if p.stack <= 0:
                p.active = False

            else:
                p.active = True

        # self.players = [p for p in self.players if p.active]

        # Remove player hole cards
        for p in self.players:
            if update_action_data:
                p.update_action_data_net_stack(self.hand_idx)
                
            p.hand = None
            p.stage_actions = []
            p.hand_actions = []
            p.prev_stack = p.stack
            p.all_in = False
            # p.hand_action_count = 0

        # Reset the deck
        self.deck = Deck()
        self.hand_idx += 1


    def play_single_hand(self):
        stages = ['PREFLOP', 'FLOP', 'TURN', 'RIVER']

        ## Preflop
        self.stage = stages[0]
        self.deal_hole_cards()
        self.take_blinds_and_ante()
        self.request_player_actions()

        if human_player:
            print(self.stage, "POT: ", self.current_pot)
            print("")
            Card.print_pretty_cards(self.board)

        ## Flop
        self.stage = stages[1]
        self.board += self.deck.draw(3)
        self.request_player_actions()

        if human_player:
            print(self.stage, "POT: ", self.current_pot)
            print("")
            Card.print_pretty_cards(self.board)

        # River
        self.stage = stages[2]
        self.board += [self.deck.draw(1)]
        self.request_player_actions()

        if human_player:
            print(self.stage, "POT: ", self.current_pot)
            print("")
            Card.print_pretty_cards(self.board)

        # Turn
        self.stage = stages[3]
        self.board += [self.deck.draw(1)]
        self.request_player_actions()
        
        if human_player:
            print(self.stage, "POT: ", self.current_pot)
            print("")
            Card.print_pretty_cards(self.board)

        # self.players[0].display_game_state(self, [])
        # Cleanup by allocating chips to winner
        self.redistribute_pot()
Beispiel #34
0
from __future__ import division
import numpy
from deuces import Card, Evaluator, Deck
import itertools
import pickle

evaluator = Evaluator()
pre_flop = pickle.load(open("preflop_scores.p", "rb"))

for i in range(0, 1000000):
    deck = Deck()
    board = deck.draw(5)
    player1_hand = deck.draw(2)
    player2_hand = deck.draw(2)
    player1_hand.sort()

    p1_score = evaluator.evaluate(board, player1_hand)
    p2_score = evaluator.evaluate(board, player2_hand)
    key = tuple(player1_hand)

    if key not in pre_flop:
        pre_flop[key] = [0, 0]

    if p1_score < p2_score:
        pre_flop[key] = [pre_flop[key][0] + 1, pre_flop[key][1] + 1]
    elif p2_score < p1_score:
        pre_flop[key][1] += 1
    else:
        pre_flop[key] = [pre_flop[key][0] + 1, pre_flop[key][1] + 2]

# for key in pre_flop:
Beispiel #35
0
deck.save()

for i in range(0, 10000):
    deck.reset()
    players = []
    players.append(first_player)
    for player_id in range(1, num_players, 1):
        player = Player(player_id, deck=deck)
        card_ints = player.draw_cards(num=2)
        players.append(player)
    flop_card_ints = deck.flop()
    # print("Flops: " + Card.format_pretty_cards(flop_card_ints))
    # print("Total left cards in deck: %d" % deck.left_card_num())

    flop_card_ints = deck.get_flop_card_ints()
    turn_card_int = deck.draw()
    flop_card_ints.append(turn_card_int)
    river_card_int = deck.draw()
    flop_card_ints.append(river_card_int)
    # evaluator.hand_summary(board=flop_card_ints, hands=[player.cards for player in players])
    hands = [player.cards for player in players]
    winner_method, winner_player = evaluator.hand_evaluate(
        board=flop_card_ints, players=players, debug=False)
    method_count = winner_methods.get(winner_method, 0)
    winner_methods[winner_method] = method_count + 1
    player_count = winner_players.get(winner_player.name, 0)
    winner_players[winner_player.name] = player_count + 1

print("\n=== End Simulation ===")
# print(winner_methods)
# print(winner_players)
Beispiel #36
0
    #constructin the whole deck
    deck = Deck()
    
    
    #Card.print_pretty_cards(player1_hand)
    
    
    #removing our own hand from the deck
    deck.cards.remove(hand[0])
    deck.cards.remove(hand[1])
    
    
    d = {}
    for j in range(opp):
        #giving a random player random cards
        d['player%s_hand'%j] = deck.draw(2)
        
    #Card.print_pretty_cards(d['player2_hand'])
   
    #Card.print_pretty_cards(d['player3_hand'])
    
    
    board = deck.draw(5)
    #Card.print_pretty_cards(board)
    
    
    #how strong are the hands from our opponents
    e = {}
    for k in range(opp):
        e['p%s_score'%k] = evaluator.evaluate(board, d['player%s_hand'%k])
#        p1_score = evaluator.evaluate(board, player1_hand)
 _=os.system("clear")
 print "Let's play a poker hand!"
 print "\nOK here are the teams and their starting chips:"
 print "\n%s TEAM has %d chips" % (team1, team1chips)
 print "%s TEAM has %d chips" % (team2, team2chips)
 print "%s TEAM has %d chips" % (team3, team3chips)
 print "%s TEAM has %d chips" % (team4, team4chips)
 print "\nWow nice chips!"
 # new deck
 deck = Deck()
 deck.shuffle()
 evaluator = Evaluator()
 print "\nFirst we deal 2 cards to each team..."
 ans3 = raw_input("\nHit <enter> to see the hands: ")
 # random board and hands
 hand1 = deck.draw(2)
 hand2 = deck.draw(2)
 hand3 = deck.draw(2)
 hand4 = deck.draw(2)
 leftovers = deck.draw(44)
 # print the hands
 _=os.system("clear")
 print "%s TEAM has hand " % team1
 Card.print_pretty_cards(hand1)
 print "\n%s TEAM has hand " % team2
 Card.print_pretty_cards(hand2)
 print "\n%s TEAM has hand " % team3
 Card.print_pretty_cards(hand3)
 print "\n%s TEAM has hand " % team4
 Card.print_pretty_cards(hand4)
 print "\nWow nice hands!"
Beispiel #38
0
import deuces
from deuces import Card
from deuces import Evaluator
from deuces import Deck

deck=Deck()
board=deck.draw(5)

class Player:
    hand_value = 0
    account_value = 0
    score = 0
    rank =  0

def card_allocation_module(no_of_players):
    print "\nReceived input is : ", no_of_Players
    return [0]

no_of_Players= raw_input("Enter your input: ");

player=[Player() for i in range(int(no_of_Players))]

for i in range(int(no_of_Players)):
    player[i].hand_value=deck.draw(2)
    Card.print_pretty_cards(player[i].hand_value)
   
##for i in range(int(no_of_Players)):
##    print "\nplayer[",i,"].hand_value=",player[i].hand_value
##    print "player[",i,"].account_value=",player[i].account_value
##    print "player[",i,"].score=",player[i].score
Beispiel #39
0
]

# pretty print cards to console
Card.print_pretty_cards(board + hand)

# create an evaluator
evaluator = Evaluator()

# and rank your hand
rank = evaluator.evaluate(board, hand)
print("Rank for your hand is: %d" % rank)

# or for random cards or games, create a deck
print("Dealing a new hand...")
deck = Deck()
board = deck.draw(5)
player1_hand = deck.draw(2)
player2_hand = deck.draw(2)

print("The board:")
Card.print_pretty_cards(board)

print("Player 1's cards:")
Card.print_pretty_cards(player1_hand)

print("Player 2's cards:")
Card.print_pretty_cards(player2_hand)

p1_score = evaluator.evaluate(board, player1_hand)
p2_score = evaluator.evaluate(board, player2_hand)
class Game:

    version = 0.0

    def __init__(self, n_players):
        self.deck = Deck()
        self.hands = [
            list(x)
            for x in zip(self.deck.draw(n_players), self.deck.draw(n_players))
        ]
        self.board = []

        self.n_players = n_players

        self.bets = np.zeros(n_players) + 10
        self.money = np.ones(n_players) * 90

        self.ins = np.ones(n_players).astype(bool)
        self.all_ins = np.zeros(n_players).astype(bool)

        self.round = 0

    def next_round(self, decision_algorithm):
        """Generating a round, using the decision algorithm to make the bets
            (Nothing to adapt here)"""

        # card increment based on which round we are in
        if self.round == 0:
            pass
        elif self.round == 1:
            self.board += self.deck.draw(3)
        elif self.round == 2:
            self.board += [self.deck.draw(1)]
        elif self.round == 3:
            self.board += [self.deck.draw(1)]
        elif self.round > 3:
            return

        # extracting features to feed to the decision algorithm

        features = self.__get_features()

        # applying the decision algorithm
        decisions = [
            decision_algorithm(f) if is_in else None
            for f, is_in in zip(features, self.ins)
        ]

        # applying the decision (to adapt to the format of the decision output)
        self.__update_game(decisions)

        # if the game is at the end, we attribute the gains
        if self.round == 3:
            self.__finalize_game()

        # updating the round number
        self.round += 1

    def __update_game(self, decisions: list):
        """
        applying the decision from the algorithm to the game state
        (Nothing to adapt here)
        :param decisions: list, output from the decision algorithm
        :return:
        """

        # updating who folded
        self.__fold(decisions)
        # deciding on a raise value based on the decision ouptut
        raise_value = self.__raise_value(decisions)
        # checking who goes all in and updating the bets
        all_ins = (self.money <= raise_value) & self.ins
        self.bets[all_ins] += self.money[all_ins]
        self.money[all_ins] = 0.
        # removing all ins pplayer from the pool
        self.all_ins |= all_ins
        self.ins &= ~self.all_ins
        # updating the bets for the other players
        self.bets[self.ins] += raise_value
        self.money[self.ins] -= raise_value

    def __finalize_game(self):
        """
        Giving all the money to the player with the best hand
        (Nothing to adapt here)
        :return:
        """

        evaluator = Evaluator()
        hand_strength = np.array(
            [evaluator.evaluate(hand, self.board) for hand in self.hands])

        if any(~(self.all_ins | self.ins)):
            hand_strength[~(self.all_ins | self.ins)] = np.nan

        if any(self.all_ins | self.ins):
            winner = np.nanargmin(hand_strength)
            # computing how much money the winner is getting from the others
            money_transfer = np.min(
                [self.bets, [self.bets[winner]] * self.n_players], axis=0)
            self.money[winner] += np.sum(money_transfer)
            self.bets = self.bets - money_transfer

        # redistributing what hasn't been won to the players
        self.money += self.bets
        self.bets *= 0

    def __get_features(self):
        """
        Creating the features for the decision algorithm
        (to be adapted in development)
        :return:
        """

        feature_dict = {}

        feature_dict['player'] = list(np.arange(self.n_players))

        feature_dict['winning_proba'] = [
            estimate_proba(hand, self.board, self.n_players, n_simul=100)
            for hand in self.hands
        ]

        feature_dict['money_to_gain'] = [sum(self.bets)] * self.n_players

        for round in range(4):
            feature_dict[f'round {round}'] = [round == self.round
                                              ] * self.n_players

        return feature_dict

    def __raise_value(self, decisions: list) -> float:
        """
        Implementation on how to decide the raise value based on the decision output
        (to be adapted in development)
        :param decisions:
        :return:
        """

        return np.max(np.min([decisions, self.money], axis=0))

    def __fold(self, decisions: list):
        """
        Implementation of how to decide if a player folds based on the decision output
        (to be adapted in development)
        :param decision: output of the decision algorithm
        """

        return np.array(decisions) < 0

    def display(self):
        for i in range(self.n_players):

            if self.ins[i]:
                status = "in"
            elif self.all_ins[i]:
                status = "all in"
            else:
                status = "out"

            print("player %d: \t Money: %d \t Bets: %d \t Status: %s " %
                  (i, self.money[i], self.bets[i], status))

            Card.print_pretty_cards(self.hands[i])

        print("board:")
        Card.print_pretty_cards(self.board)