繁体   English   中英

我如何获得所有连接?

[英]How am I to get all the connections?

我在pygame中创建了一个平台,其中的关卡相互连接。 (一个级别是一个屏幕,您可以通过离开屏幕进入下一级别)。

我目前拥有它,它可以在走出屏幕后从文件中加载连接的关卡,但这显然很慢,因此我想预加载所有关卡。 为此,我想获得一个根级别,获取它连接的所有级别,获取每个级别所连接的所有级别,依此类推,直到获得所有级别为止。

我编写此代码是为了这样做,但是它不起作用。 我很累的时候就写了。 谁能帮我这个? 如有必要,我将回答其他问题。

def loadLinkedLevels(level, surface, ignoredIds = []):
    levels = {}

    for levelId in level.warps.values():
        if levelId and levelId not in ignoredIds:
            levels[levelId] = LevelBuilder.loadLevel(levelId, surface)

    return levels

def getBranchingLevels(levels, p):
    newLevels = True # Do-while

    while newLevels:
        for level in levels.values():
            newLevels = loadLinkedLevels(level, p.screen, levels.keys())

        levels.update(newLevels)

        return levels

def preloadLevels(rootLevel, p):
    levels = loadLinkedLevels(rootLevel, p.screen)
    newLevels = {}

    for level in levels.values():
        newLevels.update(loadLinkedLevels(level, p.screen, levels.keys()))

    levels.update(newLevels)

    levels.update(getBranchingLevels(levels, p))

    return levels

突出的错误在这里:

for level in levels.values():
    newLevels = loadLinkedLevels(level, p.screen, levels.keys())

levels.update(newLevels)

在循环的最后一次,仅使用newLevels更新levels (如果您在Python调试器中逐步执行了此代码,则可以轻松发现这一点。)

但总的来说,您的代码似乎太复杂了。 您正在尝试搜索从根开始的级别图。 那么,为什么不使用简单的广度优先搜索算法呢? 像这样:

from collections import deque

def load_all_levels(root, p):
    """Load all levels reachable from `root`.
    Return a dictionary mapping level id to level.
    """
    # Queue of levels that have been loaded but whose neighbours have not.
    q = deque([root])
    # Map from level id to level for all levels loaded so far.
    loaded = {root.id: root}
    while q:
        for level_id in q.popleft().warps.values():
            if level_id not in loaded:
                level = LevelBuilder.loadLevel(level_id, p.screen)
                loaded[level_id] = level
                q.append(level)
    return loaded

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM