Skip to main content
 首页 » 编程设计

python 二十一点游戏,似乎忽略了 'if' 声明

2025年05月04日13cmt

我一直在尝试用 python 制作一个简单的二十一点游戏,但我似乎被卡住了,我的代码如下:

from random import choice 
 
def deck(): 
    cards = range(1, 12) 
    return choice(cards) 
 
def diack(): 
    card1= deck() 
    card2 = deck() 
    hand = card1 + card2 
    print hand 
    if hand < 21: 
         print raw_input("Would you like to hit or stand?") 
         if "hit": 
             return hand + deck() 
         elif "stand":  
             return hand 

当我运行它时,它似乎适用于“命中”,但当我输入“站立”时,它似乎也适用于“命中”。正如您现在可能知道的那样,我对编程非常陌生。你们能帮我指出正确的方向,让我知道如何让我的游戏运行吗(我想尽可能多地使用我的代码)。

请您参考如下方法:

if "hit" 只是测试字符串 "hit" 是否存在,它确实存在。因此,永远不会执行 elif 语句。

您需要将用户输入捕获到一个变量中并对其进行测试:

choice = raw_input("Would you like to hit or stand?") 
print choice 
if choice == "hit": 
    return hand + deck() 
elif choice == "stand":  
    return hand