Python は私の最初の言語であり、私はそれに非常に慣れていないため、答えは非常に明確かもしれませんが、何時間も見て実験した後、何が問題を引き起こしているのかわかりません。
モジュールの概要: DicePool モジュールは、辞書項目として格納された「サイコロ」のコレクションを管理するためのものです。各ディクショナリ キー (ここでは poolKey) には、1 つの「タイプ」のサイコロに関する情報を含むリストがあります。最も重要なのは、その面を記述するタプルと、「プール」内の「サイコロ」タイプ「x」の数量を表す整数です。
私の特定の質問は、Transfer メソッドに関するものです。これは、以前は 2 つのメソッド (基本的に送信と受信) でしたが、1 つのメソッドに組み合わせることができると思いました。一番下のテスト コードを実行すると、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)