You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python字典实现Blackjack游戏:初始牌重复问题求助

修复Blackjack游戏初始牌数值相同的问题

我用Python字典开发了一款Blackjack游戏,但发现玩家与电脑的初始两张牌数值始终相同。以下是完整代码,并标记出疑似问题的代码段,希望得到修正帮助:

import random
from replit import clear

deck={
    "ace": 11,
    "jack":10,
    "queen": 10,
    "king":10,
    "one": 1,
    "Two":2,
    "Three": 3,
    "four": 4,
    "five": 5,
    "six": 6,
    "seven": 7,
    "eight": 8,
    "nine": 9,
}

def computer_draw():
  # for i in range(1):
  computerchoice= random.choice(list(deck.keys()))
  computerlist.append(deck[computerchoice])
  return sum(computerlist)


def user_draw():
  # for i in range(1):
  mychoice=random.choice(list(deck.keys()))
  mychoicelist.append(deck[mychoice])
  return sum(mychoicelist)


def calculate_score(deck):
  if sum(deck) == 21 and len(deck) == 2:
    return 0
  if 11 in deck and sum(deck) > 21:
    deck.remove(11)
    deck.append(1)
  return sum(deck)

  
def cal(userscore, computerscore):
  if userscore > 21 and computerscore < 21:
    return("you lose 😫")
  elif userscore < 21 and computerscore > 21:
    return("you win 😃")
  elif userscore==0:
    return("you win, Blackjack!😎")
  elif computerscore==0:
    return("computer wins, Blackjack!😎")
  elif userscore==computerscore:
    return("It`s a draw!😏")
  elif userscore==21:
    return("you win!😀")
  elif computerscore==21:
    return("you lose!😫")
  elif computerscore > userscore:
    return("You lose 🤯")
  else:
    return("you win 😃")


mychoicelist= []
computerlist= []
def play():

  is_game_over=False
  for i in range(1):
    mychoicelist.append(user_draw())
    computerlist.append(computer_draw())
    
  while not is_game_over:
    userscore=calculate_score(mychoicelist)
    computerscore=calculate_score(computerlist)
    print(f"User has {mychoicelist} with score of {userscore}")
    print(f"computer has {computerlist[0]}")
    if userscore==0 or computerscore==0 or userscore>21: 
      is_game_over= True
    else:
      decision=input("do you want to draw, Y or N? ").lower()
      if decision=="y":
        user_draw()
      else:
        is_game_over= True
        # print(f"user has {mychoicelist} with scores {userscore}")
        
  while computerscore != 0 and computerscore < 17:
    computer_draw()
    # computerlist.append(computer_draw())
    computerscore= calculate_score(computerlist)
  print(f"computer {computerlist} with score of {computerscore}")
  print(f"user {mychoicelist} with score of {userscore}")
  print(cal(userscore, computerscore))

while input("do you what to play blackjack game y or n: ")== "y":
  del mychoicelist[:]
  del computerlist[:]
  clear()
  play()

疑似问题代码段:

for i in range(1):
    mychoicelist.append(user_draw())
    computerlist.append(computer_draw())

问题根源

  1. 抽牌函数逻辑混乱:user_draw()和computer_draw()内部已经把抽到的牌值添加到对应列表,同时返回的是列表的当前总和。但你在play()的循环里,又把这个总和追加到列表中,导致列表里同时存在牌值和总和两种数据,完全破坏了数据结构。
  2. 初始发牌次数错误:range(1)只执行一次循环,无法完成"发两张初始牌"的需求,再加上错误追加的总和,最终导致初始牌显示异常,甚至出现数值相同的情况。

修复方案

步骤1:修正抽牌函数

让抽牌函数只负责抽牌并添加到列表,不需要返回总和(避免混淆):

def computer_draw():
    computerchoice = random.choice(list(deck.keys()))
    computerlist.append(deck[computerchoice])

def user_draw():
    mychoice = random.choice(list(deck.keys()))
    mychoicelist.append(deck[mychoice])

步骤2:修正初始发牌逻辑

初始需要给玩家和电脑各发2张牌,循环执行2次,直接调用抽牌函数即可,不需要追加返回值:

def play():
    is_game_over = False
    # 初始发2张牌
    for i in range(2):
        user_draw()
        computer_draw()
    
    # 后续逻辑保持不变...

额外优化(可选)

  • 移除全局列表,改为在play()函数内创建局部列表并传入抽牌函数,减少全局变量带来的潜在问题。
  • 统一牌的键名大小写(比如"Two"改为"two"),保持代码一致性。

修复后完整代码

import random
from replit import clear

deck={
    "ace": 11,
    "jack":10,
    "queen": 10,
    "king":10,
    "one": 1,
    "two":2,
    "three": 3,
    "four": 4,
    "five": 5,
    "six": 6,
    "seven": 7,
    "eight": 8,
    "nine": 9,
}

def computer_draw(computer_list):
    computerchoice = random.choice(list(deck.keys()))
    computer_list.append(deck[computerchoice])

def user_draw(user_list):
    mychoice = random.choice(list(deck.keys()))
    user_list.append(deck[mychoice])

def calculate_score(card_list):
    if sum(card_list) == 21 and len(card_list) == 2:
        return 0
    if 11 in card_list and sum(card_list) > 21:
        card_list.remove(11)
        card_list.append(1)
    return sum(card_list)

def cal(userscore, computerscore):
    if userscore > 21 and computerscore < 21:
        return("you lose 😫")
    elif userscore < 21 and computerscore > 21:
        return("you win 😃")
    elif userscore == 0:
        return("you win, Blackjack!😎")
    elif computerscore == 0:
        return("computer wins, Blackjack!😎")
    elif userscore == computerscore:
        return("It`s a draw!😏")
    elif userscore == 21:
        return("you win!😀")
    elif computerscore == 21:
        return("you lose!😫")
    elif computerscore > userscore:
        return("You lose 🤯")
    else:
        return("you win 😃")

def play():
    mychoicelist = []
    computerlist = []
    is_game_over = False
    
    # 初始发2张牌
    for i in range(2):
        user_draw(mychoicelist)
        computer_draw(computerlist)
    
    while not is_game_over:
        userscore = calculate_score(mychoicelist)
        computerscore = calculate_score(computerlist)
        print(f"User has {mychoicelist} with score of {userscore}")
        print(f"computer has [{computerlist[0]}]")
        if userscore == 0 or computerscore == 0 or userscore > 21: 
            is_game_over = True
        else:
            decision = input("do you want to draw, Y or N? ").lower()
            if decision == "y":
                user_draw(mychoicelist)
            else:
                is_game_over = True
        
    while computerscore != 0 and computerscore < 17:
        computer_draw(computerlist)
        computerscore = calculate_score(computerlist)
    print(f"computer has {computerlist} with score of {computerscore}")
    print(f"user has {mychoicelist} with score of {userscore}")
    print(cal(userscore, computerscore))

while input("do you want to play blackjack game y or n: ") == "y":
    clear()
    play()

内容的提问来源于stack exchange,提问作者Kossy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 23:26:05