📅  最后修改于: 2023-12-03 14:46:39.318000             🧑  作者: Mango
二十一点是一种常见的纸牌游戏,也称为21点或Blackjack。本文将介绍如何使用Python编写二十一点游戏。
游戏通常由一个或多个玩家参与,每个玩家的目的都是使手中的牌的点数相加不大于21点,但又不能小于庄家的点数。点数的计算规则如下:
我们需要用到以下数据结构:
代码实现大致的步骤如下:
下面是代码实现的示例:
import random
cards = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
points = {'A': 11, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10}
def init_deck():
deck = cards * 4
random.shuffle(deck)
return deck
def get_points(hand):
num_aces = hand.count('A')
total_points = sum(points[card] for card in hand)
while total_points > 21 and num_aces:
total_points -= 10
num_aces -= 1
return total_points
def play_game():
deck = init_deck()
player_hand = [deck.pop(), deck.pop()]
dealer_hand = [deck.pop(), deck.pop()]
while True:
print(f"Player has: {player_hand}, total points: {get_points(player_hand)}")
choice = input("Do you want to hit or stand? ")
if choice.lower() == 'hit':
player_hand.append(deck.pop())
if get_points(player_hand) > 21:
print(f"Player has: {player_hand}, total points: {get_points(player_hand)}")
print("Bust!")
return -1
else:
break
dealer_points = get_points(dealer_hand)
while dealer_points < 17:
dealer_hand.append(deck.pop())
dealer_points = get_points(dealer_hand)
print(f"Dealer has: {dealer_hand}, total points: {dealer_points}")
player_points = get_points(player_hand)
if player_points > 21:
print("Bust!")
return -1
elif dealer_points > 21:
print("Dealer busts. You win!")
return 1
elif player_points > dealer_points:
print("You win!")
return 1
elif player_points == dealer_points:
print("Push.")
return 0
else:
print("You lose.")
return -1
if __name__ == '__main__':
play_again = True
while play_again:
result = play_game()
if result == 1:
print("Congratulations!")
elif result == 0:
print("Push. No one wins.")
else:
print("Better luck next time.")
print()
while True:
choice = input("Do you want to play again? ")
if choice.lower() == 'yes':
break
elif choice.lower() == 'no':
play_again = False
break
else:
print("Invalid choice. Please enter 'yes' or 'no'.")