May-13-2023, 05:27 PM
(This post was last modified: May-13-2023, 05:27 PM by Phidias618.)
class SomeBoard: def __init__(self, width, height): self.width = width self.height = height self.grid = [[0 for _ in range(width)] for _ in range(height)] self._iter_data: list[list] = [] def __getitem__(self, co: tuple[int, int]): return self.grid[co[1]][co[0]] def __iter__(self): self._iter_data.append([-1, 0]) return self def __next__(self): last = _iter_data[-1] last[0] += 1 if last[0] == self.width: last[0] = 0 last[1] += 1 if last[1] == self.height: del self._iter_data[-1] raise StopIteration return last[0], last[1], self.grid[last[0], last[1]] board = SomeBoard(8, 8) # do something with it for x, y, tile in board: break print(board._iter_data)The probleme is that i can't break when I iterate trough CustomBoard, because that will leave date inside _iter_data
with a __break__ dunder I could simply solve this by:
def __break__(self): del self._iter_data[-1]And now the iterator will work properly
But if _iter_data were only made of one list containing the x and y coordinate then I couldn't iterate trough a CustomBoard instance like this:
board = CustomBoard(8, 8) for x1, y1, tile1 in board: for x2, y2, tile2 in board: # do something ...The problem now is that this program will result in an endless loop