我在python中制作一个简单的二十一点模拟器,以习惯面向对象的编程和练习计数卡。到目前为止,模拟器看起来像这样
import random
cardvalues = {"1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7,
"8": 8, "9": 9, "10":10, "J": 10, "Q": 10, "K": 10, "A": 11}
class Shoe(object):
def __init__(self):
amount = input("how many decks do you want in the shoe?\n>")
self.shoe = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"] * amount * 4
self.shoe = random.shuffle(self.shoe)
def deal(self):
pcard1 = self.shoe.pop()
pcard2 = self.shoe.pop()
comcard1 = self.shoe.pop()
comcard2 = self.shoe.pop()
handworth = cardvalues[pcard1] + cardvalues[pcard2]
print "You have been dealt a {} and a {}. The value of your cards is {}".format(pcard1, pcard2, hadworth)
print "The dealer has a {} and an other card that's faced down.".format(comcard1)
class play(object):
def __init__(self):
print "welcome to blackjack simulator!"
print "You shall be playing at a 100 dollar minimum table, with a wallet of $5000,00"
my_shoe = Shoe()
my_shoe.deal()
if __name__ == '__main__':
play()
,错误是
AttributeError: 'NoneType' object has no attribute 'pop'
我很快发现这里的问题是该行
self.shoe = random.shuffle(self.shoe)
将我的整个self.shoe列表变为无,而不是将其改组。有人可以解释为什么会发生这种情况以及如何解决它?
没关系,我自己解决了这个问题。事实证明,我使用了random.shuffle命令错误。当我删除“self.shoe =”时,它运行没有错误。
答案 0 :(得分:2)
由于__init__的输入错误为_init_,因此永远不会调用构造函数,因此永远不会设置属性self.shoe。因此,当执行deal()时,该属性不存在
答案 1 :(得分:-2)
import random
cardvalues = {"1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7,
"8": 8, "9": 9, "10":10, "J": 10, "Q": 10, "K": 10, "A": 11}
def deal():
cards, values = zip(*random.sample(cardvalues.items(), 2)))
print("You have been dealt a {} and a {}. The value of your cards is {}".format(*cards, sum(values)))
好的,我在评论中指出了原始问题,所以我不会重复自己(除了OP已经修复了)。 至于为什么我展示了另一种解决方案 - 因为它更好。怎么样?
self.shoes
)总而言之 - 让您的代码更好地观看链接中的视频,而不是在不需要的情况下制作课程。使用random.sample
而不是创建列表,将其洗牌然后从中弹出。当然使用python3!