示例#1
0
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
示例#2
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
示例#3
0
    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
示例#4
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
示例#5
0
	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()
示例#6
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
    def test_draws_are_consistent(self):
        random.seed(0)
        hand = [Deck() for _ in range(5)]
        df_all = pd.DataFrame({'all': [deck.draw(9) for deck in hand]})
        expected = [[[
            81922, 33560861, 139523, 16783383, 147715, 69634, 164099, 1053707,
            16795671
        ]],
                    [[
                        16783383, 4212241, 295429, 69634, 81922, 73730,
                        134236965, 8394515, 557831
                    ]],
                    [[
                        266757, 1082379, 134236965, 557831, 16787479, 67127839,
                        529159, 134253349, 1053707
                    ]],
                    [[
                        33564957, 8423187, 1065995, 33589533, 98306, 268471337,
                        2114829, 16812055, 67119647
                    ]],
                    [[
                        16795671, 529159, 135427, 16783383, 266757, 2106637,
                        279045, 8423187, 8394515
                    ]]]
        self.assertEqual(df_all.values.tolist(), expected)

        random.seed(0)
        hand = [Deck() for _ in range(5)]
        df_board = pd.DataFrame({'board': [deck.draw(5) for deck in hand]})
        expected = [[[81922, 33560861, 139523, 16783383, 147715]],
                    [[16783383, 4212241, 295429, 69634, 81922]],
                    [[266757, 1082379, 134236965, 557831, 16787479]],
                    [[33564957, 8423187, 1065995, 33589533, 98306]],
                    [[16795671, 529159, 135427, 16783383, 266757]]]
        self.assertEqual(df_board.values.tolist(), expected)
    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
示例#9
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)
示例#10
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
示例#11
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
示例#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
示例#13
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
示例#14
0
    def build(self, testMode=True):
        """
        Initiate objects and views.
        """
        ''' init game objects '''
        self.deck = Deck()
        self.evaluator = Evaluator()

        self.player = []
        self.player.append(Player(0))
        self.player.append(Player(1))
        # board stands for public cards on board
        self.board = Board()

        # In test mode, both player select right-most cards for the turn automatically
        self.testMode = testMode
        ''' create view objects '''
        # Scatter that can be rotated to display players
        scatter_bot = ScatterLayout(do_rotation=False,
                                    do_translation=False,
                                    do_scale=False,
                                    size_hint=(1, 1),
                                    pos_hint={
                                        'x': 0,
                                        'y': 0
                                    },
                                    rotation=0)
        # For player on top, the widget rotates 180 degree
        scatter_top = ScatterLayout(do_rotation=False,
                                    do_translation=False,
                                    do_scale=False,
                                    size_hint=(1, 1),
                                    pos_hint={
                                        'x': 0,
                                        'y': 0
                                    },
                                    rotation=180)

        box = PlayerDeck()
        box2 = PlayerDeck()
        publicArea = PublicArea()
        box.build(self, "player1", 0, self.testMode)
        box2.build(self, "player2", 1, self.testMode)
        publicArea.build()

        scatter_bot.add_widget(box)
        scatter_top.add_widget(box2)

        self.add_widget(scatter_bot)
        self.add_widget(scatter_top)
        self.add_widget(publicArea)

        # register id of view objects
        self.ids[box.id] = box
        self.ids[box2.id] = box2
        self.ids[publicArea.id] = publicArea
示例#15
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 ]
示例#16
0
 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 =[[], []]
示例#17
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
示例#18
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
示例#19
0
def build_dataframe(nb_hands=100, nb_players=2):
    decks = [Deck() for _ in range(nb_hands)]

    df_board = pd.DataFrame({'board': [deck.draw(5) for deck in decks]})

    df_players = pd.concat([
        pd.DataFrame({'player': [deck.draw(2) for deck in decks]})
        for _ in range(nb_players)
    ],
                           axis=1,
                           keys=range(nb_players))
    df_players = df_players.swaplevel(0, 1, axis=1)

    evaluator = Evaluator()
    df_scores = pd.concat([
        df_board.join(df_players.xs(i, level=1, axis=1)).apply(
            lambda x: evaluator.evaluate(x['board'], x['player']),
            axis=1).to_frame('score')
        for i in df_players.columns.get_level_values(1)
    ],
                          axis=1,
                          keys=df_players.columns.get_level_values(1))
    df_scores = df_scores.swaplevel(0, 1, axis=1)

    return df_board, df_players, df_scores
示例#20
0
文件: game.py 项目: hencic00/Poker
    def __init__(self, lobby, minBetInit, startingCash, minRaiseInit):
        self.lobby = lobby
        self.startingCash = startingCash
        self.roundObject = None
        self.cardRankLUT = dict()
        self.cardRankLUT = {
            0: '2',
            1: '3',
            2: '4',
            3: '5',
            4: '6',
            5: '7',
            6: '8',
            7: '9',
            9: 'J',
            8: 'T',
            10: 'Q',
            11: 'K',
            12: 'A'
        }

        self.cardSuitLUT = dict()
        self.cardSuitLUT = {1: 's', 2: 'h', 4: 'd', 8: 'c'}

        self.roundCounter = 0
        self.players = []
        self.endGameUsers = []

        self.unshuffledDeck = Deck()
        self.currentPlayerIndex = 0
        self.minBet = minBetInit
        self.minRaise = minRaiseInit
