Python 是我的第一语言,我对它很陌生,所以答案可能很清楚,但经过数小时的寻找和试验,我不确定是什么导致了问题。
模块概述:DicePool 模块用于管理“骰子”集合,存储为字典项。每个字典键(此处为 poolKey)都有一个列表,其中包含有关一种“类型”骰子的信息,最重要的是,一个描述其面的元组和一个表示“池”中“骰子”类型“x”的数量的整数。
我的具体问题是关于 Transfer 方法,它曾经是两种方法(基本上是发送和接收),但我认为我可以将它们组合成一种方法。当底部的测试代码运行时,我希望它离开 dp.dictPool[poolKey][1] == 0 和 dp2.dictPool[poolKey][1] == 2。但是在我所做的每一次尝试中, 值是一样的。抱歉,我无法更好地对这个问题进行分类。. . 我真的不知道问题是什么。
无论如何,Transfer 方法的一半应该为“发送者”实例运行,而另一半应该为“接收者”实例运行。
import random
class DicePool(object):
def __init__(self):
self.dictPool = {}
def AddDice(self, poolKey, faces = 6, quant = 1, color = "white"):
'''faces must be int or items 'a,b,c'; count must be int or def to 1'''
try: #if count is not an integer, it defaults to 1
quant = int(quant)
except:
print("Quant is not an integer, defaulting to 1")
quant = 1
try: #if faces is can be int, a list is built of numbers 1 to faces
faces = int(faces)
if faces < 2: #a 1 or 0-sided die breaks the program
faces = 2
tempList = []
for i in range(1, faces+1):
tempList.append(i)
faces = tempList
except: #if faces is not an integer, it is split into list items by ","
faces = faces.split(",")
if poolKey in self.dictPool.keys(): #if the key already exists in pool
self.dictPool[poolKey][1] += quant #add to the quantity,
else: #if the key does not already exist, set all attributes
self.dictPool[poolKey] = [faces, quant, color]
def Transfer(self, poolKey, targetPool, sendQuant, senderPool = None):
'''targetPool must be DicePool instance'''
if targetPool:
self.dictPool[poolKey][1] -= sendQuant
targetPool.Transfer(poolKey, None, sendQuant, self)
else:
try:
self.dictPool[poolKey][1] -= sendQuant
except:
self.dictPool[poolKey] = senderPool.dictPool[poolKey]
self.dictPool[poolKey][1] = sendQuant
dp = DicePool()
dp2 = DicePool()
dp.AddDice("d6")
dp.AddDice("d6")
dp.Transfer("d6",dp2,2)
print(dp.dictPool,dp2.dictPool)