How to run timer and AI logic in Swift at the same time

I have NSTimer () and AI logic for a board game. The AI ​​logic takes a long time to process from 3 to 5 seconds (this is normal). When a program is executing AI logic, the NSTimer will not fire until the AI ​​logic has finished executing.

This is how I started the timer early in the game.

    public var timer = NSTimer()

      

...

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

      

I added the AI ​​logic to "SKScene Update" so that when its queue is found, it will start checking for available moves.

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

      

My question is, is it possible to run the AI ​​logic and let the timer still run at the same time?

+3


source to share


1 answer


Your problem seems to be that aIPlayer.aiCheckAvailableMoves()

the application hangs while it is running, so it NSTimer

doesn't work as expected. You can use different ones threads

to avoid this:

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

      

This code runs this function on a new thread, and when the code ends, the thread is automatically closed.

You can use completion blocks to know exactly when a function has ended. Here's an example:



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)
   }
}

      

And then, from yours, update:

you get when the function ends (note that not here dispatch_async

):

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

      

Be careful with threads as they can cause unwanted behavior and / or crash!

0


source







All Articles