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)
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 getHandStrength(self): evaluator = Evaluator() score = evaluator.evaluate( [Card.new(str(self.hand[0])), Card.new(str(self.hand[1]))], [Card.new('Td'), Card.new('4c'), Card.new('9s')]) rank = evaluator.get_rank_class(score) print "Score:", score, "Percentile:", round( 1 - float(score) / float(7254), 2), "Class:", evaluator.class_to_string(rank)
def ai_action(data, debug=False): rank, s_player, round_count = get_player(data) table_card, self_card = get_card(data) betCount = get_betCount(data) min_bet = get_minBet(data) print "Survive player : {n}".format(n=s_player) print "Sparrow ranking: {n}".format(n=rank) print "Total BetCount : {n}".format(n=betCount) print "min_bet : {n}".format(n=min_bet) gamma = 0 beta = 0 alpha = 0 if rank < 3: alpha = -1200 gamma = -1000 ''' if round_count > 5 and rank > 5: gamma += 1000 beta += 1000 if rank > 7: beta += 500 ''' if min_bet > 200: gamma += -500 beta += -500 if min_bet > 400: gamma += -1000 beta += -500 if len(table_card + self_card) >= 5: evaluator = Evaluator() pscore = evaluator.evaluate(table_card, self_card) pclass = evaluator.get_rank_class(pscore) print "Sparrow hand rank = %d (%s)\n" % ( pscore, evaluator.class_to_string(pclass)) if pscore > 6000 + beta: return "fold" elif pscore > 4000 + gamma: return "call" elif pscore > 2000 + alpha: return "raise" else: return "allin" elif round_count < 10 and min_bet > 300: return "fold" else: return "call"
def __str__(self): result = "\n\n ############## Population %d ##############\n" %(self.number) bestResult = 0 evaluator = Evaluator() for player_hand in self.population: result += str(player_hand) + "\n" currentResult = evaluator._five(player_hand.hand) if (currentResult > bestResult): bestResult = currentResult p_class = evaluator.get_rank_class(bestResult) result += "\n Best solution: %s " %(evaluator.class_to_string(p_class)) return result
def evaluate_hands(self): agent_hands = [] if self.in_game_count > 1: evaluator = Evaluator() board = [] scores = [] hand_types = [] for c in self.community_cards: board.append(Card.new(c)) for i in range(0, len(self.agents)): agent = self.agents[i] agent_hand = [] for c in agent.hand: agent_hand.append(Card.new(c)) if self.in_game[i]: agent_hands.append(agent.hand) agent_score = evaluator.evaluate(board, agent_hand) agent_hand_type = evaluator.class_to_string(evaluator.get_rank_class(agent_score)) scores.append(agent_score) hand_types.append(agent_hand_type) else: agent_hands += [None] scores.append(9999999999999) lowest_rank = scores[0] winner = 0 for i in range(0, len(self.agents)): if lowest_rank > scores[i]: lowest_rank = scores[i] winner = i return (winner, agent_hands) else: # Only 1 remaining player winner = 0 for i in range(0, len(self.agents)): if (self.in_game[i]): winner = i break return winner, agent_hands
def display_game_state(self, table, round_actions): evaluator = Evaluator() if len(table.board) > 0: p_score = evaluator.evaluate(table.board, self.hand) p_class = evaluator.get_rank_class(p_score) p_string = evaluator.class_to_string(p_class) else: p_string = "" os.system('clear') print(round_actions) print("") print("Pot: ", table.current_pot) print("Board: ", end="") Card.print_pretty_cards(table.board) print("") print("Your hand: ", end="") Card.print_pretty_cards(self.hand) print("%s \n" % (p_string)) print("Your stack: %d" % self.stack) print("") print("Current bet: ", table.current_bet)
# 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) # bin the scores into classes p1_class = evaluator.get_rank_class(p1_score) p2_class = evaluator.get_rank_class(p2_score) # or get a human-friendly string to describe the score print "Player 1 hand rank = %d (%s)" % (p1_score, evaluator.class_to_string(p1_class)) print "Player 2 hand rank = %d (%s)" % (p2_score, evaluator.class_to_string(p2_class)) # or just a summary of the entire hand hands = [player1_hand, player2_hand] evaluator.hand_summary(board, hands)
from deuces import Card from deuces import Evaluator # table cards board = [Card.new('Ad'), Card.new('Kd'), Card.new('Jd')] # self cards hand = [Card.new('Qd'), Card.new('Td')] # evaluate, can only evaluate 5 cards evaluator = Evaluator() score = evaluator.evaluate(board, hand) rank_class = evaluator.get_rank_class(score) print(rank_class) rank_class_str = evaluator.class_to_string(rank_class) print(rank_class_str) # for score # Hand strength is valued on a scale of 1 to 7462, # where 1 is a Royal Flush and 7462 is unsuited 7-5-4-3-2, # as there are only 7642 distinctly ranked hands in poker # for rank_class # 1-9 # 9, High Card # 8, Pair # 7, Two Pair # 5, Straight # 1, Straight Flush
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
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 card_allocation_module(no_of_Players) print "\n" ##player[0].hand_value=deck.draw(2) ##player[1].hand_value=deck.draw(2) Card.print_pretty_cards(board) ##Card.print_pretty_cards(player[0].hand_value) ##Card.print_pretty_cards(player[1].hand_value) print "\n" evaluator = Evaluator() for i in range(int(no_of_Players)): player[i].score = evaluator.evaluate(board, player[i].hand_value) player[i].rank = evaluator.get_rank_class(player[i].score) for i in range(int(no_of_Players)): print "Player ", i, " hand rank = %d (%s)\n" % ( player[i].score, evaluator.class_to_string(player[i].rank)) ##print "Player 2 hand rank = %d (%s)\n" % (player[1].score, evaluator.class_to_string(player[1].rank)) hands = [player[i].hand_value for i in range(int(no_of_Players))] evaluator.hand_summary(board, hands)
def main(img): path = os.path.dirname(os.path.abspath(__file__)) path = path[0: len(path)-4] train_ranks = Cards.load_ranks(path + "/card_images/") train_suits = Cards.load_suits(path + "/card_images/") image = cv2.imread(img, 1) image = Cards.resize_image(image) pre_proc = Cards.preprocess_image(image) cnts_sort, cnt_is_card = Cards.find_cards(pre_proc) # ako ne nadje konture, ne radi nista if len(cnts_sort) != 0: # inicijalizujemo praznu listu karata # k predstavlja indeks liste cards = [] k = 0 for i in range(len(cnts_sort)): if (cnt_is_card[i] == 1): # kreira card objekat od konture i dodaje ga u listu karata # pronalazi konturu sa brojem i znakom karte cards.append(Cards.preprocess_card(cnts_sort[i], image)) # pronalazi najbolji odgovarajuci broj i znak cards[k].best_rank_match, cards[k].best_suit_match, cards[k].rank_diff, cards[ k].suit_diff = Cards.match_card(cards[k], train_ranks, train_suits) # crta centar karte i rezultat image = Cards.draw_results(image, cards[k]) k = k + 1 centers = [] # crta konture karata na slici if (len(cards) != 0): temp_cnts = [] for i in range(len(cards)): temp_cnts.append(cards[i].contour) M = cv2.moments(cards[i].contour) cX = int(M["m10"] / M["m00"]) cY = int(M["m01"] / M["m00"]) centers.append([cX, cY]) cv2.drawContours(image, temp_cnts, -1, (255, 0, 0), 2) # klasterujemo centre karata u tri grupe: prvi igrac, drugi igrac, karte na stolu X = np.array(centers) clustering = DBSCAN(eps=350, min_samples=1).fit(X) groups = {0: [], 1: [], 2: []} for card, label in zip(cards, clustering.labels_): groups[label].append(card) # pravimo prazne liste u koje dodajemo deuces.Card objekte pomocu kojih racunamo snagu ruke oba igraca board = [] player1 = [] player2 = [] for board_card in groups[1]: board.append(deuces.Card.new(Cards.convert_name(board_card))) for board_card in groups[0]: player1.append(deuces.Card.new(Cards.convert_name(board_card))) for board_card in groups[2]: player2.append(deuces.Card.new(Cards.convert_name(board_card))) # pomocu deuces.Evaluator racunamo i poredimo snage ruku # stampamo obe ruke evaluator = Evaluator() player1_score = evaluator.evaluate(board, player1) player2_score = evaluator.evaluate(board, player2) print("Player 1: ", evaluator.class_to_string(evaluator.get_rank_class(player1_score))) print(groups[0][0].best_rank_match + " of " + groups[0][0].best_suit_match, ", ", groups[0][1].best_rank_match + " of " + groups[0][1].best_suit_match) print("Player 2: ", evaluator.class_to_string(evaluator.get_rank_class(player2_score))) print(groups[2][0].best_rank_match + " of " + groups[2][0].best_suit_match, ", ", groups[2][1].best_rank_match + " of " + groups[2][1].best_suit_match) if player1_score == player2_score: print("Draw") elif player1_score < player2_score: print("Player 1 wins") else: print("Player 2 wins") cv2.imshow('image', image) cv2.waitKey(0) cv2.destroyAllWindows()
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 card_allocation_module(no_of_Players) print "\n" ##player[0].hand_value=deck.draw(2) ##player[1].hand_value=deck.draw(2) Card.print_pretty_cards(board) ##Card.print_pretty_cards(player[0].hand_value) ##Card.print_pretty_cards(player[1].hand_value) print "\n" evaluator=Evaluator() for i in range(int(no_of_Players)): player[i].score=evaluator.evaluate(board,player[i].hand_value) player[i].rank=evaluator.get_rank_class(player[i].score) for i in range(int(no_of_Players)): print "Player ",i," hand rank = %d (%s)\n" % (player[i].score, evaluator.class_to_string(player[i].rank)) ##print "Player 2 hand rank = %d (%s)\n" % (player[1].score, evaluator.class_to_string(player[1].rank)) hands = [player[i].hand_value for i in range(int(no_of_Players))] evaluator.hand_summary(board, hands)
# Print board and hands print("\n") print("board:") Card.print_pretty_cards(board) # Player 1 print("\n") print("player 1:") Card.print_pretty_cards(player1_hand) # Evaluate hands p1_score = evaluator.evaluate(board, player1_hand) print("\n") print("score:") print(p1_score) # bin into classes by rank p1_class = evaluator.get_rank_class(p1_score) print("\n") print("class:") print(p1_class) print("\n") # Player 2 print("\n") print("player 2:") Card.print_pretty_cards(player2_hand) # Evaluate hands p2_score = evaluator.evaluate(board, player2_hand) print p2_score # bin into classes by rank p2_class = evaluator.get_rank_class(p2_score) print("\n") print("class:")
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 df = deal_cards() evaluator = Evaluator() df['score1'] = df.apply(lambda x: evaluator.evaluate(x['board'], x['player1']), axis=1) df['score2'] = df.apply(lambda x: evaluator.evaluate(x['board'], x['player2']), axis=1) df['class1'] = df['score1'].apply(lambda x: evaluator.get_rank_class(x)) df['class2'] = df['score2'].apply(lambda x: evaluator.get_rank_class(x)) df['class1_string'] = df['class1'].apply(lambda x: evaluator.class_to_string(x)) df['class2_string'] = df['class2'].apply(lambda x: evaluator.class_to_string(x)) def who_won(x, y): if x == y: return 0 if x < y: return 1 return 2 df['winner'] = df.apply(lambda x: who_won(x['score1'], x['score2']), axis=1) # Was the game fair?
class Game(GameFlow, FloatLayout): # give the type of game to a self-created type inheritence from both "FloatLayout" and "ABCMeta" __metaclass__ = type('GameMeta', (type(FloatLayout), ABCMeta), {}) id = "root" turn = 1 round = 1 def round_reset(self): """ At the end of round, update data and views """ self.turn = 1 self.round += 1 self.deck.shuffle() self.board.round_reset() self.player[0].round_reset() self.player[1].round_reset() self.ids.publicArea.round_reset(self.round) self.ids.player1_box.round_reset() self.ids.player2_box.round_reset() 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 def round_play(self): """ A game round starts here. """ #self.round_reset() # draw cards for players and board self.player[0].hand = self.deck.draw(5) self.player[1].hand = self.deck.draw(5) self.board.set_cards(self.deck.draw(2)) # update view self.ids.player1_box.round_play() self.ids.player2_box.round_play() self.ids.publicArea.round_play(self.board.get_cards()) self.ids.player1_box.update_hand(self.player[0].hand, self.turn) self.ids.player2_box.update_hand(self.player[1].hand, self.turn) # TODO: fix bet self.ids.publicArea.set_chip_info(self.player[0].chip, self.player[1].chip, self.board.bonus) self.ids.publicArea.set_info(self.board.get_bet_string(self.turn)) def round_end(self): """ The end of a game round. Decide winner of the round and chip shift based on: (1) If any lier caught (2) Card score """ self.turn = 5 ''' Evaluation card rank ''' self.player[0].cardScore = self.evaluator.evaluate( self.board.get_cards(), self.player[0].hand) self.player[1].cardScore = self.evaluator.evaluate( self.board.get_cards(), self.player[1].hand) self.player[0].rank = self.evaluator.get_rank_class( self.player[0].cardScore) self.player[1].rank = self.evaluator.get_rank_class( self.player[1].cardScore) ''' Card winner ''' cardWinner = 1 if self.player[0].cardScore < self.player[1].cardScore: cardWinner = 0 # Player1 ''' Decide chip gain rate for winner, loser and board ''' winnerRate = 1.0 # The chip to handover to the card winner loserRate = 0.0 # The chip to handover to the card loser maintainRate = 0.0 # The chip left on the table if self.player[cardWinner].caught and self.player[cardWinner ^ 1].caught: # Both of players lied, and caught. winnerRate, maintainRate, loserRate = 0, 1, 0 elif self.player[cardWinner].caught: # Only winner caught if self.player[cardWinner].suspect: winnerRate, maintainRate, loserRate = -1, 1.5, 0.5 else: winnerRate, maintainRate, loserRate = -0.5, 1, 0.5 elif self.player[cardWinner ^ 1].caught: # Only loser caught if self.player[cardWinner ^ 1].suspect: winnerRate, maintainRate, loserRate = 1.5, 0.5, -1 else: winnerRate, maintainRate, loserRate = 1.5, 0, -0.5 else: # No one caught winnerRate, maintainRate, loserRate = 1, 0, 0 if self.player[cardWinner].suspect: winnerRate -= 0.5 maintainRate += 0.5 if self.player[cardWinner ^ 1].suspect: loserRate -= 0.5 maintainRate += 0.5 """ Winner Host Loser winnerPrize <--1.0 ( Stay at host if winner caught ) LieCost 0.5 <--------> 0.5 ( Pay to opponent if caught ) SuspectCost 0.5-> <-0.5 ( Pay to host if suspect not stand ) """ ''' Calculate chip gain ''' stacks = self.board.totalChip bonus = self.board.bonus self.player[cardWinner].chip += int(stacks * winnerRate) self.player[cardWinner ^ 1].chip += int(stacks * loserRate) if winnerRate > 0: # winner gets bonus self.player[cardWinner].chip += bonus bonus = stacks * maintainRate elif winnerRate < 0 and loserRate > 0: # loser gets bonus self.player[cardWinner ^ 1].chip += bonus bonus = stacks * maintainRate else: # no one gets bonus due to double caught bonus = bonus + stacks * maintainRate self.board.set_bonus(int(bonus)) # TODO: real winner, win type, chip gain roundMsg = "Player " + str(cardWinner + 1) + " wins." ''' Test Mode message ''' # print cards for check in test mode if self.testMode: print '*' * 50 if self.player[cardWinner].caught and self.player[cardWinner ^ 1].caught: print "Draw due to double caught." elif not self.player[cardWinner].caught and not self.player[ cardWinner ^ 1].caught: print "No one caught." print " Player1\t\tPlayer2" print "Lie : ", self.player[0].lie, "\t\t", self.player[ 1].lie print "Suspection: ", self.player[0].suspect, "\t\t", self.player[ 1].suspect print "Caught : ", self.player[0].caught, "\t\t", self.player[ 1].caught print "Fold : ", self.player[0].fold, "\t\t", self.player[ 1].fold if cardWinner == 0: print " Win\t\tLose" else: print " Lose\t\tWin" print "Rate (winner/maintain/loser): ", winnerRate, maintainRate, loserRate print "Chip and bonus after: ", self.board.totalChip, self.board.bonus print "Card rank: " print "Player 1 hand rank = %d (%s)" % (self.player[0].cardScore, self.player[0].rank) print "Player 2 hand rank = %d (%s)" % (self.player[1].cardScore, self.player[1].rank) print '*' * 50 ''' end a game round ''' # TODO: show at another place self.ids.player1_box.set_button_message( self.evaluator.class_to_string(self.player[0].rank)) self.ids.player2_box.set_button_message( self.evaluator.class_to_string(self.player[1].rank)) self.ids.publicArea.round_end("Round : " + str(self.round) + "\n" + roundMsg + "\nNew Round") self.board.round_end() self.ids.player1_box.round_end() self.ids.player2_box.round_end()
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"
from collections import Counter from datetime import datetime from deuces import ( Deck, Evaluator ) import random random.seed(1) print 'Generating the hands.' print datetime.now() hands = [ Deck().draw(5) for _ in range(1000000) ] e = Evaluator() print 'Scoring them.' print datetime.now() scores = [ e.evaluate(x, []) for x in hands ] ranks = [ e.get_rank_class(s) for s in scores ] rank_strings = [ e.class_to_string(r) for r in ranks ] print 'Counting them.' print datetime.now() c = Counter(rank_strings) for i in c.most_common(10): print i
# 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) # bin the scores into classes p1_class = evaluator.get_rank_class(p1_score) p2_class = evaluator.get_rank_class(p2_score) # or get a human-friendly string to describe the score print("Player 1 hand rank = %d (%s)" % (p1_score, evaluator.class_to_string(p1_class))) print("Player 2 hand rank = %d (%s)" % (p2_score, evaluator.class_to_string(p2_class))) # or just a summary of the entire hand hands = [player1_hand, player2_hand] evaluator.hand_summary(board, hands)
from deuces import (Deck, Evaluator) from itertools import combinations import pandas as pd deck = Deck().draw(52) e = Evaluator() all_hands = [list(x) for x in combinations(deck, 5)] all_scores = [e.evaluate(x, []) for x in all_hands] all_ranks = [e.get_rank_class(x) for x in all_scores] df_all = pd.DataFrame({'score': all_scores, 'rank': all_ranks}) df = df_all.groupby('rank').agg({'rank': 'count', 'score': [min, max]}) df.columns = df.columns.get_level_values(1) df['width'] = df['max'] - df['min'] + 1 df['ratio'] = df['count'] / df['width']