From abbf1c85e1479ea7edf2b0defdd9fd4c7a978ab8 Mon Sep 17 00:00:00 2001 From: Stefan Harmuth Date: Sat, 11 Dec 2021 06:45:24 +0100 Subject: [PATCH] grid.Grid: finally add that stupid print() method I'm always writing for debugging grid.Grid: add(), sub() and set() return what they've actually wrote to the cell --- tools/grid.py | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/tools/grid.py b/tools/grid.py index d90cae6..8111f27 100644 --- a/tools/grid.py +++ b/tools/grid.py @@ -1,7 +1,7 @@ from __future__ import annotations from .coordinate import Coordinate from enum import Enum -from typing import Union, Any +from typing import Any, List, Union OFF = False ON = True @@ -46,7 +46,7 @@ class Grid: self.__trackBoundaries(pos) self.__grid[pos] = not self.__default - def set(self, pos: Coordinate, value: Any = True): + def set(self, pos: Coordinate, value: Any = True) -> Any: if pos.z is not None: self.mode3D = True @@ -56,6 +56,8 @@ class Grid: self.__trackBoundaries(pos) self.__grid[pos] = value + return value + def get(self, pos: Coordinate) -> Any: if pos in self.__grid: return self.__grid[pos] @@ -98,11 +100,11 @@ class Grid: else: return self.minX <= pos.x <= self.maxX and self.minY <= pos.y <= self.maxY - def add(self, pos: Coordinate, value: Union[float, int] = 1): - self.set(pos, self.get(pos) + value) + def add(self, pos: Coordinate, value: Union[float, int] = 1) -> Union[float, int]: + return self.set(pos, self.get(pos) + value) - def sub(self, pos: Coordinate, value: Union[float, int] = 1): - self.set(pos, self.get(pos) - value) + def sub(self, pos: Coordinate, value: Union[float, int] = 1) -> Union[float, int]: + return self.set(pos, self.get(pos) - value) def getActiveCells(self): return list(self.__grid.keys()) @@ -115,6 +117,18 @@ class Grid: return grid_sum + def getNeighboursOf(self, pos: Coordinate, includeDefault: bool = False, includeDiagonal: bool = True) \ + -> List[Coordinate]: + neighbours = pos.getNeighbours( + includeDiagonal=includeDiagonal, + minX=self.minX, minY=self.minY, minZ=self.minZ, + maxX=self.maxX, maxY=self.maxY, maxZ=self.maxZ + ) + if includeDefault: + return neighbours + else: + return [x for x in neighbours if self.get(x) != self.__default] + def getNeighbourSum(self, pos: Coordinate, includeNegative: bool = True, includeDiagonal: bool = True) \ -> Union[float, int]: neighbour_sum = 0 @@ -169,3 +183,11 @@ class Grid: elif mode == GridTransformation.ROTATE_TWICE: self.transform(GridTransformation.ROTATE_RIGHT) self.transform(GridTransformation.ROTATE_RIGHT) + + def print(self, spacer: str = ""): + for y in range(self.minY, self.maxY + 1): + for x in range(self.minX, self.maxX + 1): + print(self.get(Coordinate(x, y)), end="") + print(spacer, end="") + + print()