我刚开始一个二十一点游戏项目。到目前为止,我已经创建了卡片和手创建器功能。正如您从下面的代码中看到的那样,我通过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
我想知道这段代码是否获得了它们的值,如果没有,我如何获得它们的值?这也是编码二十一点游戏的好方法。
答案 0 :(得分:1)
变量values
没有连接任何东西,因此在尝试引用它时会得到一个NameError
。
列表your_hand
和opponent_hand
包含字符串列表(rank
中的键)。要将其转换为rank
中的值,您需要使用键进行查找,例如:
your_hand_values = [rank[card] for card in your_hand]
,这将为您提供int
的列表。如果要获取总和,可以使用sum
:
your_hand_total = sum(rank[card] for card in your_hand)
关于一个更大的问题,这种方法的一个问题是,一只手不可能拥有同一等级的一张以上的牌,而一副真实的牌有4套花色。
由于制作二十一点游戏是一个很常见的初学者编码问题,因此当有人问我要怎么做时,我会将这篇文章加为书签。 :) https://codereview.stackexchange.com/questions/234880/blackjack-21-in-python3/234890#234890
答案 1 :(得分:0)
将字典传递给list()将返回键的列表。所以your_hand是一个列表,其中包含排名字典的键。要获取相应的值 :
your_hand_values = [rank[card] for card in your_hand]
您可能会考虑从一开始就将卡片及其值存储在your_hand列表中,如下所示:
your_hand = [(card, value) for card, value in random.sample(rank.items(), 2)]
(作为一个旁注,这是一个寻求OOP方法的项目。只需2美分。)