class Grid(): def __init__(self): self.sandCount = 0 self._grid = [] for _ in range(maxY): self._grid.append([]) for line in self._grid: for _ in range(maxX): line.append('.') for i in range(len(self._grid[-1])): self._grid[-1][i] = '#' def drawRocks(self, start, end): if start[0] == end[0]: _min = min(start[1], end[1]) _max = max(start[1], end[1]) for i in range(_max - _min + 1): self._grid[_min + i][start[0]-modifier] = '#' if start[1] == end[1]: _min = min(start[0], end[0]) - modifier _max = max(start[0], end[0]) - modifier for i in range(_max - _min + 1): self._grid[start[1]][_min + i] = '#' def printGrid(self): for line in self._grid: tempA = '' for coord in line: tempA += coord print(tempA) def sand(self): while True: posX = 500 - modifier posY = 0 while True: if posX == 0: self.expand('left') posX += 1 if posX == len(self._grid[0]) - 1: self.expand('rigth') if self._grid[posY + 1][posX] == '.': posY += 1 elif self._grid[posY +1][posX - 1] == '.': posY += 1 posX -= 1 elif self._grid[posY +1][posX + 1] == '.': posY += 1 posX += 1 else: self._grid[posY][posX] = 'o' self.sandCount += 1 if posY == 0 and posX == 500 - modifier: return break def expand(self, direction): global modifier if direction == 'left': for i in (range(len(self._grid)-1)): self._grid[i].insert(0, '.') self._grid[-1].insert(0, '#') modifier -= 1 if direction == 'rigth': for i in (range(len(self._grid)-1)): self._grid[i].append('.') self._grid[-1].append('#') def evaluate(self): return self.sandCount with open('input14.txt','r') as f: inp = f.read().splitlines(keepends=False) lines = [] for line in inp: lines.append(line.split(' -> ')) for i in range(len(lines)): for j in range(len(lines[i])): lines[i][j] = tuple(map(int, lines[i][j].split(','))) maxY = None modifier = None maxX = None for line in lines: for point in line: if modifier is None or modifier > point[0]: modifier = point[0] if maxX is None or maxX < point[0]: maxX = point[0] if maxY is None or maxY < point[1]: maxY = point[1] maxX = maxX - (modifier - 3) modifier -= 1 maxY += 3 cave = Grid() cave.printGrid() for line in lines: for j in range(len(line)-1): cave.drawRocks(line[j], line[j+1]) print('---------------') cave.printGrid() print('---------------') cave.sand() cave.printGrid() print('---------------') print(cave.evaluate())