我想做一个筷子游戏。这里有一个维基百科链接到游戏https://en.wikipedia.org/wiki/Chopsticks_(hand_game)。到目前为止,我只是添加了一些方法,以便一只手可以使用“攻击”方法攻击另一只手。我觉得我写的代码非常冗长,丑陋,甚至可能是错误的。我怎样才能写得更优雅呢
class game:
def __init__(self):
self.x_left = 1
self.x_right = 1
self.o_left = 1
self.o_right = 1
def set_x_left(self, num):
self.x_left = num
def set_x_right(self, num):
self.x_right = num
def set_o_left(self, num):
self.o_left = num
def set_o_right(self, num):
self.o_right = num
def dict_func(self, hand):
self.func= {'x_left': self.set_x_left, 'x_right': self.set_x_right,
'o_left': self.set_o_left, 'o_right': self.set_o_right}
return self.func[hand]
def dict_hand(self, hand):
self.hands = {'x_left': self.x_left, 'x_right': self.x_right,
'o_left': self.o_left, 'o_right': self.o_right}
return self.hands[hand]
def attack(self, from_hand, to_hand):
self.dict_func(to_hand)(self.dict_hand(from_hand) + self.dict_hand(to_hand))
您的代码似乎有一些不必要的方法。您可以去掉用数字设置变量的方法:
创建游戏实例时,可以使用点符号设置值:
正如你所看到的,它打字更快,不需要任何方法。只是属性赋值。这样做会影响
dict_func
方法,因此可以创建匿名函数:实际上,您可以在
__init__
中声明self.func
self.hands
属性,以确保它们只被分配一次。然后在函数中只需写return self.func[hand]
你的
dict_hand
方法也有点过于复杂。您的目标是从实例dict获取属性,因此可以执行以下操作:(您可能需要重命名此函数:))
相关问题 更多 >
编程相关推荐