0

TL;DR 随机访问 tilemap 中的每个 tile

我有一种方法可以通过填充整个图层(只有 10x10)然后运行for像 }} 这样的循环来for (int x = 0; x < 13; x++) { for (int y = 0; y < 11; y++)随机删除图块。我也有一个上限,大约是 30。问题是当循环运行时,它会用完左边的上限(因为它从 x=0 y=0 开始,然后是 x0 x1 x2 x3 。 ..)。我尝试随机生成坐标,但这不起作用,因为它没有遍历所有坐标。

有谁知道以随机顺序扫描地图中每个坐标的更好做法?

4

2 回答 2

1

我认为实现这一点的最佳实践是通过双重哈希。要了解更多信息,请阅读此链接:Double Hashing。我将尝试简单地解释它。

您有两个需要预先计算的辅助哈希函数。以及一个for循环运行的主散列函数。让我们测试一下(这将是伪代码):

key = random_number() //lets get a random number and call it "key"
module = map_size_x // map size for our module

//form of hash function 1 is: h1(key) = key % module, lets compute the hash 1 for our main hash function
aux1 = key % module
//form of hash function 2 is: h2(key) = 1 + (key % module'), where module' is module smaller for a small number (lets use 1), lets compute it:
aux2 = 1 + (key % (module - 1))

//the main hash function which will generate a random permutation is in the form of: h(key, index) = (h1(key) + index*h2(key)) % module. we already have h1 and h2 so lets loop this through:
for (i = 0; i < map_size_x; i++)
{
     randomElement = (aux1 + i*aux2) % module //here we have index of the random element
     //DO STUFF HERE
}

要获得另一个排列,只需更改 的值key。有关更多信息,请查看链接。

希望这可以帮助。干杯。

于 2013-05-29T11:55:11.147 回答
1

无论如何,将您的瓷砖编号为 0 到 n。创建一个 NSMutableIndexSet,并将所有内容添加到其中。使用随机数生成器缩放到仍在索引集中的项目数(实际上是从第一个到最后一个的范围),抓取一个,然后将其从集合中删除。如果随机数不在集合中,则生成一个新的 be 等,直到在集合中找到一个。

于 2013-05-29T11:42:54.287 回答