python21点小游戏
时间: 2023-08-30 20:05:07 浏览: 121
python21点小游戏源码下载.zip
5星 · 资源好评率100%
以下是一个简单的Python 21点小游戏,供参考:
```python
import random
# 定义扑克牌的点数和花色
card_values = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
card_suits = ['♠', '♥', '♦', '♣']
# 创建一副扑克牌
deck = [(value, suit) for value in card_values for suit in card_suits]
# 计算一张牌的点数
def card_value(card):
if card[0] in ['J', 'Q', 'K']:
return 10
elif card[0] == 'A':
return 11
else:
return int(card[0])
# 计算一手牌的点数
def hand_value(hand):
value = sum(card_value(card) for card in hand)
num_aces = len([card for card in hand if card[0] == 'A'])
while value > 21 and num_aces:
value -= 10
num_aces -= 1
return value
# 发牌
def deal(deck, n):
hand = []
for i in range(n):
card = deck.pop()
hand.append(card)
return hand
# 打印一手牌
def print_hand(hand):
for card in hand:
print(card[0] + card[1], end=' ')
print()
# 主游戏逻辑
def play_game():
# 初始化
deck = [(value, suit) for value in card_values for suit in card_suits]
random.shuffle(deck)
player_hand = deal(deck, 2)
dealer_hand = deal(deck, 2)
# 玩家回合
while True:
print('你的牌是:')
print_hand(player_hand)
print('总点数是:', hand_value(player_hand))
if hand_value(player_hand) > 21:
print('你爆了!')
return False
elif hand_value(player_hand) == 21:
print('21点,你赢了!')
return True
else:
choice = input('你要继续要牌吗?(y/n)')
if choice.lower() == 'y':
player_hand.append(deck.pop())
else:
break
# 庄家回合
while hand_value(dealer_hand) < 17:
dealer_hand.append(deck.pop())
# 结束游戏
print('你的牌是:')
print_hand(player_hand)
print('总点数是:', hand_value(player_hand))
print('庄家的牌是:')
print_hand(dealer_hand)
print('总点数是:', hand_value(dealer_hand))
if hand_value(dealer_hand) > 21:
print('庄家爆了,你赢了!')
return True
elif hand_value(dealer_hand) > hand_value(player_hand):
print('庄家赢了!')
return False
elif hand_value(player_hand) > hand_value(dealer_hand):
print('你赢了!')
return True
else:
print('平局!')
return False
# 开始游戏
while True:
print('欢迎来玩21点!')
if play_game():
print('你赢了!')
else:
print('你输了!')
choice = input('你要再来一局吗?(y/n)')
if choice.lower() == 'n':
break
```
阅读全文