首页 > 解决方案 > Pygame for-loop 只运行一次

问题描述

我正在制作一个平台游戏。我有一个平台列表,然后是一个“for platform in platform_list:”,即使有两个或更多平台,for 循环也只运行一次。我有另一个文件,我在其中存储平台类和 make_platform() 函数。

###### platformer_main.py #######
from platform import make_platform

def platform_handler():
    print(len(platform_list)) # even if this prints out 2, the for loop still only runs once
    for platform in platform_list:
        pygame.draw.rect(window, green, (platform.x, platform.y, platform.w, platform.h))  # draw

        platform.x -= platform.speed  # move to the left
        if platform.done == False:  # add next platform
            if platform.x <= 650:
                platform.done = True
                add_platform()

        if platform.x + platform.w <= 0:  # delete platform
            platform_list.remove(platform)
            return platform_list
        # character collision detection
        if charac.x + charac.w >= platform.x and charac.x <= platform.x + platform.w and charac.y + charac.h >= platform.y and charac.y <= platform.y + platform.h:
            charac.fall = False
        else:
            charac.fall = True
        return charac
###### platform.py #####

class Platform:
    def __init__(self):
        self.x = 0
        self.y = 0
        self.w = 0
        self.h = 0
        self.speed = 0
        self.done = 0


def make_platform():
    platform = Platform()

    platform.x = 1000
    platform.y = random.randrange(200, 600)
    platform.w = random.randrange(300, 500)
    platform.h = 20
    platform.done = False
    platform.speed = 5

    return platform

不会出现错误消息。

标签: pythonfor-looppygame

解决方案


return导致函数返回,停止任何正在进行的循环。


推荐阅读