用户:锅巴b12W查看:0 回复:0 评论:0 创建时间:2023-06-03T13:47:23
【作品展示】

【作品介绍】
二十一点
【作品源代码】
import random
# 定义常量
CARD_VALUES = {"A": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "10": 10, "J": 10, "Q": 10, "K": 10}
PLAYER_MIN_SCORE = 12
DEALER_HIT_UNTIL = 17
# 定义函数
def deal_card(deck):
return deck.pop()
def total(cards):
values = [CARD_VALUES[card] for card in cards if card in CARD_VALUES]
num_aces = sum(card == "A" for card in cards)
sum_values = sum(values)
for i in range(num_aces):
if sum_values + 10 <= 21:
sum_values += 10
return sum_values
def print_cards(title, cards):
print(title)
for card in cards:
print(card, end=" ")
print()
# 初始化扑克牌
deck = list(CARD_VALUES.keys()) * 4
random.shuffle(deck)
# 发牌
player_hand = [deal_card(deck), deal_card(deck)]
dealer_hand = [deal_card(deck), deal_card(deck)]
# 玩家抽牌
while total(player_hand) < PLAYER_MIN_SCORE:
player_hand.append(deal_card(deck))
# 庄家抽牌
while total(dealer_hand) < DEALER_HIT_UNTIL:
dealer_hand.append(deal_card(deck))
# 显示底牌
print_cards("庄家底牌:", [dealer_hand[0], "*"])
print_cards("你的牌:", player_hand)
# 判断游戏结果
player_score = total(player_hand)
if player_score > 21:
print("你输了!")
elif total(dealer_hand) > 21:
print("你赢了!")
elif player_score > total(dealer_hand):
print("你赢了!")
elif player_score < total(dealer_hand):
print("你输了!")
else:
print("平局!")
# 显示庄家所有牌
print_cards("庄家的牌:", dealer_hand)
【提示】
部分含有Python第三方库相关内容的作品,在海龟编辑器网页端无法运行哦!如遇到这种情况,可以打开下面的链接,下载海龟编辑器客户端:
https://python.codemao.cn