gpt4 book ai didi

swift - Hacking With Swift Project 2...如何随机化这些图像?

转载 作者:行者123 更新时间:2023-11-30 12:26:43 25 4
gpt4 key购买 nike

所以我正在研究 Hacking With Swift 的项目 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.
}


}

最佳答案

你只需要打乱数组即可:

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

关于swift - Hacking With Swift Project 2...如何随机化这些图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44117245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com