我正在使用swift编写游戏,我想创建一个代码,让我可以在每x秒内对一组图像进行排序。这是5张图像,其思路是每2秒钟,图像的位置会发生变化而无法重复拍摄图像。
所以会有很多组合:
1,2,3,4,5
5,4,3,2,1
1,3,2,5,4
等...
以上是我制作的代码,但我认为这不是最好的方法。
var timer:NSTimer!
func startTimer() {
if timer != nil {
timer.invalidate()
}
timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "sortImg", userInfo: nil, repeats: true)
}
// imagens de elementos de alimentação
@IBOutlet weak var imgCoracao: UIImageView!
@IBOutlet weak var imgCoxinha: UIImageView!
@IBOutlet weak var imgSerie: UIImageView!
@IBOutlet weak var imgSushi: UIImageView!
@IBOutlet weak var imgTod: UIImageView!
func sortImg() {
let rand = arc4random_uniform(4)
if rand == 0 {
imgCoracao.image = UIImage(named: "icon_coxinha.png")
imgCoxinha.image = UIImage(named: "icon_toddy.png")
imgSerie.image = UIImage(named: "icon_sushi.png")
imgSushi.image = UIImage(named: "icon_serie.png")
imgTod.image = UIImage(named: "icon_coracao.png")
} else if rand == 1 {
imgCoracao.image = UIImage(named: "icon_coxinha.png")
imgCoxinha.image = UIImage(named: "icon_sushi.png")
imgSerie.image = UIImage(named: "icon_toddy.png")
imgSushi.image = UIImage(named: "icon_coracao.png")
imgTod.image = UIImage(named: "icon_serie.png")
} else if rand == 2 {
imgCoracao.image = UIImage(named: "icon_serie.png")
imgCoxinha.image = UIImage(named: "icon_coracao.png")
imgSerie.image = UIImage(named: "icon_sushi.png")
imgSushi.image = UIImage(named: "icon_toddy.png")
imgTod.image = UIImage(named: "icon_coxinha.png")
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
startTimer()
sortImg()
}
最好的方法是什么?我尝试使用arc4random_uniform和If Else语句实现一个函数,但我无法手动覆盖所有可能性。我不知道如何实现时间因素来触发变化。