-
Notifications
You must be signed in to change notification settings - Fork 0
/
obstacles.py
88 lines (62 loc) · 2.81 KB
/
obstacles.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
79
80
81
82
83
84
85
86
87
88
import asyncio
from curses_tools import draw_frame
class Obstacle:
def __init__(self, row, column, rows_size=1, columns_size=1, uid=None):
self.row = row
self.column = column
self.rows_size = rows_size
self.columns_size = columns_size
self.uid = uid
def get_bounding_box_frame(self):
# increment box size to compensate obstacle movement
rows, columns = self.rows_size + 1, self.columns_size + 1
return '\n'.join(_get_bounding_box_lines(rows, columns))
def get_bounding_box_corner_pos(self):
return self.row - 1, self.column - 1
def dump_bounding_box(self):
row, column = self.get_bounding_box_corner_pos()
return row, column, self.get_bounding_box_frame()
def has_collision(self, obj_corner_row, obj_corner_column, obj_size_rows=1, obj_size_columns=1):
'''Determine if collision has occured. Return True or False.'''
return has_collision(
(self.row, self.column),
(self.rows_size, self.columns_size),
(obj_corner_row, obj_corner_column),
(obj_size_rows, obj_size_columns),
)
def _get_bounding_box_lines(rows, columns):
yield ' ' + '-' * columns + ' '
for _ in range(rows):
yield '|' + ' ' * columns + '|'
yield ' ' + '-' * columns + ' '
async def show_obstacles(canvas, obstacles):
"""Display bounding boxes of every obstacle in a list"""
while True:
boxes = []
for obstacle in obstacles:
boxes.append(obstacle.dump_bounding_box())
for row, column, frame in boxes:
draw_frame(canvas, row, column, frame)
await asyncio.sleep(0)
for row, column, frame in boxes:
draw_frame(canvas, row, column, frame, negative=True)
def _is_point_inside(corner_row, corner_column, size_rows, size_columns, point_row, point_row_column):
rows_flag = corner_row <= point_row < corner_row + size_rows
columns_flag = corner_column <= point_row_column < corner_column + size_columns
return rows_flag and columns_flag
def has_collision(obstacle_corner, obstacle_size, obj_corner, obj_size=(1, 1)):
'''Determine if collision has occured. Return True or False.'''
opposite_obstacle_corner = (
obstacle_corner[0] + obstacle_size[0] - 1,
obstacle_corner[1] + obstacle_size[1] - 1,
)
opposite_obj_corner = (
obj_corner[0] + obj_size[0] - 1,
obj_corner[1] + obj_size[1] - 1,
)
return any([
_is_point_inside(*obstacle_corner, *obstacle_size, *obj_corner),
_is_point_inside(*obstacle_corner, *obstacle_size, *opposite_obj_corner),
_is_point_inside(*obj_corner, *obj_size, *obstacle_corner),
_is_point_inside(*obj_corner, *obj_size, *opposite_obstacle_corner),
])