所以我正在嘗試制作一個回合制紙牌游戲,其中一張紙牌在玩時可以交換“施法者”和“施法者”的手(不確定這是否是一個詞)。我創建了一個Player類和實體Jim,Pam,Dwight和Michael。每當打出那張牌時,我必須hand在兩個玩家之間交換屬性。
class Player:
def __init__(self, name, hand=[]):
self.name = name
self.hand = [self.draw_card() for n in range(0, 2)]
我試過創建一個方法,它接受“castee”,self在這種情況下是“castee” ,并與腳輪交換手,但它不起作用。這caster是另一個實體的名稱,例如它可以Michael.hand代替caster.hand:
def hand_swap(self):
self.hand, caster.hand = caster.hand, self.hand
我也嘗試了以下但沒有運氣:
def hand_swap(self):
myhand = self.hand.copy()
casterhand = caster.hand.copy()
setattr(caster, "hand", myhand)
setattr(self, "hand", casterhand)
每次回圈后,玩家和他們的手都會被列印在字典中。代碼沒有拋出任何錯誤,但沒有換手,一切都保持不變。
我的代碼是否有問題,或者在讓一個實體更改另一個實體的屬性時不是那么簡單?
edit1:什么是“caster” edit2:我如何檢查它是否失敗
uj5u.com熱心網友回復:
如果您添加caster到hand_swap()您將實作您的目標。
def hand_swap(self, caster):
self.hand, caster.hand = caster.hand, self.hand
然后交換手
pam.hand_swap(michael)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/356504.html
上一篇:訪問類中的屬性
