From c089762042488f800fb121d85fb0ff78f4599a06 Mon Sep 17 00:00:00 2001 From: setop Date: Sat, 10 Dec 2022 17:42:29 +0100 Subject: [PATCH] day 9, add terminal animation --- d09/animp.py | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 d09/animp.py diff --git a/d09/animp.py b/d09/animp.py new file mode 100644 index 0000000..9f76065 --- /dev/null +++ b/d09/animp.py @@ -0,0 +1,61 @@ +import sys, os +import numpy +import time + +class display: + def __init__(self): + self.w, self.h = tuple(os.get_terminal_size()) + #self.h -= 1 + border = "o" + self.delta = numpy.array((self.w//2, self.h//2)) + top = border * (self.w) + line = border + " " * (self.w - 2) + border + self.background = top + "".join( + line for _ in range(self.h - 2)) + top + + def __call__(self, knots): + print("\033[0;0H", end='') + x, y = self.delta + knots[0] + J = 20 + 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] + for i,knot in enumerate(reversed(knots)): + x, y = knot + self.delta + txt[int(x + y * self.w)] = str(9-i) + 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))