我正在创建一个 python 应用程序来玩游戏 Perudo(或说谎者的骰子)。
我正在尝试创建一个函数来计算允许玩家(或 AI)进行的所有可能移动并返回它们的列表,以便它可以拒绝非法移动。
转数存储为 2 个数字的列表,例如[10,6] 代表十个六。
如果起始变量 currentbid
是 [19,3]
(十九个三)并且有 20 个骰子在玩,那么唯一可能的移动是 19 个四,19 个五,19六、20 个二、20 个三、20 个四、20 个五和 20 个六。不允许调用 ones。
该程序应将以上内容输出为:
[[19,4],[19,5],[19,6],[20,2],[20,3],[20,4],[20,5],[20,6]]
而是将其输出为:
[[20,6],[20,6],[20,6],[20,6],[20,6],[20,6],[20,6],[20,6]]
我做错了什么?
def calcpossiblemoves(self, currentbid, totalnoofdice):
self.possiblemoves = [] # Create a list of possible moves that will be added too
self.bid = currentbid
while self.bid[0] <= totalnoofdice:
while self.bid[1] < 6:
self.bid[1] += 1
self.possiblemoves.append(self.bid) # <- I think the problem is something to do with this line
print(self.possiblemoves) #For tracking the process
# Increase 1st number, reset 2nd number to 1
self.bid[0] += 1
self.bid[1] = 1 # Which will get increased to 2
#print("Reached 6")
return self.possiblemoves
最佳答案
问题是您正在使用 list
s,它们是可变对象,您正在创建引用,而不是副本。您可以通过复制 self.bid
来修复它每次都列出,但最“pythonic”的解决方案是不使用 list
, 但要使用 tuple
s,而是:
def calcpossiblemoves(self, currentbid, totalnoofdice):
possiblemoves = []
numberof, value = currentbid
while numberOf <= totalnoofdice:
while value < 6:
value += 1
possiblemoves.append((numberOf, value))
# Increase 1st number, reset 2nd number to 1
numberof += 1
value = 1 # Which will get increased to 2
#print("Reached 6")
return self.possiblemoves
请注意,这不会更新 self.bid
(但你可以很容易地添加它),你会得到一个 list
不可变的 tuple
编辑:因为tuple
s 是不可变的,我使用元组拆包 来创建两个变量。这是为了防止出现以下问题:
>>> bid = (1, 2)
>>> bid[0] += 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
我可以写 bid = (bid[0]+1, bid[1])
,但是使用两个变量,恕我直言,更容易理解。
通常,确保 list
的所有成员都是一个很好的经验法则。 s 表示相同的东西,而 values 表示不同的东西在 tuple
中s 或 dict
s,或自定义容器,例如 NamedTuple
或自定义类。
在此示例中,外部 list
包含许多出价,但每个内部 list
s 有一个骰子数和一个值,表示 list
可能是错误的类型。
关于python - 将微型列表 append 到更大的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39027187/