示例#21
0
文件: hand.py 项目: pashadia/treys
 def rest_of_the_deck(self):
     """Return a list with the rest of the cards in the deck."""
     full_deck = Deck.GetFullDeck()
     return [
         elem for elem in full_deck
         if elem not in (self._cards + self._board._cards)
     ]
示例#22
0
 def __init__(self, bot, name='kiwi'):
     self.players = []
     self.name = name
     self.deck = Deck()
     self.visible_cards = []
     self.bot = bot
     self.potpies = 0
示例#23
0
 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])
示例#24
0
文件: Round.py 项目: hencic00/Poker
	def __init__(self, gameObject):
		self.pot = 0
		self.sidePot = 0
		self.currentMinBet = gameObject.minBet
		self.roundPlayers = gameObject.players
		self.playerStatus = []
		self.playerHandScores = []
		self.playerHandClasses = []
		self.board = []
		self.deck = Deck()
		#self.deck = random.sample(gameObject.unshuffledDeck, 52)    #deck shuffle -> uporablja Fisher-Yates O(n)
	 
		for p in self.roundPlayers: #empty player hands
			p.hand = []
			p.currentBet=0
			self.allIn=False
			self.allInDifference=0
示例#25
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
示例#26
0
 def __init__(self, numPlayers, maxRaise, deck=False):
     self.numPlayers = numPlayers
     self.maxRaise = maxRaise + 1
     if deck:
         self.deck = deck
     else:
         self.deck = Deck()
     self.boardLength = 5
示例#27
0
 def setUp(self) -> None:
     self.players = [
         Player(handle=f"p{n}", hand=Hand([])) for n in range(1, 5)
     ]
     self.game = Game(little_ante=25,
                      big_ante=50,
                      players=self.players,
                      deck=Deck())
     self.game_service = GameService(game=self.game)
示例#28
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
示例#29
0
def generate(mdp, state, action):
    cardsInUse = []
    for player in state['players']:
        hand = player[0]
        if not hand:
            continue
        for card in hand:
            cardsInUse.append(card)
    for card in state['board']:
        cardsInUse.append(card)

    fullDeck = Deck().GetFullDeck()
    deck = [card for card in fullDeck if card not in cardsInUse]

    random.shuffle(deck)

    #Update state based on action
    rewards = mdp.getRewards(state, action)
    if action == -1:
        #Player folded, set their hand to False
        state['players'][state['curPlayer']] = (
            False, state['players'][state['curPlayer']][1])
    else:
        #Add players action to their running total bet
        if (state['players'][state['curPlayer']][1] == False):
            newPlayerBet = action  #if current bet is False
        else:
            newPlayerBet = state['players'][state['curPlayer']][1] + action
        state['players'][state['curPlayer']] = (
            state['players'][state['curPlayer']][0], newPlayerBet)
        #Total bet for the round is equal to the player's total running bet
        state['curBet'] = newPlayerBet
        #Add the players bet to the pot
        state['pot'] += action

    if mdp.roundIsOver(state):

        if len(state['board']) == 0:
            #Flop
            newcards = [deck.pop(0) for _ in range(3)]
            state['board'] = state['board'] + newcards
        else:
            #Turn or River or End of round
            state['board'] = state['board'] + [deck.pop(0)]
        #Reset current bet for the round
        state['curBet'] = 0
        #Rotate starting bet
        state['curPlayer'] = mdp.getStartingPlayer(state)

        # Reset player bets for all players
        for i, player in enumerate(state['players']):
            state['players'][i] = (state['players'][i][0], False)
    else:
        state['curPlayer'] += 1
        state['curPlayer'] %= mdp.numPlayers

    return state, rewards
示例#30
0
def deal_cards(nb_players=2):
    all_cards = [ Deck().draw(5 + 2*nb_players) for x in range(1000) ]
    df = pd.DataFrame({'all': all_cards})
    df['board'] = df['all'].apply(lambda x: x[:5])
    for i in range(nb_players):
        i_start = 5 + 2*i
        i_end = i_start + 2
        df['player{0}'.format(i+1)] = df['all'].apply(lambda x: list(islice(x, i_start, i_end)))
    del df['all']
    return df
示例#31
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
 def test_board(self):
     random.seed(0)
     hand = [Deck() for _ in range(5)]
     df_board = pd.DataFrame({'board': [deck.draw(5) for deck in hand]})
     expected = [[[81922, 33560861, 139523, 16783383, 147715]],
                 [[16783383, 4212241, 295429, 69634, 81922]],
                 [[266757, 1082379, 134236965, 557831, 16787479]],
                 [[33564957, 8423187, 1065995, 33589533, 98306]],
                 [[16795671, 529159, 135427, 16783383, 266757]]]
     self.assertEqual(df_board.values.tolist(), expected)
示例#33
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 build_dataframe(nb_hands=1000):
    decks = [Deck() for _ in range(nb_hands)]
    boards = [deck.draw(5) for deck in decks]
    player1 = [deck.draw(2) for deck in decks]
    player2 = [deck.draw(2) for deck in decks]

    e = Evaluator()
    score1 = [e.evaluate(b, h) for (b, h) in zip(boards, player1)]
    score2 = [e.evaluate(b, h) for (b, h) in zip(boards, player2)]

    return pd.DataFrame({'score1': score1, 'score2': score2})
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)