Overview
这是一个简单的Python实现的21点(Blackjack)游戏。以下是代码的主要部分和功能解释:
1. `main()` 函数:主要的游戏逻辑在这里。它包括处理玩家的赌注、发牌、处理玩家和庄家的动作、判断输赢等。
2. `getBet()` 函数:提示玩家下注金额,并验证输入的赌注是否合法。
3. `getDeck()` 函数:生成一副完整的扑克牌(52张)并洗牌。
4. `displayHands()` 函数:显示玩家和庄家的牌面。如果 `showDealerHand` 参数为 `False`,则隐藏庄家的第一张牌。
5. `getHandValue()` 函数:计算一手牌的总点数。将A的值视为1或11,其他牌的值为其点数值,J、Q、K视为10。
6. `displayCards()` 函数:用文本形式打印出玩家和庄家的牌面。
7. `getMove()` 函数:获取玩家的行动选择,可以选择继续要牌(Hit)、停止要牌(Stand)、双倍下注(Double down)。
8. `if __name__ == '__main__':` 部分:如果直接运行代码文件,则执行 `main()` 函数。
这个游戏允许玩家与庄家进行21点游戏,并实现了赌注、牌面显示、动作选择、赢家判定等基本功能。
1.The Program in Action:
(ll_env) maxwellpan@192 4BlackJack % python3 blackjack.py
Blackjack, by Maxwell Pan
Rules:
Try to get as close to 21 without going over.
Kings,Queens, and Jacks are worth 10 points.
Aces are worth 1 or 11 points.
Cards 2 through 10 are worth their face value.
(H)it to take another card.
(S)tand to stop taking cards.
On your first play, you can (D)ouble down to increase your bet but must hit exactly one more time before standing, In case of a tie, the bet is returned to the player.
The dealer stops hitting at 17.
Money: 5000
How much do you bet? (1-5000, or QUIT)
> 400
Bet: 400
DEALER: ???
____ ____
|## | |J |
|###| | ♦ |
|_##| |__J |
PLAYER: 20
____ ____
|K ||Q |
| ♥ || ♠ |
|__K ||__Q |
(H)it, (S)tand, (D)ouble down> h
You drew a 8 of ♠.
DEALER: ???
____ ____
|## | |J |
|###| | ♦ |
|_##| |__J |
PLAYER: 28
____ ____ ____
|K ||Q ||8 |
| ♥ || ♠ || ♠ |
|__K ||__Q ||__8 |
DEALER: 21
____ ____
|A ||J |
| ♣ || ♦ |
|__A ||__J |
PLAYER: 28
____ ____ ____
|K ||Q ||8 |
| ♥ || ♠ || ♠ |
|__K ||__Q ||__8 |
You lost!
Press Enter to continue...
Money: 4600
How much do you bet? (1-4600, or QUIT)
> quit
Thanks for playing!
(ll_env) maxwellpan@192 4BlackJack %
2. How It Works
"""Blackjack, by Maxwell Pan
The classic card game also known as 21.(This version doesn't have splitting or insurance.)
More info at https://en.wikipedia.org/wiki/Blackjack
View this code at https://nostarch.com/big-book-small-python-projects
Tags: large, game, card game"""
import random, sys
# Set up the constants:
HEARTS = chr(9829)
DIAMONDS = chr(9830)
SPADES = chr(9824)
CLUBS = chr(9827)
# (A list of chr codes is at https://inventwithpython.com/charactermap)
BACKSIDE = 'backside'
def main():
print('''Blackjack, by Maxwell Pan
Rules:
Try to get as close to 21 without going over.
Kings,Queens, and Jacks are worth 10 points.
Aces are worth 1 or 11 points.
Cards 2 through 10 are worth their face value.
(H)it to take another card.
(S)tand to stop taking cards.
On your first play, you can (D)ouble down to increase your bet but must hit exactly one more time before standing, In case of a tie, the bet is returned to the player.
The dealer stops hitting at 17.''')
money = 5000
while True: # Main game loop.
# Check if the player has run out of money.
if money < 0:
print("You're broke!")
print("Good thing you weren't playing with real money.")
print("Thanks for playing!")
sys.exit()
# Let the player enter their bet for this round:
print('Money:', money)
bet = getBet(money)
# Give the dealer and player two cards from the deck each:
deck = getDeck()
dealerHand = [deck.pop(), deck.pop()]
playerHand = [deck.pop(), deck.pop()]
# Handle player actions:
print('Bet:', bet)
while True: #Keep looping until player stands or busts.
displayHands(playerHand, dealerHand, False)
print()
# Check if the player has bust:
if getHandValue(playerHand) > 21:
break
# Get the player's move, either H, S, or D:
move = getMove(playerHand, money - bet)
# Handle the player actions:
if move == 'D':
# Player is doubling down, they can increase their bet:
additionalBet = getBet(min(bet, (money - bet)))
bet += additionalBet
print('Bet increased to {}.'.format(bet))
bet += additionalBet
print('Bet increased to {}.'.format(bet))
print('Bet:', bet)
if move in ('H','D'):
# Hit/doubling down tasks another card.
newCard = deck.pop()
rank, suit = newCard
print('You drew a {} of {}.'.format(rank, suit))
playerHand.append(newCard)
if getHandValue(playerHand) > 21:
# The player has busted:
continue
if move in ('S', 'D'):
# Stand/doubling down stops the player's turn.
break
# Handle the dealer's actions:
if getHandValue(playerHand) <= 21:
while getHandValue(dealerHand) < 17:
# The dealer hits:
print('Dealer hits...')
dealerHand.append(deck.pop())
displayHands(playerHand, dealerHand, False)
if getHandValue(dealerHand) > 21:
break # The dealer has busted.
input('Press Enter to continue...')
print('\n\n')
# Show the final hands:
displayHands(playerHand, dealerHand, True)
playerValue = getHandValue(playerHand)
dealerValue = getHandValue(dealerHand)
# Handle whether the player won, lost, or tied:
if dealerValue > 21:
print('Dealer busts! You win ${}!'.format(bet))
money += bet
elif (playerValue > 21) or (playerValue < dealerValue):
print('You lost!')
money -= bet
elif playerValue > dealerValue:
print('You won ${}!'.format(bet))
money += bet
elif playerValue == dealerValue:
print('It\'s a tie, the best is returned to you.')
input('Press Enter to continue...')
print('\n\n')
def getBet(maxBet):
"""Ask the player how much they want to bet for this round."""
while True: #Keep asking until they enter a valid amount.
print('How much do you bet? (1-{}, or QUIT)'.format(maxBet))
bet = input('> ').upper().strip()
if bet == 'QUIT':
print('Thanks for playing!')
sys.exit()
if not bet.isdecimal():
continue # If the player didn't enter a number , ask again.
bet = int(bet)
if 1 <= bet <= maxBet:
return bet # Player entered a valid bet.
def getDeck():
"""Return a list of (rank, suit) tuples for all 52 cards."""
deck = []
for suit in (HEARTS, DIAMONDS, SPADES, CLUBS):
for rank in range(2, 11):
deck.append((str(rank), suit)) # Add the numbered cards.
for rank in ('J','Q','K','A'):
deck.append((rank, suit)) # Add the face and race cards
random.shuffle(deck)
return deck
def displayHands(playerHand, dealerHand, showDealerHand):
"""Show the player's and dealer's card. Hide the dealer's first card if showDealerHand is False."""
print()
if showDealerHand:
print('DEALER:', getHandValue(dealerHand))
displayCards(dealerHand)
else:
print('DEALER: ???')
# Hide the dealer's first card:
displayCards([BACKSIDE] + dealerHand[1:])
# Show the player's cards:
print('PLAYER:', getHandValue(playerHand))
displayCards(playerHand)
def getHandValue(cards):
"""Returns the value of the cards. Face cards are worth 10, aces are worth 11 or 1 (this function picks the most suitable ace value)."""
value = 0
numberOfAces = 0
# Add the value for the non-ace cards
for card in cards:
rank = card[0] # card is a tuple like(rank, suit)
if rank == 'A':
numberOfAces += 1
elif rank in ('K','Q','J'): # Face cards are worth 10 points
value += 10
else:
value += int(rank) # Numbered cards are worth their number.
# Add the value for the aces:
value += numberOfAces # Add 1 per ace.
for i in range(numberOfAces):
# If another 10 can be added with busting, do so:
if value + 10 <= 21:
value += 10
return value
def displayCards(cards):
"""Display all the cards in the cards list."""
rows = ['', '', '', '', ''] # The text to display on each row.
for i, card in enumerate(cards):
rows[0] += ' ____ ' # Print the top line of the card.
if card == BACKSIDE:
# Print a card's back:
rows[1] += '|## | '
rows[2] += '|###| '
rows[3] += '|_##| '
else:
# Print the card's front:
rank, suit = card #The card is a tuple data structure.
rows[1] += '|{} |'.format(rank.ljust(2))
rows[2] += '| {} |'.format(suit)
rows[3] += '|_{} |'.format(rank.rjust(2, '_'))
# Print each row on the screen:
for row in rows:
print(row)
def getMove(playerHand, money):
"""Asks the player for their move, and returns 'H' for hit, 'S' for stand , 'D' for double down."""
while True:
# Determine what moves the player can make:
moves = ['(H)it', '(S)tand']
# The player can double down on their first move, which we can
# tell because they'll have exactly two cards:
if len(playerHand) == 2 and money > 0:
moves.append('(D)ouble down')
# Get the player's move:
movePrompt = ', '.join(moves) + '> '
move = input(movePrompt).upper()
if move in ('H', 'S'):
return move # Player has entered a valid move.
if move == 'D' and '(D)ouble down' in moves:
return move # Player has entered a valid move.
# If the program is run (instead of imported), run the game:
if __name__ == '__main__':
main()