aoc2022/d09/anim.py

67 lines
1.9 KiB
Python

import sys, os
import numpy
import time
class display:
def __init__(self):
self.w, self.h = tuple(os.get_terminal_size())
border = "o"
self.delta = numpy.array((self.w//2, self.h//2))
top = border * (self.w)
wodd = self.w%2
lines = [
border + "" * (self.w//2-1) + ""*wodd + border,
border + "" * (self.w//2-1) + " "*wodd + border
]
self.background = [
top + "".join(lines[h%2] for h in range(self.h - 2)) + top,
top + "".join(lines[1-h%2] for h in range(self.h - 2)) + top
]
def __call__(self, knots):
print("\033[0;0H", end='')
x, y = self.delta + knots[0]
J = 19 # must be odd to see scroll
if x <= 0:
self.delta[0] += J
if x >= self.w-1:
self.delta[0] -= J
if y <= 0:
self.delta[1] += J
if y >= self.h-1:
self.delta[1] -= J
txt = [c for c in self.background[sum(self.delta)%2]]
for i,knot in enumerate(reversed(knots)):
x, y = knot + self.delta
txt[int(x + y * self.w)] = "\033[30;43m" + str(9-i) + "\033[0m"
print("".join(txt),end='')
time.sleep(.008)
d = display()
def input():
for l in sys.stdin:
m, q = l.split()
m = dict(U=(0,1), D=(0,-1), L=(-1,0), R=(1, 0))[m]
for _ in range(int(q)):
yield m
def follow(head, tail):
delta = head - tail
if max(abs(delta)) <= 1: # no move
return
if delta[0]:
tail[0] += 1 if delta[0] > 0 else -1
if delta[1]:
tail[1] += 1 if delta[1] > 0 else -1
knots = [numpy.array((0, 0)) for _ in range(10)]
visits = [ {(0,0)} for _ in range(10)]
for direction in input():
knots[0] += direction
for n in range(1, 10):
follow(knots[n-1], knots[n])
d(knots)
visits[n].add(tuple(knots[n]))
print(" ".join(str(len(v)) for v in visits))