函数定义如下:
/**
* @param {number} x The x-coordinate (can be positive or negative)
* @param {number} y The y-coordinate (can be positive or negative)
* @param {number} tileCount The number of available tiles
* @return {number} The selected tile index
*/
function getRandomTileIndex(x, y, tileCount) {
// Fill in code here
}
我可以,例如,return x * y % tileCount
,但我想引入随机性。我可以用return Math.round(Math.random() * (tileCount-1))
,但是每次都会返回不同的索引
我希望这个函数是确定性的,所以当使用相同的输入(x, y, tileCount)
时,总是会出现相同的输出。但我也希望它看起来(尽可能)是随机的,均匀分布——随机性的质量不必是完美的。
这个随机贴图生成器的目的是一个游戏(几乎)无限的网格-用户开始在中间的(x,y) = (0,0)
,并将在任何方向向外移动他想要的-我将只有一个固定数量的背景瓷砖的"地面"-我想要它,所以每次你加载游戏的世界看起来是一样的。
如果你想引入"可预测的随机性",那么听起来你需要一个散列。可预测的随机性是一个矛盾修饰法,因为真正的随机性是不可预测的,所以我们将其称为未知但确定的。
算法如下:
- 使用算法(SHA-256, md5等)来散列一些唯一的值对于一个给定的位置,
(x*Y)
对我来说听起来不错引入一些对称性——(1,1)
映射到与(-1 -1)
相同的 - 使用返回值的某些属性来返回一个tileCount数量
- 可能是
sum(bits of hash) % tileCount
- 可能是
为了解决对称性问题,你可以在x和y上添加一个大的数字,这样对称就会发生在一个几乎不可能的遥远的地方。所以:
hashVal = hash((x+53562345)*(y-235734093))
tileType = sum(hashVal bits) % tileCount
或者您可以使用sum(hash(x)+hash(y))来消除对称性,但是太多的哈希算法会变得缓慢和笨拙。
我建议您使用一个函数来动态创建磁贴,然后将它们保存在一个对象中。因此,每次调用该函数时,它都会返回创建对象的值。如果你想要创造一款HTML5游戏,你也可以使用HTML5 Local Storage来保存对象。
建议是:
/**
* @param {number} x The x-coordinate (can be positive or negative)
* @param {number} y The y-coordinate (can be positive or negative)
* @param {number} tileCount The number of available tiles
* @return {number} The selected tile index
*/
var tiles = {};
function getRandomTileIndex(x, y, tileCount) {
var tile;
if(tiles[x][y]) {
tile = tiles[x][y];
}
else {
tile = Math.round(Math.random() * (tileCount));
tiles[x][y] = tile;
}
return tile;
}