A brief introduction to Texas Hold'em
What's Texas Hold 'Em?
Texas Hold'em Poker is a gaming card game that originated in Texas, U.S.A. The game is divided into regular table (Cash, cash game), single table tournament (SNG) and multi-table tournament (MTT). Although there are many different types of poker, the basic rules of poker usually remain the same. It is a game of mind and strategy.
Brief description of the rules of the game
I. Use of props
A standard deck of playing cards is played with 52 cards after removing the king and queen.
II. Number of players
Usually 2-10 players, with isolated cases of 12 players.
III. Purpose of the game
Win chips from other players
IV. Purpose of betting
Players need to bet the same amount of chips to continue to see or match cards at the same time, and players who are short on chips can see the end of the hand and participate in the match after all-in.
V. Dealing bets
Licensing is generally divided into 5 steps, which are.
Perflop - the big and small blinds are placed first, then each player is dealt 2 cards, the first player behind the big blind chooses to call, raise, or cover and fold, and in a clockwise direction, the other players tabulate in turn, with the player in the big blind tabulating last, and the player who has already called needs to tabulate again if the player has a raising situation If a player raises, the player who called before him needs to check again, or even multiple times.
Flop - Three public cards are dealt at the same time, starting with the small blind (if the small blind has covered, the player closest behind starts, and so on), and the table is tabled in clockwise order, with the players having the option of betting, raising, or folding with a cover.
Turn - Deal the 4th card, starting in the small blind and tabling in clockwise order.
River - A fifth card is dealt, starting with the small blind and tabling in clockwise order, with players having the option of betting, raising, or folding with a cover.
Match Play - After the first 4 rounds of dealing and betting, the remaining players begin to show their cards to match sizes, and the player with the largest completed hand wins the bottom of the pool.
VI. Methods of comparing cards
Using your 2 base cards combined with your 5 community cards, you select 5 cards, regardless of how many cards you use in your hand (you can even use no base cards in your hand), to make the largest completed hand, and compare sizes with the other players.
Than the card first than the card type, the big card type is bigger than the small card type, the card type is generally divided into 10 kinds, from big to small for:
A python implementation of a Texas Hold'em game.
Game Initialization
# Call the sample function in the random library for randomly drawing cards from the deck pile from random import sample # Use lists to store card suits and numbers color = ['Spades','Cardinal','Plum Blossom','Square'] number = ['2','3','4','5','6','7','8','9','10','J','Q','K','A']
The sample function in the random library is imported and subsequently used to randomly draw cards from the deck pile. Also use the list to store the color and number of the cards in color and number respectively.
The #PokerGenerator function is used to generate a deck of cards def PokerGenerator(): #Store cards in lists Poker = [] # Dictionary representation of cards, adding 52 blank cards to the Poker list for i in range(0,52): t = {'Numbers':0,'Flower color':''} (t) # Assigns a value to each card, each suit has 13 suits each, for a total of four suits and 52 cards. for i in range(0,52): Poker[i].update({'Numbers':number[i%13],'Flower color':color[i//13]}) # Returns the list Poker with 52 cards stored in it return Poker
The function PokerGenerator is used to generate a new deck of playing cards, the standard deck of playing cards used in Texas Hold'em, containing four suits ('spades', 'hearts', 'clubs', 'diamonds'), each suit has 13 cards ranging from '2' to 'A', for a total of 52 playing cards, not including large and small. ', 'Spades', 'Hearts', 'Clubs', 'Diamonds'), each suit has 13 cards ranging from '2' to 'Ace', for a total of 52 poker cards, excluding kings and queens.
#Distribute cards according to the number of players def Pokerinitial(playersum): Playerpoker = [] Poker = PokerGenerator()#Initialize a new deck of cards num = 52 for i in range(0,playersum): Pripoker = sample(Poker,2)#Draw two cards at random from the deck for one player's hand (Pripoker)#The drawn cards are pseudo-added to the Playerpoker list as a tuple, with the Playerpoker's subscript number representing the player's serial number. # Remove the cards drawn by each player from the deck pile, i.e., implement a no-playback sampling for n in [0,1]: for m in range(0,num): if Poker[m] == Pripoker[n]: del Poker[m] num -=1 break Publicpoker = sample(Poker,3)# Draw three more cards from the pile as a public card # Remove the drawn public card from the pile. for n in [0,1,2]: for m in range(0,num): if Poker[m] == Publicpoker[n]: del Poker[m] num -=1 break # Show each player's hand with the public card output for i in range(0,playersum): print("Player %d"%(i+1)+": Card 1:"+str(Playerpoker[i][0])+" Card 2:"+str(Playerpoker[i][1])) print("") print("") print("") print("Public cards:"+str(Publicpoker)+" ") return [Playerpoker,Poker,Publicpoker]#Returns player's hand, remaining pile, public deck
Distribute two hand cards to each player, distribute the three public cards at the start of the game, and display the output of each player's hand situation with the public situation, using a dictionary to represent the playing cards.
pick a winner
The most critical step in realizing Texas Hold'em is to figure out which player has the biggest hand, determine the final winner, and split the prize pool if there are multiple final winners. I use 0 to 8 and so on 9 numbers represent high cards to flush and so on four levels, I do not specialize in the Royal Flush list a level, if the field at the same time appeared two flush, according to the largest card number in the flush to determine the winner, the next began to introduce the method of determining the various categories of hands.
#Determine if a player's cards form a straight with the community cards def judgestraight(finalpoker): result = [0, 0]#The result is used to store the results. result[0] stores the category of the player's best five cards, numbered from 0 to 9 from the high card to the royal flush. result[1] stores the card with the highest number in the current open set. pokernum = []#Store the numbers of the deck for i in range(0, len(finalpoker)): ((finalpoker[i]['Numbers'])) ()# Sort card numbers from smallest to largest #Determine if a combination of player cards and public cards can constitute a straight maxp = minp = 0 for i in range(1, len(finalpoker)): if (pokernum[i - 1] + 1) == pokernum[i]: maxp = i else: minp = i if (maxp - minp) == 4: result[0] = 4 result[1] = max(pokernum[minp:maxp + 1]) return result
The judgestraight function is used to determine whether the player's hand and the five public cards can constitute a straight, and requires the input parameter finalpoker. finalpoker should accept a list object containing the player's hand and the final public cards, totaling seven cards. The finalpoker shall accept a list object containing the player's hand and the final public cards, totaling 7 cards, and shall determine whether there is a straight among them and return the result of the judgment. The result contains two pieces of information: result[0] is 4 if it contains a straight, and 0 if it does not. If it contains a straight, result[1] stores the number of the largest card in the straight.
#Determine if there is a flush in the deck def judgeflush(finalpoker): result = [0, 0] pokernum = [] flush = []# Used to store cards of the same suit while len(finalpoker) >= 5: #Draw cards of the same suit in the deck (finalpoker[0]) for i in range(1, len(finalpoker)): if finalpoker[i]['Flower color'] == finalpoker[0]['Flower color']: (finalpoker[i]) # If there are no fewer than five cards of the same color, then the deck has a flush if len(flush) >= 5: result[0] = 5 for ele in flush: ((ele['Numbers'])) result[1] = max(pokernum) for ele in flush: (ele) () return result
The judgeflush function is used to determine whether the player's hand contains a flush and returns the result. As above, the result returned by the judgeflush function contains two pieces of information, whether or not the combination of the player's hand and the public beat contains a flush, and if so, the maximum number in the flush is returned at the same time.
#Determine if there are four, three, two or one pairs in the deck def judgesame(finalpoker): result = [0, 0] four = -1 #Record the presence of four in the deck three = -1 #Record the presence of three in the deck two = [-1, -1] #Record the presence of two pairs in the deck vs. one pair count = 1 pokernum = [] bottom = 0 #Store all card numbers of the deck into pokernum and sort them for i in range(0, len(finalpoker)): ((finalpoker[i]['Numbers'])) () # Determine if there are four, three, two pairs or one pair, etc. in the deck and store the largest corresponding card numbers for i in range(1, len(finalpoker)): if pokernum[i] == pokernum[bottom]: count += 1 else: if count == 2: if pokernum[bottom] > min(two): numid = (min(two)) two[numid] = pokernum[bottom] if count == 3: if pokernum[bottom] > three: three = pokernum[bottom] if count == 4: four = pokernum[bottom] bottom = i count = 1 #Determine the largest combo card type present in the deck if four >= 0: result[0] = 7 result[1] = four elif three >= 0 and max(two) >= 0: result[0] = 6 t = three * 10 + max(two) result[1] = t elif three >= 0: result[0] = 3 result[1] = three elif min(two) >= 0: result[0] = 2 result[1] = max(two) elif max(two) >= 0: result[0] = 1 result[1] = max(two) return result
This function is relatively much longer compared to the two functions above, as it performs three functions in one, determining whether the combination of a player's hand and a public card contains a pair, two pairs, three or four. Similar to the function above, judgesame determines whether the accepted deck contains any of these four cases, and if it does, it returns the case with the highest rank, as well as the number of the largest card contained in that case.
# Calculate the largest combo card type in a player's deck holdings def computeresult(Playerpoker, Publicpoker): finalresult = [0, 0] finalpoker = [] finalpoker = Playerpoker + Publicpoker a = () b = () c = () # Store the judgment results of flush, straight, four, three (i.e., the number of digits that are the same as the case), etc., respectively result_1 = judgeflush(a) result_2 = judgestraight(b) result_3 = judgesame(c) #Determine if it's a Flush if result_1[0] != 0 and result_2[0] != 0: finalresult[0] = 8 finalresult[1] = result_2[1] #If it is not a flush, determine the largest deck type consisting of the player's hand with the public cards in it else: t_0 = result_1[0] t_1 = result_1[1] if result_2[0] > t_0: t_0 = result_2[0] t_1 = result_2[1] if result_3[0] > t_0: t_0 = result_3[0] t_1 = result_3[1] # Determine the final result, i.e., the maximum card type a player has finalresult[0] = t_0 finalresult[1] = t_1 return finalresult
I ended up utilizing the computersult function to calculate the highest ranked deck that each player ended up with. In this function I call each of the three functions above, compare them to arrive at the highest ranked deck a player has, and return the results.
Game Theme Functions
We wrote the function has been able to achieve the initialization of the game and the calculation of the results of the game, then we will use the above function to write the real body of the Texas Hold'em game.
# Game function body def gamestart(playersum): finalresult = []# Used to store each player's maximum hand [playerpoker,Poker,Publicpoker] = Pokerinitial(playersum)# Initialize a deck of cards based on the number of players and distribute two hand cards to each player, and distribute the initial three public cards playerlist = list(range(1,playersum+1))#Record players remaining after each round. playerlist_t = [] Playerpoker = [] while len(Publicpoker) < 5 and len(playerlist) > 1:#When the community card count is 5 or when there is only one player left, the game ends for settlement tag = 0 # Identifier to mark whether the player entered to continue the game is incorrect, and if so, to re-enter it playerkeep = input("Please enter the player who will continue the game:") playerlist_t = eval(playerkeep) if isinstance(playerlist_t,int): if playerlist_t in playerlist: winplayer = playerlist_t print("game over. The winner is "+str(winplayer))# If only one player chooses to continue the game, the game ends with a settlement return () else: print("Input error, please re-enter.")# If the input player does not exist during the turn an error is reported and the player is re-entered. elif isinstance(playerlist_t, tuple): playerlist_t = list(playerlist_t) for i in playerlist_t: if i not in playerlist: tag = 1 if tag == 1: print("Input error, please re-enter.")# If one of the players entered does not exist during the turn, an error is reported and the player is re-entered. else: playerlist = playerlist_t pokerkeep = sample(Poker,1)#Draw another card from the remaining deck as a public card Publicpoker += pokerkeep pokerkeep = pokerkeep[0] print("Public cards:"+str(Publicpoker)+" ")#Display the public cards for this turn for n in range(0,len(Poker)):#Remove the drawn public card from the remaining decks if Poker[n] == pokerkeep: del Poker[n] break for i in playerlist: (playerpoker[i-1]) for ppoker in Playerpoker: (computeresult(ppoker, Publicpoker))# Calculate the final result by substituting each player's hand with the public cards finalscore = [] finalscore_t = [] finalplayer = [] winner = [] for t in range(0, len(finalresult)): (finalresult[t][0]) maxscore = max(finalscore)# Determine the type of the largest combination of cards among all players at this point in time # If more than one player has the largest type of combination at the same time, the numbers of their largest cards are compared for t in range(0, len(finalresult)): if finalscore[t] == maxscore: (t) for t in finalplayer: finalscore_t.append(finalresult[t][1]) maxscore_t = max(finalscore_t) for t in finalplayer: if finalresult[t][1] == maxscore_t: (playerlist[t]) ##Output the final player print("game winner is:") for t in winner: print("Player:"+str(t)) return
The only parameter that the gamestart function needs to output is the number of players. At the start of the game, we use the Pokerinitial function to obtain a new deck of cards, deal two hands to each player, and distribute three initial public cards. When the number of players is down to one halfway through the game, we consider the game to be over and display the final winner. If the game proceeds normally to the end (with two or more players sticking around until the final turn), the highest ranked card combination each player has is counted and compared to arrive at the final winner. If the player who enters to continue the game is not in the current team of players, the system will report an error and prompt a new entry. Well, without further ado, let's start experiencing the game!
Game Experience and Demonstration
from Texas_Hold_em_Poker import gamestart
We start by importing the Texas Hold'em game module we wrote and only need the gamstart function from it.
n = input('Please enter the number of players for the game to be played:') gamestart(int(n))
We then write an input function to get the number of players playing the game from the console.
We set the number of players participating in the game at 5
Then each player's hand and public cards appeared on the screen.
Then we enter the player who will continue the game
Then the public cards for the next turn appeared, and we proceeded to let players 1, 2 and 3 continue the game
You can see that the public cards from the final round appear and the final winner is calculated. At this point we try to enter the number of a player who did not continue in the game last turn and see what comes up.
We still set the number of players in the game at 5 and still let players 1, 2, and 3 continue the game on the first turn
But we enter players #4 and #5, who have quit the game, on the next turn.
You can see that the system reported an error and prompted to re-enter, at this point we just need to enter the correct player number to get the correct results.
Module deficiencies and subsequent improvements
In the game display we can see that the player's hand is public, while in the actual Texas Hold'em, each player's hand is completely confidential, which obviously does not meet the practical requirements. But because this code can only be output in the console display, so there is no good way to confidentiality of each player's hand, if the next can be achieved visualization can be set up by setting the key to output each player's hand, respectively, to achieve good confidentiality, or on this basis it will be developed into a final mini-game is also able to achieve confidentiality.
In addition to this in Texas Hold'em need to have non-stop raises and calls, which can also be written as a function, this waiting for some time I slightly empty point can fill up hahaha, have the idea of friends can also write their own try.
To this article on the use of Python to write a simple version of Texas Hold'em poker game is introduced to this article, more related Python Texas Hold'em content, please search for my previous articles or continue to browse the following related articles I hope that you will support me more in the future!