cell_size = 0.01
grid_size = int(1.0 / cell_size)
grid = [[0.0 for _ in range(grid_size)] for _ in range(grid_size)]
for ix in range(grid_size):
for iy in range(grid_size):
px = ix * cell_size
py = iy * cell_size
px1 = px + cell_size
py1 = py + cell_size
noise_sum = 0.0
# 对每个网格内的点进行求和
for i in range(4):
tx = px + (i % 2) * cell_size
ty = py + (i // 2) * cell_size
noise_sum += noise(tx, ty)
# 计算噪声均值并映射到0到1之间
grid[ix][iy] = (noise_sum / 4.0 + 1.0) / 2.0
# 设置每个网格是陆地还是海洋
land_threshold = 0.6
land_grid = [[grid[ix][iy] > land_threshold for iy in range(grid_size)] for ix in range(grid_size)]
3.连接每个陆地网格形成大陆,连接方式以相邻网格连接且不能穿过海洋。可以使用连通图算法来实现。
python
# 获得所有陆地点的坐标
land_coords = [(ix, iy) for ix in range(grid_size) for iy in range(grid_size) if land_grid[ix][iy]]
# 连接所有陆地点
connections = []
for i in range(len(land_coords)):
for j in range(i + 1, len(land_coords)):
if can_connect(land_coords[i], land_coords[j], land_grid):
connections.append((land_coords[i], land_coords[j]))
# 获得连通的网格集合
connected_groups = []
while len(connections) > 0:
cur_set = set([connections[0][0], connections[0][1]])
del connections[0]
changed = True
while changed:
changed = False
for i in range(len(connections)):
set1 = set([connections[i][0], connections[i][1]])
if len(cur_set & set1) > 0:
cur_set |= set1
changed = True
del connections[i]
break
connected_groups.append(cur_set)
# 设置大陆网格
land_grid = [[False for _ in range(grid_size)] for _ in range(grid_size)]
for group in connected_groups:
for ix, iy in group:
land_grid[ix][iy] = True
def can_connect(coord1, coord2, land_grid):
# 判断coord1和coord2是否可以相连
x1, y1 = coord1
x2, y2 = coord2
if x1 == x2:
if y1 > y2:
y1, y2 = y2, y1
for iy in range(y1 + 1, y2):
if not land_grid[x1][iy]:
return False
return True
if y1 == y2:
if x1 > x2:
x1, x2 = x2, x1
for ix in range(x1 + 1, x2):
if not land_grid[ix][y1]:
return False
return True
return False