#!/usr/bin/env python3

import sys
import os
import numpy as np
import pygame

Nx = int(sys.argv[1])
Ny = int(sys.argv[2])
try:
    fps = float(sys.argv[3])
except (IndexError, ValueError):
    fps = 1.0


def point2idx(x,y):
    return 3*(x+Nx*y)

def set_pixel_max(buffer, x, y):
    idx = point2idx(x,y)
    for i in range(3):
        buffer[idx+i] = max(0x00, buffer[idx+i]-1)

def set_pixel_rand(buffer, x, y):
    idx = point2idx(x,y)
    for i in range(3):
        buffer[idx+i] = np.random.randint(0x00, 0xff)

clock = pygame.time.Clock()
buffer = bytearray(b"\x00"*(3*Nx*Ny))

i = 0
while True:
    i = i + 1
    for px in range(Nx):
        for py in range(Ny):
            set_pixel_max(buffer, px, py)
    for j in range(10):
        set_pixel_rand(buffer, np.random.randint(0, Nx), np.random.randint(0, Ny))
        if i > 100:
            os.write(1, buffer)
            clock.tick_busy_loop(fps)