[英]How am I to get all the connections?
I am creating a platformer in pygame in which the levels are connected to eachother. 我在pygame中创建了一个平台,其中的关卡相互连接。 (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. 在循环的最后一次,仅使用
newLevels
更新levels
。 (You would have been able to easily spot this if you had stepped through this code in the Python debugger .) (如果您在Python调试器中逐步执行了此代码,则可以轻松发现这一点。)
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.