如何在方法中只运行一次特定条件?

时间:2018-01-23 21:58:15

标签: python python-3.x

我只想在第一次运行方法时将val设为0,但我无法找到实现此目的的方法。第一次运行该方法时,roll的值等于该值,然后用户必须滚动该值加1。如果用户没有滚动下一个值,那么您已经滚动了{}但需要滚动{}'被展示。如果他们得到正确的卷,那么你就得到了它!下一个值是{}'将会显示。

def roll(self):
        'primary game play'
        ds.shake()
        rolled = ds.getTotalRoll()
        while True:
            val = 0
            if val == 0:
                rolled = val
                val += 1
                return 'You got it! Next value is {}'.format(val)
                break
        if rolled == val:
            val +=1
            self.count += 1
            return 'You got it! Next value is {}'.format(val)
        else:
            self.count += 1
            return 'You rolled a {} but needed to roll a {}'.format(rolled, val)

1 个答案:

答案 0 :(得分:0)

将其设为对象属性并在构造函数中设置它。

def __init__(self):
    self.val = 0
    ...

def roll(self):
    'primary game play'
    ds.shake()
    rolled = ds.getTotalRoll()
    while True:
        if self.val == 0:
            rolled = self.val
            self.val += 1
            return 'You got it! Next value is {}'.format(self.val)
            break
    if rolled == self.val:
        self.val +=1
        self.count += 1
        return 'You got it! Next value is {}'.format(self.val)
    else:
        self.count += 1
        return 'You rolled a {} but needed to roll a {}'.format(rolled, self.val)