首页 > 解决方案 > 为什么这不会输出 diceroll2 函数?

问题描述

我正在为我的计算机科学 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 而不是什么都不输出吗?

标签: pythonpython-3.x

解决方案


  • 您正在尝试使用类名来调用类实例方法player1.rolls(),而不是那样,您应该做的是使用类的对象来做到这一点。
p1 = player1()
p1.rolls()
  • 一个类player对于您的代码就足够了,您不需要两个相同的类,并在其上调用两个实例(感谢@khelwood)
  • dicerollp1并且dicerollp2可以在类中移动,也许通过添加一个附加属性player_number
  • 您也许可以更改player1.rolls += -1player1.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=0and p2.rolls=5,因此p1.rolls > p2.rolls将是 false 并且 if 不会被执行,因此输出将是

foo1
foo1
foo1
foo1
foo1

推荐阅读