-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmap.py
71 lines (54 loc) · 1.65 KB
/
map.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
from collections import namedtuple
from dataclasses import dataclass
from typing import List
PosType = namedtuple("Pos", "x y")
class Pos(PosType):
@property
def adjacent(self):
for offset in [Pos(-1, 0), Pos(1, 0), Pos(0, -1), Pos(0, 1)]:
yield offset
def add(self, other):
return Pos(self.x + other.x, self.y + other.y)
def subtract(self, other):
return Pos(self.x - other.x, self.y - other.y)
@dataclass
class Map:
map: List[List[str]]
@property
def width(self):
return len(self.map[0])
@property
def height(self):
return len(self.map)
def get(self, pos):
if not self.in_map(pos):
raise Exception(f"{pos} outside of map")
return self.map[pos.y][pos.x]
def set(self, pos, val):
if not self.in_map(pos):
raise Exception(f"{pos} outside of map")
self.map[pos.y][pos.x] = val
def in_map(self, pos):
return all(
[
pos.x >= 0,
pos.x < self.width,
pos.y >= 0,
pos.y < self.height,
]
)
@property
def all_positions(self):
for x in range(self.width):
for y in range(self.height):
yield Pos(x, y)
def draw(self, positions={}):
print(f"Map: {self.width} x {self.height}")
for y in range(self.height):
for x in range(self.width):
pos = Pos(x, y)
if pos in positions:
print(positions[pos], end=" ")
else:
print(self.get(pos), end=" ")
print()