21点(Blackjack)是一种经典的赌场扑克游戏,玩家与庄家比拼牌面点数,目标是使自己的牌总点数尽可能接近21点但不爆掉。本文将详细介绍如何使用Python实现一个简化版的21点游戏。
import random
money = 100 # 玩家的总资产
def get_shuffled_deck():
"""初始化包括52张扑克牌的列表,并混排后返回,表示一副洗好的扑克牌"""
suits = {'♣', '♠', '♦', '♥'}
ranks = {'2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'}
deck = []
# 创建一副52张的扑克牌
for suit in suits:
for rank in ranks:
deck.append(suit + ' ' + rank)
random.shuffle(deck)
return deck
def deal_card(deck, participant, flag):
"""发一张牌给参与者participant"""
card = deck.pop()
if flag:
flag_1 = input('是否开启高级玩家模式(输入H)')
if flag_1 == 'H':
password = input('输入高级玩家密码:')
if password == '123456':
print(card)
flag_2 = input('是否要这张牌(输入是/否):')
if flag_2 == '是':
participant.append(card)
return card
else:
return
else:
print('输入密码错误')
print('直接发牌')
participant.append(card)
return card
else:
participant.append(card)
return card
else:
participant.append(card)
if compute_total(participant) > 21:
participant.pop()
return
else:
return card
def compute_total(hand):
"""计算并返回一手牌的点数和"""
values = {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8,
'9': 9, '10': 10, 'J': 0.5, 'Q': 0.5, 'K': 0.5, 'A': 1}
result = 0 # 初始化点数和为0
for card in hand:
result += values[card[2:]]
return result
def blackjack():
global money
deck = get_shuffled_deck()
house = [] # 庄家的牌
player = [] # 玩家的牌
# 初始发牌
for i in range(2):
deal_card(deck, player, False)
deal_card(deck, house, False)
print('庄家的牌:', end='')
print_hand(house)
print('玩家的牌:', end='')
print_hand(player)
bet = 10
print('下注10元')
# 玩家回合
answer = input('是否继续拿牌(y/n,缺省为y):')
while True:
while answer in ('', 'y', 'Y'):
if len(player) >= 5:
break
card = deal_card(deck, player, True)
print('玩家拿到的牌为:', end='')
print_hand(player)
flag = input('是否加注(是/否):')
if flag == '是':
bet_num = int(input('加注多少元:'))
if bet_num + bet > money:
print('穷货,你没那么多钱')
else:
bet += bet_num
print('加注成功,当前下注金额:', bet)
if compute_total(player) > 21:
print('爆掉 玩家输牌!')
money -= int(bet * random.uniform(1, 2))
return
answer = input('是否继续拿牌(y/n,缺省为y):')
# 庄家回合
while compute_total(house) < 17:
if len(house) >= 5:
break
card = deal_card(deck, house, False)
print('庄家拿到的牌为:', end='')
print_hand(house)
answer = input('是否进入结算(y/n,缺省为y):')
if answer in ('', 'y', 'Y'):
break
# 结算
houseTotal, playerTotal = compute_total(house), compute_total(player)
if houseTotal > playerTotal:
print('庄家赢牌!')
money -= int(bet * random.uniform(1, 2))
elif houseTotal < playerTotal:
print('玩家赢牌!')
money += int(bet * random.uniform(1, 2))
elif houseTotal == 21 and 2 == len(house) < len(player):
print('庄家赢牌!')
money -= int(bet * random.uniform(1, 2))
elif playerTotal == 21 and 2 == len(player) < len(house):
print('玩家赢牌!')
money += int(bet * random.uniform(1, 2))
else:
print('平局!')
if __name__ == '__main__':
while money > 0:
blackjack()
print('你的余额为:', money)
f = input('是否继续玩耍(是/否):')
if f == '是':
continue
else:
break
else:
print('你破产了')
输入密码可以预知下一张牌并选择是否要牌,为游戏增添策略元素。
玩家可以在游戏过程中灵活加注,体验真实的赌场氛围。
输赢金额会在下注金额的1-2倍之间随机浮动,增加游戏变数。
庄家拿牌时自动防止爆牌,保证游戏逻辑合理性。