我的代码似乎运行得太快

时间:2016-02-01 14:08:38

标签: ios swift nstimer

我正在编写一个西蒙风格的记忆游戏,游戏的阶段,程序向用户显示当前要记住的东西列表似乎立即运行。

我的想法是逐步浏览列表(在我将每个项目中的1个作为调试数据放入代码中)并在屏幕上更改一段时间的颜色然后移动到下一个。

我想用于内存数组中的每个项目,然后调用一个简单的过程来检查它是哪一个,然后在一段时间内改变颜色然后再回到原始状态。

如果我在测试更改颜色(灰色)和原始颜色之间放置中断,我在此处添加的代码将起作用。但由于某种原因,计时器看起来似乎没有用。

有什么想法吗?

import UIKit
import Foundation

var gameisrunning = false
var playererror = false
var memoryArray = [Int]()
var currentScore = 0

var timer = NSTimer()

class ViewController: UIViewController {

    @IBAction func startGameButton(sender: UIButton) {

        if gameisrunning == false {

            gameisrunning = true
            memoryArray.append(1) //for debug
            memoryArray.append(2) //for debug
            memoryArray.append(3) //for debug
            memoryArray.append(4) //for debug
            print(memoryArray) //for debug
            gameStart()

        } else {


        }

    }


    //these are to be implemented once i get the showing sequence sorted.

    @IBAction func redButton(sender: UIButton) {

    }

    @IBAction func greenButton(sender: UIButton) {

    }

    @IBAction func yellowButton(sender: UIButton) {

    }

    @IBAction func blueButton(sender: UIButton) {

    }

    @IBOutlet weak var redLabel: UILabel!
    @IBOutlet weak var greenLabel: UILabel!
    @IBOutlet weak var yellowLabel: UILabel!
    @IBOutlet weak var blueLabel: UILabel!
    @IBOutlet weak var scoreLabel: UILabel!

    func addAnotherItemToMemory () {

        // adds another item to the memory

        memoryArray.append(Int(arc4random_uniform(4)+1))
    }

    func gameStart () {

        // main body of game
        showPlayerTheMemory()
    }


    func showPlayerTheMemory () {

        // go through list and highlight the colors one at a time

        for eachItem in memoryArray {
            self.showColor(eachItem)
        }
    }


    func pauseForAWhile(length: Double) {

        timer = NSTimer.scheduledTimerWithTimeInterval(length, target:self, selector: nil , userInfo: nil, repeats: false)
        timer.invalidate()

    }


