-
Notifications
You must be signed in to change notification settings - Fork 0
/
crawler.py
80 lines (68 loc) · 2.37 KB
/
crawler.py
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
from base_objects import CrawlerPosition
class Crawler:
"""Moves to the next available space on a maze map, starting at the
specified start co-ordinates and returns its new position"""
def __init__(self, maze_map, start_x, start_y, pointing="left"):
# import code; code.interact(local=dict(globals(), **locals()))
self.x, self.y = start_x, start_y
self.maze_map = maze_map
self.pointing = pointing
"""Coefficients for use in other methods:
[list rotation index, x _shift, y _shift, symbol]"""
directions = {
"up": [0, 0, -1, "^"],
"right": [1, 1, 0, ">"],
"down": [2, 0, 1, "v"],
"left": [3, -1, 0, "<"]
}
def perform(self):
# Crawl one space starting from leftmost available path
movement_list = self._movements_to_try()
self._move_in_order(movement_list)
return CrawlerPosition(self.x, self.y, self.pointing)
def flip(self):
#Turn crawler 90deg clockwise
if self.pointing == "up":
self.pointing = "down"
elif self.pointing == "right":
self.pointing = "left"
elif self.pointing == "down":
self.pointing = "up"
elif self.pointing == "left":
self.pointing = "right"
"""Private Methods"""
def _movements_to_try(self):
cls = self.__class__
movements = ["left", "up", "right", "down"]
movement_idx = cls.directions[self.pointing][0]
list_rotator = lambda lst, n: lst[n:] + lst[:n]
movements = list_rotator(movements, movement_idx)
return movements
def _move_in_order(self, direction_list):
# Attempts to move crawler in order of preference
for direction in direction_list:
if self._is_space(direction):
self._shift(direction)
break
def _shift(self, direction):
# Move crawler into adjacent empty space and updates direction pointer
cls = self.__class__
self.x = self.x+cls.directions[direction][1]
self.y = self.y+cls.directions[direction][2]
self.pointing = direction
# print(cls.directions[direction][3]) # Print direction indicator (<>^v)
def _is_space(self, direction):
# Check if adjacent space is a path or wall
cls = self.__class__
row = self.x+cls.directions[direction][1] - 1
column = self.y+cls.directions[direction][2] - 1
try:
if self.maze_map[column][row] == " " or self.maze_map[column][row] == "F":
# Is a path
return True
else:
# Is a wall
return False
except IndexError:
# Is edge of maze_map (first/last index in row or column array)
return False