|
| 1 | +# Advent of Code 2019, Day 8, Part 2 |
| 2 | +# Author: Joth (https://github.com/joth00) |
| 3 | + |
| 4 | +from os import path |
| 5 | + |
| 6 | + |
| 7 | +def main(): |
| 8 | + text_input = get_raw_input() |
| 9 | + raw_image = [int(x) for x in text_input] |
| 10 | + |
| 11 | + WIDTH = 25 |
| 12 | + HEIGHT = 6 |
| 13 | + |
| 14 | + layers = [] |
| 15 | + |
| 16 | + i = 0 |
| 17 | + while i < len(raw_image): |
| 18 | + j = i + WIDTH*HEIGHT |
| 19 | + layers.append(Layer.from_raw_data(raw_image[i:j], WIDTH, HEIGHT)) |
| 20 | + i = j |
| 21 | + |
| 22 | + final_image = Image(WIDTH, HEIGHT) |
| 23 | + |
| 24 | + for layer in reversed(layers): |
| 25 | + layer.add_to_image(final_image) |
| 26 | + |
| 27 | + final_image.visualize() |
| 28 | + |
| 29 | + |
| 30 | + |
| 31 | +class Image: |
| 32 | + BLACK = 0 |
| 33 | + WHITE = 1 |
| 34 | + TRANSPARENT = 2 |
| 35 | + |
| 36 | + def __init__(self, width, height): |
| 37 | + self._data = [[0]*width for _ in range(height)] |
| 38 | + |
| 39 | + def put(self, pixel, row, column): |
| 40 | + if pixel != Image.TRANSPARENT: |
| 41 | + self._data[row][column] = pixel |
| 42 | + |
| 43 | + def visualize(self): |
| 44 | + for row in self._data: |
| 45 | + line = '' |
| 46 | + for pixel in row: |
| 47 | + if pixel == Image.BLACK: |
| 48 | + line += '\u001b[30m\u2588'*2 |
| 49 | + elif pixel == Image.WHITE: |
| 50 | + line += '\u001b[37m\u2588'*2 |
| 51 | + elif pixel == Image.TRANSPARENT: |
| 52 | + line += ' '*2 |
| 53 | + print(line) |
| 54 | + print('\u001b[0m') |
| 55 | + |
| 56 | + |
| 57 | +class Layer: |
| 58 | + def __init__(self, layer_data): |
| 59 | + self._data = layer_data |
| 60 | + |
| 61 | + @staticmethod |
| 62 | + def from_raw_data(raw_data, width, height): |
| 63 | + data = [[0]*width for _ in range(height)] |
| 64 | + for i in range(height): |
| 65 | + for j in range(width): |
| 66 | + data[i][j] = raw_data[i*width + j] |
| 67 | + return Layer(data) |
| 68 | + |
| 69 | + |
| 70 | + def add_to_image(self, img): |
| 71 | + for i in range(len(self._data)): |
| 72 | + for j in range(len(self._data[i])): |
| 73 | + img.put(self._data[i][j], i, j) |
| 74 | + |
| 75 | + |
| 76 | +def get_raw_input(): |
| 77 | + return open(retrieve_input_file_path(), 'r').read() |
| 78 | + |
| 79 | + |
| 80 | +def retrieve_input_file_path(): |
| 81 | + return path.join(path.dirname(__file__), 'input.txt') |
| 82 | + |
| 83 | + |
| 84 | +main() |
0 commit comments