我对编程很陌生,而且我有一个For循环,应该一个接一个地运行我游戏的所有级别。
var level = 1
for stage in stages {
runLevel(level, stageDef: stage) { _ in
if level < stages.count {
print("Skipping to level \(level + 1)")
level += 1
}
}
}
每个级别由runLevel函数运行,该函数在操作结束时提供回调。
我想知道如何设置这个For循环,以便在迭代到下一级之前等待回调。
目前,我的问题是第一级重复的次数与级别数一样多,几乎同时是因为循环在跳到下一次迭代之前没有等待一个级别完成。
另外,如果您认为我的For循环方法不是最合适的话,请随时告诉我。
这是runLevel函数
func runLevel(levelId: Int, stageDef:Dictionary<String, String>, completionBlock:(completed: Bool)->()) {
var helicoAction = SKAction()
var herculeAction = SKAction()
var mirageAction = SKAction()
print("Processing level \(levelId)")
self.levelLabel.text = "Level \(levelId)"
if let strNbHelico = stageDef["helicopter"] {
if let nbHelico = Int(strNbHelico) {
print("nbHelico: \(nbHelico)")
helicoAction = SKAction.repeatAction(SKAction.sequence([SKAction.waitForDuration(NSTimeInterval(3), withRange: NSTimeInterval(3)),SKAction.runBlock(addHelico2)
]), count: nbHelico)
}
}
if let strNbHercule = stageDef["hercule"] {
if let nbHercule = Int(strNbHercule) {
print("nbHercule: \(nbHercule)")
herculeAction = SKAction.repeatAction(SKAction.sequence([SKAction.runBlock(addHercule),
SKAction.waitForDuration(NSTimeInterval(3), withRange: NSTimeInterval(5))
]), count: nbHercule)
}
}
if let strNbMirage = stageDef["mirage"] {
if let nbMirage = Int(strNbMirage) {
print("nbMirage: \(nbMirage)")
mirageAction = SKAction.repeatAction(SKAction.sequence([SKAction.runBlock(addHercule),
SKAction.waitForDuration(NSTimeInterval(3), withRange: NSTimeInterval(5))
]), count: nbMirage)
}
}
let groupedActions = SKAction.group([helicoAction, herculeAction, mirageAction])
runAction(SKAction.sequence([groupedActions,SKAction.waitForDuration(1)]), completion: {
print("action completed")
completionBlock (completed: true)
})
}
感谢您的帮助
答案 0 :(得分:1)
为此你可以创建像这样的函数
func perfomSomethinOn(lavel: Int) {
runLevel(level, stageDef: stage) { _ in
if (level + 1) < stages.count {
print("Skipping to level \(level + 1)")
self.perfomSomethinOn(lavel + 1)
}
}
}
现在像这样调用这个函数
self.perfomSomethinOn(1)