|
| 1 | +from GhostyUtils import aoc |
| 2 | +from GhostyUtils.grid import Grid |
| 3 | +from GhostyUtils.vec2 import Vec2, Dir |
| 4 | + |
| 5 | + |
| 6 | +class Robot: |
| 7 | + def __init__(self, pos: Vec2) -> 'Robot': |
| 8 | + self.pos = Vec2(pos) |
| 9 | + |
| 10 | + def move(self, dir: Dir, grid: Grid) -> bool: |
| 11 | + if grid[self.pos + dir].move(dir, grid): |
| 12 | + grid[self.pos] = Air(self.pos) |
| 13 | + self.pos += dir |
| 14 | + grid[self.pos] = self |
| 15 | + return True |
| 16 | + return False |
| 17 | + |
| 18 | + def __str__(self) -> str: |
| 19 | + return '@' |
| 20 | + |
| 21 | + |
| 22 | +class Box: |
| 23 | + def __init__(self, pos: Vec2) -> 'Box': |
| 24 | + self.pos = Vec2(pos) |
| 25 | + |
| 26 | + def move(self, dir: Dir, grid: Grid) -> bool: |
| 27 | + if grid[self.pos + dir].move(dir, grid): |
| 28 | + grid[self.pos] = Air(self.pos) |
| 29 | + self.pos += dir |
| 30 | + grid[self.pos] = self |
| 31 | + return True |
| 32 | + return False |
| 33 | + |
| 34 | + def __str__(self) -> str: |
| 35 | + return 'O' |
| 36 | + |
| 37 | + |
| 38 | +class Wall: |
| 39 | + def __init__(self, pos: Vec2) -> 'Wall': |
| 40 | + self.pos = Vec2(pos) |
| 41 | + |
| 42 | + def move(self, dir: Dir, grid: Grid) -> bool: |
| 43 | + return False |
| 44 | + |
| 45 | + def __str__(self) -> str: |
| 46 | + return '#' |
| 47 | + |
| 48 | + |
| 49 | +class Air: |
| 50 | + def __init__(self, pos: Vec2) -> 'Air': |
| 51 | + pass |
| 52 | + |
| 53 | + def move(self, dir: Dir, grid: Grid) -> bool: |
| 54 | + return True |
| 55 | + |
| 56 | + def __str__(self) -> str: |
| 57 | + return '.' |
| 58 | + |
| 59 | + |
| 60 | +def convert(cell: str, pos: Vec2) -> Robot | Box | Wall | Air: |
| 61 | + return {'@': Robot, '#': Wall, 'O': Box, '.': Air}[cell](pos) |
| 62 | + |
| 63 | + |
| 64 | +def main(): |
| 65 | + warehouse, instructions = aoc.read_sections() |
| 66 | + warehouse = Grid(warehouse.splitlines()) |
| 67 | + robot = None |
| 68 | + boxes = [] |
| 69 | + for cell, pos in warehouse.by_cell(): |
| 70 | + warehouse[pos] = convert(cell, pos) |
| 71 | + if type(warehouse[pos]) is Box: |
| 72 | + boxes.append(warehouse[pos]) |
| 73 | + elif type(warehouse[pos]) is Robot: |
| 74 | + robot = warehouse[pos] |
| 75 | + |
| 76 | + if aoc.args.verbose or aoc.args.progress: |
| 77 | + print(warehouse) |
| 78 | + |
| 79 | + for instr in instructions: |
| 80 | + if instr == '\n': |
| 81 | + continue |
| 82 | + robot.move(Dir.map_nswe('^v<>')[instr], warehouse) |
| 83 | + |
| 84 | + if aoc.args.verbose or aoc.args.progress: |
| 85 | + print(warehouse) |
| 86 | + |
| 87 | + print(f"p1: {sum(box.pos.y * 100 + box.pos.x for box in boxes)}") |
| 88 | + |
| 89 | + |
| 90 | +if __name__ == "__main__": |
| 91 | + main() |
0 commit comments