Angela Yu Python教程第11天Blackjack代码无法运行,请求排查
解决Blackjack游戏代码的执行问题
以下是你的代码中存在的关键问题及修复方案:
主要问题与修复
函数调用错误:
在电脑抽卡的循环中,computer_cards.append(draw_card)没有调用函数(缺少括号),导致函数对象被添加到列表而非随机卡牌。应改为computer_cards.append(draw_card())。未更新电脑分数:
电脑抽卡后未重新计算分数,导致computer_score始终为初始值,可能引发无限循环。需在电脑每次抽卡后重新调用calculate_score更新分数。无意义的print调用:
compare函数仅打印结果但不返回值,print(compare(...))会额外输出None。直接调用compare(user_score, computer_score)即可。输入判断逻辑错误:
get_card == "y".lower()写法冗余且逻辑颠倒,应先将用户输入转为小写再判断,即get_card.lower() == "y"。跨平台清屏适配:
替换Replit专属的clear函数为跨平台实现,让代码能在Thonny等环境运行。
修复后的完整代码
import random import os def clear(): # 跨平台清屏函数,替代Replit专属的clear os.system('cls' if os.name == 'nt' else 'clear') # 若没有art.py文件,可注释掉该行或自行定义logo变量 from art import logo def draw_card(): cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] return random.choice(cards) def calculate_score(cards): if sum(cards) == 21 and len(cards) == 2: return 0 # 用0表示Blackjack if sum(cards) > 21 and 11 in cards: cards.remove(11) cards.append(1) return sum(cards) def compare(user_score, computer_score): if user_score > 21 and computer_score > 21: print("You went over 21. You lost") elif computer_score == 0: print("You lost. Computer has blackjack") elif user_score == 0: print("You won with a blackjack.") elif user_score == computer_score: print("Draw") elif user_score > 21: print("You lost") elif computer_score > 21: print("You won") elif user_score > computer_score: print("You won.") else: print("Computer won") def play_game(): print(logo) user_cards = [] computer_cards = [] for _ in range(2): user_cards.append(draw_card()) computer_cards.append(draw_card()) game_end = False while not game_end: user_score = calculate_score(user_cards) computer_score = calculate_score(computer_cards) print(f" Your cards: {user_cards}, your score: {user_score}.") print(f" Computer's first card: {computer_cards[0]}") # 用户拿到Blackjack或爆牌时提前结束回合 if user_score == 0 or user_score > 21: game_end = True else: get_card = input("Type 'y' to get another card, type 'n' to pass: ") if get_card.lower() == "y": user_cards.append(draw_card()) else: game_end = True # 电脑按规则补牌(分数<17且未拿到Blackjack) while computer_score != 0 and computer_score < 17: computer_cards.append(draw_card()) computer_score = calculate_score(computer_cards) print(f" Your final hand: {user_cards}, final score: {user_score}") print(f" Computer's final hand: {computer_cards}, final score: {computer_score}") compare(user_score, computer_score) play = input("Do you want to play a game of blackjack. Type y or n: ").lower() while play == "y": clear() play_game() play = input("Do you want to play again? Type y or n: ").lower()
额外优化说明
- 新增用户拿到Blackjack或爆牌时提前结束回合的逻辑,符合21点规则
- 电脑补牌逻辑移到用户回合结束后,流程更合理
- 添加游戏结束后再玩一次的询问
内容的提问来源于stack exchange,提问作者Vahaj Qureshi
相关产品推荐
相关产品推荐

