Swift中的多个延迟

时间:2016-02-19 22:43:35

标签: ios swift delay timedelay

我正在制作一个简单的纸牌游戏,玩家按下按钮后,三台AI计算机将一个接一个地转动。但是,我需要在每个回合之间有一个停顿。

这就是我需要的:

  

playerButton>暂停> computer1Goes>暂停> computer2Goes>暂停> computer3Goes

代码:

@IBAction func placeCardAction(sender: UIButton) {

    // playerButton does this action
    var playerCardOnTop = game!.player.deck.placeCard()
    middleDeck.addSingleCard(playerCardOnTop)
    updateCardCount()

    // Start computer actions
    let delay = 2.0 * Double(NSEC_PER_SEC)
    let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
    dispatch_after(time, dispatch_get_main_queue()) {
        self.game?.computer1PlacesCard(&self.middleDeck)
        self.updateCardCount()
    }

    let delay2 = 2.0 * Double(NSEC_PER_SEC)
    let time2 = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
    dispatch_after(time2, dispatch_get_main_queue()) {
        self.game?.computer2PlacesCard(&self.middleDeck)
        self.updateCardCount()
    }

    let delay3 = 2.0 * Double(NSEC_PER_SEC)
    let time3 = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
    dispatch_after(time3, dispatch_get_main_queue()) {
        self.game?.computer3PlacesCard(&self.middleDeck)
        self.updateCardCount()
    }
}

不幸的是,所有延迟同时开始/结束,所以最终发生的是所有计算机功能同时运行而不是一个接一个地轮流。

如果有人可以帮助解决这个问题,我将不胜感激!

3 个答案:

答案 0 :(得分:0)

最简单的解决方案......将延迟2改为4,将延迟3改为6.现在它们当然都在同一时间,所有都有相同的延迟。

或者,将它们堆叠起来:

NESTED LOOP

答案 1 :(得分:0)

我建议使用可以执行placeCard功能的计算机对象数组

@IBAction func placeCardAction(sender: UIButton) {

    // playerButton does this action
    var playerCardOnTop = game!.player.deck.placeCard()
    middleDeck.addSingleCard(playerCardOnTop)
    updateCardCount()

    self.computersPlaceCards(0)
}

private func computersPlaceCards(i: Int) {
    if self.game == nil || i >= self.game!.computers.count {
        return
    }

    let delay = 2.0 * Double(NSEC_PER_SEC)
    let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
    dispatch_after(time, dispatch_get_main_queue()) {
        self.game?.computers[i].placeCards(&self.middleDeck)
        self.updateCardCount()

        self.computersPlaceCards(i+1)
    }
}

答案 2 :(得分:0)

您可以在dispatch_async中使用sleep()

dispatch_async( dispatch_get_global_queue( QOS_CLASS_USER_INTERACTIVE, 0 ) ) {
    dispatch_async(dispatch_get_main_queue()) {
        print("first")
    }
    sleep(1)
    dispatch_async(dispatch_get_main_queue()) {
        print("second")
    }
    sleep(1)
    dispatch_async(dispatch_get_main_queue()) {
        print("third")
    }
    sleep(1)
    dispatch_async(dispatch_get_main_queue()) {
        print("fourth")
    }
}

(我之前使用的答案是NSOperationQueue - 要么会起作用)