【问题标题】:Pre-generating pseudo-random terrain in JS在 JS 中预生成伪随机地形
【发布时间】:2016-03-17 00:00:21
【问题描述】:

我正在开发一个简单的 JS/canvas 游戏。在这个游戏中,我希望用户能够在每次由客户端根据相同的种子生成的世界中导航。因此,虽然世界是随机的,但每个用户都得到相同的结果。

因此,我正在寻找一种方法来执行以下操作:

var some_seed = "abcdefg" // For instance
function get_world_rect(ab, cd) { ... }

get_world_rect([0,0], [9,9])
// Yields the following: 
[[0, 0, 0, 0, 0, 0, "some_feature", 0, 0, 0], 
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, "rock", 0, 0, "bush", 0, 0, 0, 0, 0], 
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
 [0, 0, 0, "bush", 0, 0, 0, 0, 0, 0], 
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
 [0, 0, 0, 0, 0, 0, 0, "bush", 0, 0], 
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
 [0, 0, "rare_flower", 0, 0, 0, 0, 0, 0, 0], 
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

这里的两个重要部分是我希望能够每次在每个客户端上生成相同的“地图”并控制某些功能的“稀有性”。所以我可以说这张地图产生“灌木”的概率为 X,产生“稀有花”的概率为 Y。

【问题讨论】:

标签: javascript canvas random procedural-generation


【解决方案1】:

我使用了自定义随机数生成器。然后我给它一个种子加上一些基于图块的 x 和 y 的计算。

不确定这是否是我能做的最好的,但它确实有效。

下面会出现一个sn-p。

generate_map = function(chunk_x, chunk_y) {
    // The MersenneTwister object is from code this link: https://gist.github.com/banksean/300494
    // this.base seed is some int.
    // a "map chunk" is a square of tile containing this.map_chunk_size tiles.
    // chunk_x and chunk_y are that chunk's X and Y.
    g = new MersenneTwister(this.base_seed + chunk_x*1000000 + chunk_y)
    tiles = []
    for(var x = 0; x < this.map_chunk_size; x++) {
        for(var y = 0; y < this.map_chunk_size; y++) {
            var k = g.random()
            /* 
            Objects:
            0 - empty
            1 - something 1
            2 - something 2
            */
            var obj = 0
            if (k < 0.001) {
                // Something rare
                obj = 2
            } else if (k < 0.1) {
                obj = 1
            }
            tiles.push(obj)
        }
    }
    return tiles
}

通过这种方式,它可以跨浏览器和操作系统进行预测(据我目前所知),而且我不必在服务器上生成并保留大量数据。

据我所知,对性能的影响很小。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-07
    • 2012-02-12
    • 1970-01-01
    • 2010-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多