编程和尝试制作我的第一个游戏的新手。它是我想要的4个UIImages"打开"在用户复制模式的模式中。从以下是相同模式并增加随机模式。 arc4random.uniform()我在这里寻找什么?我知道这会生成一个随机数,但我仍然坚持如何让随机图像重复并随机添加+1。
答案 0 :(得分:0)
所以你有4张图片,我猜你想要一个1到4之间的随机数代表你想要的图像"打开"。以下内容可以为您生成随机的图像序列(您可以在Swift Playground中测试它):
import Foundation
let numberOfImages = 4
func addRandom(array: [Int]) -> [Int] {
var returnArray = array
returnArray.append(Int(arc4random()) % numberOfImages)
return returnArray
}
func makePattern(length: Int) -> [Int] {
var pattern = [Int]()
for _ in 0...(length - 1) {
pattern = addRandom(pattern)
}
return pattern
}
// Array of 3 random digits
var firstPattern = makePattern(3)
// Same array as before, with one more random digit at the end
var nextPattern = addRandom(firstPattern)
// Same array as before, with yet another random digit at the end
var lastPattern = addRandom(nextPattern)
只是为了好玩,你可以使用Pattern类更干净地做到这一点,如下所示:
import Foundation
class Pattern {
private(set) var maxRandomNumber: Int!
private(set) var pattern: [Int] = [Int]()
init(maxRandomNumber: Int) {
self.maxRandomNumber = maxRandomNumber
}
init(length: Int, maxRandomNumber: Int) {
self.maxRandomNumber = maxRandomNumber
for _ in 0...(length - 1) {
self.appendRandom()
}
}
func appendRandom() {
self.pattern.append(Int(arc4random()) % self.maxRandomNumber)
}
}
// Initialize a new pattern with 3 iterations and a max random number of 4
var pattern = Pattern(length: 3, maxRandomNumber: 4)
// See the pattern
print(pattern.pattern)
// Add another random number on to the end and check
pattern.appendRandom()
print(pattern.pattern)