Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
101 lines (82 loc) · 2.81 KB
/
Copy pathmain.py
File metadata and controls
101 lines (82 loc) · 2.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import random
import sys
from time import time
from nbinput import BlockingInput
class Maze:
def __init__(self, width, height):
self.width = 1 + 2 * int(width / 2)
self.height = 1 + 2 * int(height / 2)
self.end = (self.width - 2, self.height - 2)
self.generate()
def __str__(self):
return self.string()
def string(self, objs={}):
h_border = '+' + ('-' * (self.width * 2 + 1)) + '+\n'
string = h_border
for y, row in enumerate(self.maze):
string += '|'
for x, cell in enumerate(row):
string += ' '
try:
string += objs[(x, y)]
except KeyError:
string += '#' if cell else ' '
string += ' |\n'
string += h_border
return string
def generate(self):
space = lambda x, y: ((x % 2) and (y % 2))
wall = lambda x, y: ((x % 2) and not (y % 2)) or (not (x % 2) and (y % 2))
self.maze = [[not (space(x, y) or (wall(x, y) and random.randint(0, 1))) or (x == 0 or x == self.width - 1 or y == 0 or y == self.height - 1) for x in range(self.width)] for y in range(self.height)]
if not self.solve():
self.generate()
def solve(self, coord=(1, 1), prev=False):
x, y = coord
if coord == self.end:
return True
if not prev:
self.prev = []
self.prev.append(coord)
solved = False
for d in ((0, -1), (1, 0), (0, 1), (-1, 0)):
x1, y1 = x + d[0], y + d[1]
x2, y2 = x1 + d[0], y1 + d[1]
if x2 >= 0 and x2 < len(self.maze[0]) and y2 >= 0 and y2 < len(self.maze) and not self.maze[y1][x1] and (x2, y2) not in self.prev:
solved = self.solve((x2, y2), True)
if solved:
break
return solved
def play(maze):
solved = False
x, y = (1, 1)
with BlockingInput() as bi:
while not (x, y) == maze.end:
print(maze.string({(x, y): 'X'}))
dx, dy = (0, 0)
c = bi.char()
if c in 'aA':
dx = -1
elif c in 'dD':
dx = 1
elif c in 'wW':
dy = -1
elif c in 'sS':
dy = 1
x += dx * (not maze.maze[y][x + dx])
y += dy * (not maze.maze[y + dy][x])
print(maze.string({(x, y): 'X'}))
print('Completed!')
def main():
try:
x, y = (int(n) for n in sys.argv[1:3])
except ValueError:
sys.exit('Usage: {} width height'.format(sys.argv[0]))
n = 10
start = time()
for i in range(n):
maze = Maze(x, y)
play(maze)
print('Time to complete {} {}x{} mazes: {}'
.format(n, x, y, round(time() - start, 2)))
if __name__ == '__main__':
main()