swift - 如何在 Swift 中同时运行定时器和 AI 逻辑

标签 swift sprite-kit artificial-intelligence nstimer

我有一个 NSTimer() 和一个棋盘游戏的 AI 逻辑。 AI 逻辑需要很长时间来处理大约 3 到 5 秒(这没问题)。当程序执行 AI 逻辑时,NSTimer 不会触发,直到 AI 逻辑完成执行。

这就是我在游戏初始阶段启动计时器的方式。

    public var timer = NSTimer()

...

    let timeSelector:Selector = "timerFired"
    if self.useTime {
       timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: timeSelector, userInfo: nil, repeats: true)
    }

我在 SKScene 的更新中添加了 AI 逻辑,以便当它检测到轮到他时,他将开始检查可用的 Action

override func update(currentTime: CFTimeInterval) {
      if gameStatus.playerTurn == "AI" && !aiThiking {
         aiThiking = true
         aIPlayer.aiCheckAvaialbleMoves()
         // executeMove
         // change Turn
         aiThiking = false
      }

我的问题是,有没有可能让AI逻辑执行的同时让定时器还在运行?

最佳答案

您的问题似乎是 aIPlayer.aiCheckAvailableMoves() 会在应用程序执行时卡住应用程序,因此 NSTimer 无法正常工作。您可以使用不同的线程来避免这种情况:

dispatch_async(dispatch_get_global_queue(priority, 0)) {
    aIPlayer.aiCheckAvaialbleMoves()
}

此代码在新线程中运行此函数,当代码结束时,线程会自动关闭。

您可以使用完成 block 来准确知道函数何时结束。这是一个例子:

func aiCheckAvailableMoves(completion : (result : BOOL) -> Void) {
   dispatch_async(dispatch_get_global_queue(priority, 0)) {
       //Do your code normally

       //When you have finished, call the completion block (like a return)
       completion(true)
   }
}

然后,从你的update:你会得到函数结束的时间(请注意这里没有dispatch_async):

aIPlayer.aiCheckAvailableMoves(){
    //Finished checking moves, maybe schedule again?
}

小心线程,因为它们可能导致意外行为或/和崩溃!

关于swift - 如何在 Swift 中同时运行定时器和 AI 逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31873919/

相关文章:

python - Q-Learning AI 无法识别简单的模式

ios - 如何在 Swift 的 UIAlertController 中为 addTextField 设置默认文本

ios - 使用触摸滚动 SpriteNode

java - 神经网络激活/输出

matlab - matrix(256*256) 的行列式可能是无限的

xcode - 重命名 XCode 项目,现在应用程序将无法加载

ios - 数据未从 JSON Swift 获取

ios - 如何使用 Alamofire 4 以字节为单位获取下载进度?

java - 使用全局变量而不是通过 segue 将值推送到下一个 Activity/ View

swift - 为什么我的 SKTileMapNode 类型的对象没有被解码?