我正在为我的计算机科学GCSE制作回合制骰子游戏,无法理解为什么程序的某些部分无法运行或至少无法输出。
class player1:
def __init__(self):
self.rolls = 5
class player2:
def __init__(self):
self.rolls = 5
def dicerollp1():
print("foo")
def dicerollp2():
print("2foo")
while player1.rolls > 0 and player2.rolls > 0:
dicerollp1()
player1.rolls += -1
if player1.rolls > player2.rolls:
dicerollp2()
player2.rolls += -1
是否应该输出2foo而不是什么?
答案 0 :(得分:1)
player1.rolls()
,而不是那样,您应该做的是使用类的对象来执行此操作。 p1 = player1()
p1.rolls()
player
就足够了您的代码,您不需要两个相同的类,并在其上调用两个实例(感谢@khelwood)dicerollp1
和dicerollp2
可以在类中移动,也许可以通过添加其他属性player_number
player1.rolls += -1
更改为player1.rolls -= 1
重构后的代码看起来像#One player class
class player:
#Player number as attribute to diceroll
def __init__(self, player_number):
self.rolls = 5
self.player_number = player_number
#One diceroll function
def diceroll(self):
print("foo{}".format(self.player_number))
#Instantiate object of class player
p1 = player(1)
p2 = player(2)
#Use them in the logic
while p1.rolls > 0 and p2.rolls > 0:
#Refer to p1's diceroll
p1.diceroll()
p1.rolls += -1
if p1.rolls > p2.rolls:
# Refer to p2's diceroll
p2.diceroll()
p2.rolls += -1
也在while循环之后,p1.rolls=0
和p2.rolls=5
,因此p1.rolls > p2.rolls
将为false,if将不被执行,因此输出为
foo1
foo1
foo1
foo1
foo1