I'm programming a game in swift and i want to create a code that let me sort a group of image in every x seconds. It's 5 images, and the idea is that in every 2 seconds, the position of the images will be changed and cannot have repeated images.
So will have a lot of combinations:
1, 2, 3, 4, 5
5, 4, 3, 2, 1
1, 3, 2, 5, 4
etc...
Above is the code that i made, but i thinks this is not the best way to do that.
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()
}
what the best way to do that? I tried to implement a function with arc4random_uniform and If Else statements, but i cant cover all the possibilities manually. And i don't know how to implement the time factor to make trigger the change.