使用Swift Project 2进行黑客攻击...如何随机化这些图像?

时间:2017-05-22 15:55:21

标签: swift xcode

所以我正在使用Hacking With Swift从事Project 2。我制作的游戏很简单,你猜测正确的旗帜和3个新旗帜出现了。每次单击答案时,我都需要刷新标志。点击时我的标签得分计数器计数,但标志不“刷新”。在项目的前一次迭代中,它使用警报和刷新标志成功计算得分,但我通过教程完成了。您将看到我导入了Gameplay Kit并使用GKRandomsource,它在原始迭代中随机化了标志,我想我现在需要利用它。我希望这个问题不要过于混乱,如果是这样,请告诉我。

TLDR:当我点击按钮时,我需要这些标志随机化。

import GameplayKit
import UIKit

class ViewController: UIViewController {
@IBOutlet weak var button1: UIButton!
@IBOutlet weak var button2: UIButton!
@IBOutlet weak var button3: UIButton!

@IBOutlet weak var displayScore: UILabel!

var countries = [String]()
var correctAnswer = 0
var score = 0


override func viewDidLoad() {
    super.viewDidLoad()
  countries += ["estonia", "france", "germany", "ireland", "italy", "monaco", 
"nigeria", "poland", "russia", "spain", "uk", "us"]

    button1.layer.borderWidth = 1
    button2.layer.borderWidth = 1
    button3.layer.borderWidth = 1

    button1.layer.borderColor = UIColor.lightGray.cgColor
    button2.layer.borderColor = UIColor.lightGray.cgColor
    button3.layer.borderColor = UIColor.lightGray.cgColor

    askQuestion(action: nil)

}

func askQuestion(action: UIAlertAction!) {
    countries = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: 
countries) as! [String]
    button1.setImage(UIImage(named: countries[0]), for: .normal)
    button2.setImage(UIImage(named: countries[1]), for: .normal)
    button3.setImage(UIImage(named: countries[2]), for: .normal)
    correctAnswer = GKRandomSource.sharedRandom().nextInt(upperBound: 3)
    title = countries[correctAnswer].uppercased()
}

@IBAction func buttonTapped(_ sender: UIButton) {
    var title: String

    if sender.tag == correctAnswer {
        title = "Correct"
        score += 1
    } else {
        title = "Wrong"
        score -= 1
    }

    displayScore.text = "Your Score is \(score)"
    //let ac = UIAlertController(title: title, message: "Your score is \
(score).", preferredStyle: .alert)
    //ac.addAction(UIAlertAction(title: "Continue", style: .default, handler: 
askQuestion))
    //present(ac, animated: true)
}


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


}

1 个答案:

答案 0 :(得分:0)

你只需要改组阵列:

    extension MutableCollection where Index == Int {
        /// Shuffle the elements of `self` in-place.
        mutating func shuffle() {
            // empty and single-element collections don't shuffle
            if count < 2 { return }

            for i in startIndex ..< endIndex - 1 {
                let j = Int(arc4random_uniform(UInt32(endIndex - i))) + i
                if i != j {
                    swap(&self[i], &self[j])
                }
            }
        }
    }