    func showColor(buttonItem: Int) {

        //check to see which color, change to grey (test color) and back to original after a set time.

        if buttonItem == 1  {

            self.redLabel.backgroundColor = UIColor.grayColor()
            pauseForAWhile(2)
            self.redLabel.backgroundColor = UIColor.redColor()
            print(buttonItem) //for debug

        } else if buttonItem == 2 {

            self.greenLabel.backgroundColor = UIColor.grayColor()
            pauseForAWhile(2)
            greenLabel.backgroundColor = UIColor.greenColor()
            print(buttonItem) //for debug

        } else if buttonItem == 3 {

            self.yellowLabel.backgroundColor = UIColor.grayColor()
            pauseForAWhile(2)
            yellowLabel.backgroundColor = UIColor.yellowColor()
            print(buttonItem) //for debug

        } else if buttonItem == 4 {

            self.blueLabel.backgroundColor = UIColor.grayColor()
            pauseForAWhile(2)
            blueLabel.backgroundColor = UIColor.blueColor()
            print(buttonItem) //for debug

        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

新的相关代码更改为:

func colorChange (){

    self.redLabel.backgroundColor = UIColor.redColor()
    self.blueLabel.backgroundColor = UIColor.blueColor()
    self.yellowLabel.backgroundColor = UIColor.yellowColor()
    self.greenLabel.backgroundColor = UIColor.greenColor()
}

func showColor(buttonItem: Int, length: Double) {

    //check to see which color, change to grey (test color) and back to original after a set time.

    if buttonItem == 1  {

        self.redLabel.backgroundColor = UIColor.grayColor()
        timer = NSTimer.scheduledTimerWithTimeInterval(length, target:self, selector: ("colorChange") , userInfo: nil, repeats: false)
        print(buttonItem) //for debug

    } else if buttonItem == 2 {

        self.greenLabel.backgroundColor = UIColor.grayColor()
        timer = NSTimer.scheduledTimerWithTimeInterval(length, target:self, selector: ("colorChange") , userInfo: nil, repeats: false)
        print(buttonItem) //for debug

    } else if buttonItem == 3 {

        self.yellowLabel.backgroundColor = UIColor.grayColor()
        timer = NSTimer.scheduledTimerWithTimeInterval(length, target:self, selector: ("colorChange") , userInfo: nil, repeats: false)
        print(buttonItem) //for debug

    } else if buttonItem == 4 {

        self.blueLabel.backgroundColor = UIColor.grayColor()
        timer = NSTimer.scheduledTimerWithTimeInterval(length, target:self, selector: ("colorChange") , userInfo: nil, repeats: false)
        print(buttonItem) //for debug

    }
}

我整天都在试图解决这个困扰我的问题。我已经复制了下面的新最新代码,请丢弃上面的代码。

我有四个标签,颜色为红蓝绿色和黄色。具有4 3 2 1内部测试数据的阵列需要逐步执行每个项目 - 将标签的颜色更改为x秒然后将其返回到正常颜色。我试过NSTimer,我已经尝试了当前的延迟,如附带的代码。我错过了我放置代码的地方 - 它应该在viewdidload下吗?我试过循环,当前代码示例显示切换,以防它的行为不同 - 它没有!!

基本上同时所有标签都会变灰(现在测试颜色),然后在x秒延迟后全部变成原始颜色。

在我疯了之前我需要一些帮助。老实说我知道这是基本的东西,但我无法理解。

import UIKit
import Foundation

var gameisrunning = false
var playererror = false
var memoryArray = [Int]()
var currentScore = 0

class ViewController: UIViewController {

    @IBAction func startGameButton(sender: UIButton) {

        if gameisrunning == false {

            gameisrunning = true
            memoryArray.append(4) //for debug
            memoryArray.append(3) //for debug
            memoryArray.append(2) //for debug
            memoryArray.append(1) //for debug
            print(memoryArray) //for debug
            gameStart()

        } else {

        }
    }


    //these are to be implemented once i get the showing sequence sorted.

    @IBAction func redButton(sender: UIButton) {
    }
    @IBAction func greenButton(sender: UIButton) {
    }
    @IBAction func yellowButton(sender: UIButton) {
    }
    @IBAction func blueButton(sender: UIButton) {
    }

    @IBOutlet weak var redLabel: UILabel!
    @IBOutlet weak var greenLabel: UILabel!
    @IBOutlet weak var yellowLabel: UILabel!
    @IBOutlet weak var blueLabel: UILabel!
    @IBOutlet weak var scoreLabel: UILabel!

    func addAnotherItemToMemory () {
        // adds another item to the memory
        memoryArray.append(Int(arc4random_uniform(4)+1))
    }

    func gameStart () {
        // main body of game
        showPlayerTheMemory()
    }

    func delayProg (){
        //attempt 100093287492 to get a delay in program
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(2.0 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            self.blueLabel.backgroundColor = UIColor.blueColor()
            self.yellowLabel.backgroundColor = UIColor.yellowColor()
            self.greenLabel.backgroundColor = UIColor.greenColor()
            self.redLabel.backgroundColor = UIColor.redColor()

        }
    }

    func showPlayerTheMemory () {

        // go through list and highlight the colors one at a time

        for var i=0; i <= memoryArray.count-1; i++ {
            self.showColor(memoryArray[i])
        }
    }


    func showColor(buttonItem: Int) {

        //check to see which color, change to grey (test color) and back to original after a set time.

        switch (buttonItem) {

        case 1:
            self.redLabel.backgroundColor = UIColor.grayColor()
            delayProg()
            print(buttonItem) //for debug
        case 2:
            self.greenLabel.backgroundColor = UIColor.grayColor()
            delayProg()
            print(buttonItem) //for debug
        case 3:
            self.yellowLabel.backgroundColor = UIColor.grayColor()
            delayProg()
            print(buttonItem) //for debug
        case 4:
            self.blueLabel.backgroundColor = UIColor.grayColor()
            delayProg()
            print(buttonItem) //for debug
        default:
            print("error")
        }
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

1 个答案:

答案 0 :(得分:1)

以下是正确实施NSTimer()

的示例
var myTimer = NSTimer()

func startTimer() {
    myTimer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: "myFunction", userInfo: nil, repeats: true)
}

func myFunction() {
myTimer.invalidate()
    //do other stuff
}
//the selector is "myFunction", this will be the name of the function that you wish to call every time the timer reaches its specified intervl
//the interval in this case is 10 seconds. In my experience NSTimer is good down to the second but is not precise enough beyond that
//repeats: true ... this will tell the timer to repeat its action consistently firing the selector each time the given time interval is reached. If repeat is set to false then the timer only fires once
//use myTimer.invalidate to stop the timer and to stop calling the selector.

务必invalidate您的计时器或设置repeats: false以确保它不会永远存在。确保您的选择器拼写与您的功能完全相同。如果您的函数是func myFunction(),则选择器应为"myFunction"。确保指定有效的时间间隔,以秒为单位。