Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python 21点游戏中获得密钥值_Python_List_Dictionary_Random_Blackjack - Fatal编程技术网

如何在Python 21点游戏中获得密钥值

如何在Python 21点游戏中获得密钥值,python,list,dictionary,random,blackjack,Python,List,Dictionary,Random,Blackjack,我刚开始一个21点游戏项目。到目前为止,我已经创造了卡片和手工制作功能。正如您从下面的代码中所看到的,我通过pick()函数选择我的手,并获得秩字典的键 rank={'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'J':10, 'K':10,'Q':10,'A':1} your_hand=[] opponent_hand=[] def pick(): your_hand = random.sample(li

我刚开始一个21点游戏项目。到目前为止,我已经创造了卡片和手工制作功能。正如您从下面的代码中所看到的,我通过pick()函数选择我的手,并获得秩字典的键

rank={'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'J':10,
   'K':10,'Q':10,'A':1}
your_hand=[]
opponent_hand=[]
def pick():    
    your_hand =  random.sample(list(rank),2) 
    opponent_hand = random.sample(list(rank),2) 
    print(your_hand[values])
    print(opponent_hand)
def count():
    pass
我想知道这段代码是否得到了它们的值,如果没有,我如何才能得到它们的值?这也是编写21点游戏的好方法。

将dict传递给list()会返回一个键列表。因此,您的手是一个列表,包含排名字典的键。要获取相应的值,请执行以下操作:

你可以考虑从一开始就把卡和它的值存储在You-Help列表中,像这样:

your_hand =  [(card, value) for card, value in random.sample(rank.items(), 2)]

(作为旁注,这是一个迫切需要OOP方法的项目。只需我的2美分。)

变量
与任何东西都没有连接,因此当您尝试引用它时,会出现
名称错误

列表
你的手
对手手
包含字符串列表(键在
等级
)。要将这些值转换为
rank
中的值,您需要使用键进行查找,例如:

your_hand_values = [rank[card] for card in your_hand]
这将为您提供
int
s的列表。如果您想获得总和,可以使用
sum

your_hand_total = sum(rank[card] for card in your_hand)
关于更大的问题,这种方法的一个问题是,一手牌不可能有多张相同等级的牌,因为一副真正的牌有4套


由于构建21点游戏是一个非常常见的初学者编码问题,所以当有人问我该如何做时,我会将这篇文章作为书签保存

关于21点规则的注释:默认情况下ace值为11。From:一张牌的A值为11的牌被称为“软牌”,这意味着该牌不会因为额外的一张牌而破裂。ace的值将变为1,以防止手部超过21。否则,这手牌就叫做“硬牌”。我看到的一个问题是,在一场游戏中,两名玩家都有相同的牌。为了解决这个问题,我建议先删除第一个玩家从ramk收到的牌,然后再为第二个玩家挑选牌
your_hand_total = sum(rank[card] for card in your_hand)