import Image
import gameduino.prep as gdprep
import gameduino.remote
import gameduino
import array
import sys
import time

im = Image.new("RGB", (400,300))
def paint(y, rgb):
  qrgb = [int(c) & 0xf8 for c in rgb]
  for x in range(400):
    im.putpixel((x, y), tuple(qrgb))

def lerp(t, a, b):
    return a + t * (b - a)

def clerp(t, ta, tb):
    return tuple([int(lerp(t, a, b)) for (a, b) in zip(ta, tb)])

sky = (0,169,255)
sand = (249,214,114)
white = (255,255,255)

if 1:
    for i in range(160):
      paint(i, sky)
    for i in range(32):
        t = i / 31.
        paint(160 + i, clerp(t, sky, (255,255,255)))
        paint(160 + 63 - i, clerp(t, sand, (255,255,255)))
    for i in range(160+63, 300):
        paint(i, sand)
    im.save("desert.png")
    sys.exit(0)

# sky blends to white (32 lines), white meets sand (32 lines)
desert = array.array('H', [gdprep.rgb555(*clerp(i / 31., sky, white)) for i in range(32)] + [gdprep.rgb555(*clerp(i / 31., white, sand)) for i in range(32)])

gd = gameduino.remote.Gameduino(sys.argv[1], 115200)
gd.microcode(open("../../j1firmware/bgstripes.binle").read())
gd.wrstr(0x3e80, desert)
gd.wr16(gameduino.RAM_PAL, gameduino.TRANSPARENT)

gd.wr(gameduino.COMM+0, 150-32)

(dpic, dchr, dpal) = gdprep.encode(Image.open("chr.png"))
chars = Image.open("chr.png").convert("RGBA")
charset = [chars.crop((x, y, x+8, y+8)) for y in range(0, 128, 8) for x in range(0, 128, 8)]
dchr = array.array('B', [0] * 4096)
dpal = array.array('H', [0] * 1024)
for i,ci in enumerate(charset):
    dc,dp = gdprep.encodech(ci.tostring())
    dchr[16 * i:16 * i + 16] = array.array('B', dc)
    dpal[4 * i:4 * i + 4] = dp
dpal[0] = gameduino.TRANSPARENT
gd.wrstr(gameduino.RAM_CHR, dchr)
gd.wrstr(gameduino.RAM_PAL, dpal)

if 1:
    tiles = open("tiles").read()
    map = open("map").read()
    for yd in range(0, 128):
            gd.wr16(gameduino.SCROLL_Y, 511 & (yd * 16))
            for x in range(32):
                y = yd & 31
                t = ord(map[32 * (127 & yd) + x])
                tile = tiles[4 * t:4 * t + 4]
                gd.putstr(2 * x, 2 * y, tile[0:2])
                gd.putstr(2 * x, 2 * y + 1, tile[2:4])
