Friday, May 17, 2019

Timer code for Concentration game

This code is in the action method for when a button (card) gets touched. Your code may need to be a little different. 

        if buttonsTouched.count >= 2 {
            // same picture
            if pictures[buttonsTouched[0].tag] == pictures[buttonsTouched[1].tag] {
                let _ = Timer.scheduledTimer(
                    timeInterval: 2.0,
                    target: self,
                    selector: #selector(keepCards),
                    userInfo: nil,
                    repeats: false)
            }
            // not same picture
            else {
                let _ = Timer.scheduledTimer(
                    timeInterval: 2.0,
                    target: self,
                    selector: #selector(turnOver),
                    userInfo: nil,
                    repeats: false)
            }
        }


These are the selector functions that will get called. Your code may be a lot different.

    @objc func keepCards() {
        buttonsTouched[0].backgroundColor = flippedColor
        buttonsTouched[1].backgroundColor = flippedColor
//        buttonsTouched[0].setTitleColor(.white, for: .normal)
//        buttonsTouched[1].setTitleColor(.white, for: .normal)
        buttonsTouched = []
    }
   
    @objc func turnOver() {
        if seen.contains(pictures[buttonsTouched[0].tag]) {
            missed += 1
            missedLabel.text = "\(missed) missed"
        }
        for b in buttonsTouched {
            b.setTitle("\(b.tag+1)", for: .normal)
            seen.append(pictures[b.tag])
        }
        buttonsTouched = []
        print (seen)
    }

No comments:

Post a Comment