1import itertools
2import random
3import time
4
5from curtsies import FullscreenWindow, Input, FSArray
6from curtsies.fmtfuncs import red, bold, green, on_blue, yellow, on_red
7
8MAX_FPS = 1000
9time_per_frame = 1. / MAX_FPS
10
11class FrameCounter:
12    def __init__(self):
13        self.render_times = []
14        self.dt = .5
15    def frame(self):
16        self.render_times.append(time.time())
17    def fps(self):
18        now = time.time()
19        while self.render_times and self.render_times[0] < now - self.dt:
20            self.render_times.pop(0)
21        return len(self.render_times) / max(self.dt, now - self.render_times[0] if self.render_times else self.dt)
22
23def main():
24    counter = FrameCounter()
25    with FullscreenWindow() as window:
26        print('Press escape to exit')
27        with Input() as input_generator:
28            a = FSArray(window.height, window.width)
29            c = None
30            for framenum in itertools.count(0):
31                t0 = time.time()
32                while True:
33                    t = time.time()
34
35                    temp_c = input_generator.send(max(0, t - (t0 + time_per_frame)))
36                    if temp_c is not None:
37                        c = temp_c
38
39                    if c is None:
40                        pass
41                    elif c == '<ESC>':
42                        return
43                    elif c == '<SPACE>':
44                        a = FSArray(window.height, window.width)
45                    else:
46                        row = random.choice(range(window.height))
47                        column = random.choice(range(window.width-len(c)))
48                        a[row:row+1, column:column+len(c)] = [c]
49
50                    c = None
51                    if time_per_frame < t - t0:
52                        break
53
54                row = random.choice(range(window.height))
55                column = random.choice(range(window.width))
56                a[row:row+1, column:column+1] = [random.choice(".,-'`~")]
57
58                fps = 'FPS: %.1f' % counter.fps()
59                a[0:1, 0:len(fps)] = [fps]
60
61                window.render_to_terminal(a)
62                counter.frame()
63
64if __name__ == '__main__':
65    main()
66