简体   繁体   中英

How am I to get all the connections?

I am creating a platformer in pygame in which the levels are connected to eachother. (one level is one screen, you move to the next level by walking off the screen).

I currently have it that it loads the connected level from it's file after walking offscreen, but this is obviously slow and as such I would like to pre-load all of the levels. I would like to do this by taking one root level, getting all the levels it is connected to, getting all the levels each of those levels are connected to and so on until I have all of the levels.

I wrote this code to do so, but it does not work. I wrote it when I was very tired. Can anyone help me with this? I'll answer any further questions if necessary.

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

The bug that stands out is here:

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

levels.update(newLevels)

levels only gets updated with newLevels on the last time round the loop. (You would have been able to easily spot this if you had stepped through this code in the Python debugger .)

But in general your code seems way too complex. You're trying to search the graph of levels starting at the root. So why not use a straightforward breadth-first search algorithm? Like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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