Skip to content

Instantly share code, notes, and snippets.

@shiracamus
Last active January 29, 2019 15:43
Show Gist options
  • Save shiracamus/91f118041134082f9557a673567f1c32 to your computer and use it in GitHub Desktop.
Save shiracamus/91f118041134082f9557a673567f1c32 to your computer and use it in GitHub Desktop.
import sys
import random
def show_maze(maze):
print()
for row in maze:
print(' ', *row, sep='')
def maze(height, width):
"""height行width列の迷路を作る"""
maze = [['*'] * (width * 2 + 1) for y in range(height * 2 + 1)]
clusters = [number for number in range(height * width)]
def clusterling(cluster1, cluster2):
"""大きい方のクラスタ番号を小さい方のクラスタ番号にリンクする"""
clusters[max(cluster1, cluster2)] = min(cluster1, cluster2)
def cluster(x1, y1):
"""指定位置のクラスタ番号(接続先最小クラスタ番号)を得る"""
number = y1 * width + x1
while number != clusters[number]:
number = clusters[number]
return number
def remove(wall):
"""指定された壁を壊してクラスタリング"""
x1, y1, x2, y2 = wall
c1 = cluster(x1, y1)
c2 = cluster(x2, y2)
if c1 == c2:
# 同じクラスタを隔てている壁は壊さない
return
clusterling(c1, c2)
if x1 == x2:
# 縦(下側)の壁を壊す
maze[y1 * 2 + 2][x1 * 2 + 1] = ' '
else:
# 横(右側)の壁を壊す
maze[y1 * 2 + 1][x1 * 2 + 2] = ' '
def make():
walls = []
for y in range(height):
for x in range(width):
maze[y * 2 + 1][x * 2 + 1] = ' '
y > 0 and walls.append((x, y - 1, x, y)) # 上側の壁とこの壁
x > 0 and walls.append((x - 1, y, x, y)) # 左側の壁とこの壁
random.shuffle(walls)
for wall in walls:
remove(wall)
make()
maze[-2][1] = 'S'
maze[1][-2] = 'G'
return maze
def main():
height, width = 10, 20
if len(sys.argv) == 2:
height = width = int(sys.argv[1])
elif len(sys.argv) == 3:
height, width = map(int, sys.argv[1:])
show_maze(maze(height, width))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment