Python实现21点游戏教程:掌握Python编程,创建自己的21点游戏,附带源码示例
21点是一个流行的纸牌游戏,玩家与庄家对抗,目标是通过纸牌的总点数尽可能接近21点,但不超过21点。在Python中编写一个简单的21点游戏需要使用random模块来生成随机数模拟抽牌。
以下是一个简单的21点游戏的Python代码示例:
import random
def deal_card():"""返回一张随机生成的牌"""cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]return random.choice(cards)
def calculate_score(hand):"""计算手牌的总点数"""if sum(hand) == 21 and len(hand) == 2:return 0if 11 in hand and sum(hand) > 21:hand.remove(11)hand.append(1)return sum(hand)
def compare_scores(user_score, dealer_score):"""比较玩家和庄家的分数"""if user_score == dealer_score:return "平局"elif dealer_score == 0:return "庄家胜利"elif user_score == 0:return "玩家胜利"elif user_score > 21:return "玩家失败,分数超过21"elif dealer_score > 21:return "庄家失败,分数超过21"elif user_score > dealer_score:return "玩家胜利"else:return "庄家胜利"
# 游戏开始
playing = True
while playing:user_hand = []dealer_hand = []# 给玩家和庄家各发两张牌for _ in range(2):user_hand.append(deal_card())dealer_hand.append(deal_card())# 计算玩家和庄家的初始分数user_score = calculate_score(user_hand)dealer_score = calculate_score(dealer_hand)# 显示玩家的手牌和庄家的一张牌print("玩家手牌:", user_hand, "分数:", calculate_score(user_hand))print("庄家手牌:", dealer_hand[0], "分数:", calculate_score(dealer_hand))# 玩家决策while user_score != 0 and user_score < 21:hit_or_stand = input("你要击球(h)还是站立(s)? ")if hit_or_stand.lower() == 'h':user_hand.append(deal_card())user_score = calculate_score(user_hand)print("玩家击球,新牌是:", user_hand[-1], "当前分数:", user_score)elif hit_or_stand.lower() == 's':breakelse:print("无效输入,请输入h或s。")# 如果玩家分数超过21,则玩家失败if user_score > 21:print("玩家失败,分数超过21")break# 庄家决策while dealer_score != 0 and dealer_score < 17:dealer_hand.append(deal_card())dealer_score = calculate_score(dealer_hand)# 显示庄家的所有牌print("庄家击球,新牌是:", dealer_hand[-1], "庄家当前分数:", dealer_score)# 比较分数并宣布结果result = compare_scores(user_score, dealer_score)print(result)# 询问玩家是否再玩一轮new_game = input("想要再玩一轮吗(y/n)? ")if new_game.lower() != 'y':playing = False
print("感谢游玩,再见!")
在这个游戏中,玩家可以输入'h'来击球(即抽取一张牌),或者输入's'来站立(即停止抽取牌)。然后庄家会根据特定的规则抽取牌,最后比较玩家和庄家的分数来决定胜