Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Intcode } from "../intcode/intcode";
- import { Store } from "../intcode/store";
- import { handleByLine, colorize, Colors } from "../utils";
- enum Color {
- Black = 0,
- White = 1
- }
- enum Turn {
- Left = 0,
- Right = 1
- }
- enum Direction {
- Up,
- Right,
- Down,
- Left
- }
- class Painter {
- private readonly initialPosition = `0,0`;
- private currentPosition: string = this.initialPosition;
- private currentDirection: Direction = Direction.Up;
- private positions: { [position: string]: Color } = {
- [this.initialPosition]: Color.White
- };
- constructor(private intcode: Intcode) {}
- run() {
- while (true) {
- let input = this.getColor(this.currentPosition);
- this.paintCurrentPosition(this.intcode.run(input).output);
- this.turn(this.intcode.run(input).output);
- this.move(1);
- if (this.intcode.isTerminated()) {
- break;
- }
- }
- this.visualize();
- }
- getColor(position: string): Color {
- return this.positions[position] || Color.Black;
- }
- paintCurrentPosition(color: Color) {
- this.positions[this.currentPosition] = color;
- }
- move(steps: number) {
- let [x, y] = this.currentPosition.split(",").map(p => parseInt(p));
- switch (this.currentDirection) {
- case Direction.Up:
- y += steps;
- break;
- case Direction.Right:
- x += steps;
- break;
- case Direction.Down:
- y -= steps;
- break;
- case Direction.Left:
- x -= steps;
- break;
- }
- this.currentPosition = `${x},${y}`;
- }
- turn(direction: Turn) {
- switch (this.currentDirection) {
- case Direction.Up:
- this.currentDirection =
- direction === Turn.Left ? Direction.Left : Direction.Right;
- break;
- case Direction.Right:
- this.currentDirection =
- direction === Turn.Left ? Direction.Up : Direction.Down;
- break;
- case Direction.Down:
- this.currentDirection =
- direction === Turn.Left ? Direction.Right : Direction.Left;
- break;
- case Direction.Left:
- this.currentDirection =
- direction === Turn.Left ? Direction.Down : Direction.Up;
- break;
- }
- }
- visualize() {
- //TODO: Possible optimization: consolidate loops
- const coords = Object.keys(this.positions).map(p => {
- const [x, y] = p.split(",").map(p => parseInt(p));
- return { x, y };
- });
- const minX = Math.min(...coords.map(c => c.x));
- const maxX = Math.max(...coords.map(c => c.x));
- const minY = Math.min(...coords.map(c => c.y));
- const maxY = Math.max(...coords.map(c => c.y));
- const padding = 2;
- for (let y = maxY + padding; y >= minY - padding; y--) {
- for (let x = minX - padding; x <= maxX + padding; x++) {
- let color = this.getColor(`${x},${y}`);
- let output = colorize(
- color === Color.Black ? Colors.FgBlack : Colors.FgWhite,
- "██"
- );
- process.stdout.write(output);
- }
- process.stdout.write("\n");
- }
- }
- }
- handleByLine(`data.txt`, line => {
- const intcode = new Intcode(new Store(line.split(",")));
- const painter = new Painter(intcode);
- painter.run();
- });
Add Comment
Please, Sign In to add comment