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

2024-04-24 05:31:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我想让21-34行的这些while循环交替(一个结束,另一个开始),但一个简单地停止,下一个不运行。你知道吗

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

Tags: rectselfrightfalsetruereturnifdef
2条回答

在循环内调用return将中断函数/方法的执行,并将值返回给调用者。你知道吗

因此,一旦第一个循环返回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.

如果您只希望第一个循环、第二个循环和exit不需要嵌套它们,只需从函数中删除return调用即可。你知道吗

相关问题 更多 >