python练习游戏,在循环之间切换的问题



我想要这些时在第21-34行上的循环替代(一个结束时,下一个开始(,但一个人只是停止而下一个不运行。

def update(self):
    mv_p = False
    while not mv_p:
        self.rect.x -= 5
        if self.rect.left > width - 750:
            mv_p = True
            return mv_p
            break
    while mv_p:
        self.rect.y += 5
        if self.rect.right < width - 750:
            mv_p = False
            return mv_p
            break

循环内部的呼叫返回将破坏函数/方法执行并返回到呼叫者。

所以,一旦第一个循环返回mv_p,您的方法调用就结束了。

如果您要它们交替(第一个循环,第二个循环,第一个循环,第二个循环等(,则应将它们嵌套在另一个循环中。

def update(self):
    mv_p = False
    while True:
        while not mv_p:
            self.rect.x -= 5
            if self.rect.left > width - 750:
                mv_p = True
                break
        while mv_p:
            self.rect.y += 5
            if self.rect.right < width - 750:
                mv_p = False
                break
        #need to draw on the screen here or nothing will be shown
        #add condition to exit the function, adding for example a return
        #inside af if, otherwise this will be an infinite loop.

相反,如果您只想第一个循环,第二个循环和退出无需嵌套,只需从您的功能中删除return调用。

最新更新