我能想到的最简单的方法:
for each tile
based on the surrounding already generated tiles,
generate a random type among those which won't result in 3-in-a-row
还有一种未优化的方法,假设只有水平和垂直匹配(不是对角线):(伪代码)
for x = 1 to M
for y = 1 to M
do
board[x][y] = randomType()
while ((x >= 3 && board[x-1][y] == board[x-2][y] && board[x-1][y] == board[x][y]) ||
(y >= 3 && board[x][y-1] == board[x][y-2] && board[x][y-1] == board[x][y]))
一种完全避免重复生成的方法:(假设类型是数字)
for x = 1 to M
for y = 1 to M
limit = N
horizontal = (x >= 3 && board[x-1][y] == board[x-2][y] && board[x-1][y] == board[x][y])
vertical = (y >= 3 && board[x][y-1] == board[x][y-2] && board[x][y-1] == board[x][y])
if horizontal
limit--
if vertical
limit--
board[x][y] = randomType(limit)
offset = 0
if (vertical && board[x][y] >= board[x][y-1])
offset++
if (horizontal && board[x][y] >= board[x-1][y])
offset++
board[x][y] += offset
上述方法的工作原理类似于在 [0,A-1] 和 [A+1,B] 范围内生成数字,方法是在 [0,B-1] 范围内生成数字,然后,如果生成的数字是 A 或更大,我们将其增加 1。
N
至少需要 3,否则您可能会得到类似的结果:
..A
..A
BB?
为此,上述算法将陷入无限循环。