我很喜欢编程。我试图动态地堆积随机块,直到它击中上框架。但似乎斯威夫特不允许我这样做。我有什么不想错的吗?任何意见都表示赞赏。
let blocks =[block1,block2,block3,block4,block5,block6,block7,block8,block9,block10,block11,block12]
var block:SKSpriteNode!
let blockX:Double = 0.0
var blockY:Double = -(self.size.height/2)
repeat{
block = blocks.randomBlock()
block.zPosition = 2
block.position = CGPoint(x:blockX, y:blockY)
block.size.height = 50
block.size.width = 50
self.addChild(block)
blockY += 50
} while( block.position.y < self.size.height)
extension Array {
func randomBlock()-> Element {
let randint = Int(arc4random_uniform(UInt32(self.count)))
return self[randint]
}
}
答案 0 :(得分:1)
您需要在某种程度上跟踪已选择的块,并确保它们不会再次被选中。下面的方法使用一个数组来存储所选块的索引,然后使用递归来查找循环直到找到未使用的匹配。
private var usedBlocks = [Int]()
func randomBlock() -> Int {
guard usedBlocks.count != blocks.count else { return -1 }
let random = Int(arc4random_uniform(UInt32(blocks.count)))
if usedBlocks.contains(random) {
return randomBlock()
}
usedBlocks.append(random)
return random
}
循环中的将初始化程序更改为
let index = randomBlock()
if index > -1 {
block = blocks[index]
block.zPosition = 2
block.position = CGPoint(x:blockX, y:blockY)
}
请记住,如果您重新开始游戏或开始新的等级,则必须清除usedBlocks中的所有对象
usedBlocks.removeAll()