根据种子Swift 3

时间:2017-10-18 09:38:32

标签: swift random

让我们说你正在制作一款游戏,这款游戏通过程序生成的地形来自用户在其世界创作菜单中输入的种子

并且此种子生成一组值,只有在种子更改时才会更改

例如,假设您想要获取一个随机的整数集以在for循环中生成并从数组中随机拉取整数集,每次都保持相同并从数组中拉出完全相同的项每次运行for循环直到更改种子

如何在swift中实现这一目标

在我的代码中,我可以获得地形,但每次都不会生成相同的内容,而这正是我想让它去做的事情

override func didMove(to view: SKView) {

    let tile1 = SKTileDefinition(texture: SKTexture(imageNamed: "stone") ,size: CGSize(width: 64, height: 64))
    let tile2 = SKTileDefinition(texture: SKTexture(imageNamed: "water") ,size: CGSize(width: 64, height: 64))
    let tile3 = SKTileDefinition(texture: SKTexture(imageNamed: "sand") ,size: CGSize(width: 64, height: 64))
    let tile4 = SKTileDefinition(texture: SKTexture(imageNamed: "grass") ,size: CGSize(width: 64, height: 64))

    let tileGroup1 = SKTileGroup(tileDefinition: tile1)
    let tileGroup2 = SKTileGroup(tileDefinition: tile2)
    let tileGroup3 = SKTileGroup(tileDefinition: tile3)
    let tileGroup4 = SKTileGroup(tileDefinition: tile4)
    let tileGroup5 = SKTileGroup(tileDefinition: tile4)
    let tileGroup6 = SKTileGroup(tileDefinition: tile4)

    let tileSet = SKTileSet(tileGroups: [tileGroup1,tileGroup2,tileGroup3,tileGroup4,tileGroup5,tileGroup6])

    let columns = 5
    let rows = 5

    let tileSize = CGSize(width: 64, height: 64)

    //this is another GKNoise class called Noise
    let noise = Noise()
    let noiseMap = GKNoiseMap(noise, size: vector_double2(10.0,10.0), origin: vector_double2(0.0,0.0), sampleCount: vector_int2(100), seamless: true)
    //this is another SKTileMapNode Class called TileMap and a class func called tileMapNodes
    let tileMap = TileMap.tileMapNodes(tileSet: tileSet, columns: columns, rows: rows, tileSize: tileSize, from: noiseMap, tileTypeNoiseMapThresholds: [(-1.0 as NSNumber),(+1.0 as NSNumber)])

    tileMapNode = tileMap.first!

    let seed = Int

    for column in 0 ..< tileMapNode.numberOfColumns {
        for row in 0 ..< tileMapNode.numberOfRows {
            let rand = Int(arc4random_uniform(UInt32(tileSet.tileGroups.count)))
            print(rand)
            let tile = tileMapNode.tileSet.tileGroups[rand]
            tileMapNode.setTileGroup(tile, forColumn: column, row: row)
        }
    }

1 个答案:

答案 0 :(得分:2)

如果您想根据特定种子使用生成随机值:srand48drand48

srand允许您指定种子:

    srand48(230)

然后drand48会给你0到1之间的双倍:

    let doubleValue = drand48()

因此,在您的情况下,如果您想要一个0到9之间的Int,您可以执行以下操作:

    srand48(230)
    print("Random number: \(1 + Int((drand48() * 8) + 0.5))")
    print("Random number: \(1 + Int((drand48() * 8) + 0.5))")
    print("Random number: \(1 + Int((drand48() * 8) + 0.5))")

它将为您提供3个伪随机数,直到您更改种子

以下drand48适用于您的新问题:

let seed = srand48(230)

for column in 0 ..< tileMapNode.numberOfColumns {
    for row in 0 ..< tileMapNode.numberOfRows {
        let rand = Int(Double(tileSet.tileGroups.count) * drand48() - 0.5)
        print(rand)
        let tile = tileMapNode.tileSet.tileGroups[rand]
        tileMapNode.setTileGroup(tile, forColumn: column, row: row)
    }
}