用python写一段栅格地图
时间: 2023-09-29 08:06:10 浏览: 83
以下是一个简单的栅格地图的Python代码示例:
```python
import random
# 定义栅格地图的大小
MAP_WIDTH = 10
MAP_HEIGHT = 10
# 定义障碍物的数量
OBSTACLE_COUNT = 10
# 定义地图的符号表示
EMPTY = "-"
OBSTACLE = "X"
START = "S"
GOAL = "G"
# 创建一个空的地图
map = [[EMPTY for x in range(MAP_WIDTH)] for y in range(MAP_HEIGHT)]
# 在地图上随机放置障碍物
for i in range(OBSTACLE_COUNT):
x = random.randint(0, MAP_WIDTH - 1)
y = random.randint(0, MAP_HEIGHT - 1)
map[y][x] = OBSTACLE
# 随机选择起点和终点
start_x = random.randint(0, MAP_WIDTH - 1)
start_y = random.randint(0, MAP_HEIGHT - 1)
map[start_y][start_x] = START
goal_x = random.randint(0, MAP_WIDTH - 1)
goal_y = random.randint(0, MAP_HEIGHT - 1)
while goal_x == start_x and goal_y == start_y:
goal_x = random.randint(0, MAP_WIDTH - 1)
goal_y = random.randint(0, MAP_HEIGHT - 1)
map[goal_y][goal_x] = GOAL
# 打印地图
for row in map:
print(" ".join(row))
```
该代码将创建一个大小为10x10的栅格地图,并在其中随机放置10个障碍物。然后随机选择起点和终点,并将它们标记为“S”和“G”。最后,该代码将打印出整个地图,显示障碍物、起点和终点的位置。
阅读全文