Grid.recalcBoundaries() (for when grids get smaller, which is not tracked by default)

Grid.from_str() and Grid.print() now accept translate dicts for more complex grid values
This commit is contained in:
Stefan Harmuth 2022-12-23 08:00:21 +01:00
parent 9e08c99ae1
commit 5bae00234c

View File

@ -61,6 +61,11 @@ class Grid:
self.minZ = pos.z if pos.z < self.minZ else self.minZ
self.maxZ = pos.z if pos.z > self.maxZ else self.maxZ
def recalcBoundaries(self) -> None:
self.minX, self.maxX, self.minY, self.maxY, self.minZ, self.maxZ = None, None, None, None, None, None
for c in self.__grid:
self.__trackBoundaries(c)
def getBoundaries(self) -> (int, int, int, int, int, int):
if self.mode3D:
return self.minX, self.minY, self.maxX, self.maxY, self.minZ, self.maxZ
@ -403,19 +408,26 @@ class Grid:
put_y = y
put_x += 1
def print(self, spacer: str = "", true_char: str = None, false_char: str = " ", mark: list = None):
def print(self, spacer: str = "", true_char: str = '#', false_char: str = " ", translate: dict = None, mark: list = None):
if translate is None:
translate = {}
if true_char is not None and True not in translate:
translate[True] = true_char
if false_char is not None and False not in translate:
translate[False] = false_char
for y in range(self.minY, self.maxY + 1):
for x in range(self.minX, self.maxX + 1):
if mark and Coordinate(x, y) in mark:
pos = Coordinate(x, y)
if mark and pos in mark:
print("X", end="")
elif true_char:
print(true_char if self.get(Coordinate(x, y)) else false_char, end="")
else:
value = self.get(Coordinate(x, y))
value = self.get(pos)
if isinstance(value, Enum):
print(value.value, end="")
else:
print(value, end="")
value = value.value
print(value if value not in translate else translate[value], end="")
print(spacer, end="")
print()
@ -435,10 +447,18 @@ class Grid:
)
@classmethod
def from_str(cls, grid_string: str, true_char: str = '#', true_value: Any = True, default: Any = False) -> 'Grid':
def from_str(cls, grid_string: str, default: Any = False, true_char: str = '#', true_value: Any = True, translate: dict = None) -> 'Grid':
if translate is None:
translate = {}
if true_char is not None and True not in translate.values():
translate[true_char] = true_value if true_value is not None else True
ret = cls(default=default)
for y, line in enumerate(grid_string.split("/")):
for x, c in enumerate(line):
ret.set(Coordinate(x, y), true_value if c == true_char else default)
if c in translate:
ret.set(Coordinate(x, y), translate[c])
else:
ret.set(Coordinate(x, y), c)
return ret