import math
import tkinter as tk

WIDTH = 160
HEIGHT = 120
SCALE = 3

root = tk.Tk()
root.title("CRT Pixel Demoscene")

canvas = tk.Canvas(root, width=WIDTH*SCALE, height=HEIGHT*SCALE)
canvas.pack()

img = tk.PhotoImage(width=WIDTH, height=HEIGHT)
canvas.create_image((0, 0), image=img, anchor="nw")

t = 0.0

def update():
    global t
    rows = []
    for y in range(HEIGHT):
        row_colors = []
        for x in range(WIDTH):
            nx = (x / (WIDTH - 1)) * 2 - 1
            ny = (y / (HEIGHT - 1)) * 2 - 1

            #ripple
            value = math.sin(10 * (nx**2 + ny**2) - t)
            value += 0.3 * math.sin(5 * nx + 5 * ny - t * 0.5)

            #neighbors mix together
            nx_offset = 0.01
            ny_offset = 0.01
            neighbor = math.sin(10 * ((nx+nx_offset)**2 + (ny+ny_offset)**2) - t)
            value = 0.8 * value + 0.2 * neighbor

            # Convert to brightness 0-255
            brightness = int((value + 1) / 2 * 255)

            # make rows darker
            if y % 2 == 0:
                brightness = int(brightness * 0.6)

            # Clamp
            brightness = max(0, min(255, brightness))
            color = f'#{brightness:02x}{brightness:02x}{brightness:02x}'
            row_colors.append(color)
        rows.append("{" + " ".join(row_colors) + "}")
    img.put(" ".join(rows))
    t += 0.1
    root.after(30, update)

update()
root.mainloop()

