如何快速随机排列一组精灵?

时间:2018-08-23 03:07:22

标签: ios swift sprite-kit shuffle

每次启动应用程序时,我都希望对数组中的元素进行混洗,而且这些元素也应放在屏幕上而不重复,我该怎么做?我尝试了几种扩展来改组我的阵列,但是没有用

我正在使用swift 4.1,这是我的代码:

import SpriteKit

struct ContainerSprite{
    let block : SKSpriteNode!

    let containers = ["Container_Circle_Blue","Container_Hexagone_Blue",
"Container_Square_Blue","Container_Star_Blue","Container_Triangle_Blue",
"Container_Circle_DBlue","Container_Hexagone_DBlue","Container_Square_DBlue",
"Container_Star_DBlue","Container_Triangle_DBlue","Container_Circle_Green",
"Container_Hexagone_Green","Container_Square_Green","Container_Star_Green",
"Container_Triangle_Green"]

    init (numContainer: Int, row: Int, col: Int , inThisScene: GameScene) {
        block = SKSpriteNode(imageNamed: containers[numContainer])
        let numberOfBlocks = 12.5
        let blockScale = 0.6   
     }
}

这是我使用的扩展程序之一,但是当我尝试时,它显示的是随机重复的元素

extension MutableCollection {
    /// Shuffles the contents of this collection.
    mutating func shuffle() {
        let c = count
        guard c > 1 else { return }

        for (firstUnshuffled, unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {
            // Change Int in the next line to IndexDistance in < Swift 4.1
            let d: Int = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
            let i = index(firstUnshuffled, offsetBy: d)
            swapAt(firstUnshuffled, i)
        }
    }
}

extension Sequence {
    /// Returns an array with the contents of this sequence, shuffled.
    func shuffled() -> [Element] {
        var result = Array(self)
        result.shuffle()
        return result
    }
}

0 个答案:

没有答案