#include <SPI.h>
#include <GD.h>

#include "froggerbg.h" // http://gameduino.com/results/5f30d40b/
#include "sprite.h"    // http://gameduino.com/results/1d2bd1ca/

#define BG_BLUE   0
#define BG_ZERO   12
#define BG_BLACK  34
#define BG_LIFE   35

static uint16_t atxy(byte x, byte y)
{
  return RAM_PIC + 64 * y + x;
}

static void draw_score(uint16_t dst, long n)
{
  GD.wr(dst + 0, BG_ZERO + (n / 10000) % 10);   // ten-thousands
  GD.wr(dst + 1, BG_ZERO + (n / 1000) % 10);    // thousands
  GD.wr(dst + 2, BG_ZERO + (n / 100) % 10);     // hundreds
  GD.wr(dst + 3, BG_ZERO + (n / 10) % 10);      // tens
  GD.wr(dst + 4, BG_ZERO + n % 10);             // ones
}

void setup()
{
  GD.begin();
  GD.copy(RAM_CHR, froggerbg_chr, sizeof(froggerbg_chr));
  GD.copy(RAM_PAL, froggerbg_pal, sizeof(froggerbg_pal));
  for (byte y = 0; y < 32; y++)
    GD.copy(atxy(0, y), froggerbg_pic + y * 28, 28);
  GD.fill(atxy(0, 1), BG_BLUE, 28);

  GD.copy(PALETTE16A, sprite_sprpal, sizeof(sprite_sprpal));
  GD.uncompress(RAM_SPRIMG, sprite_sprimg);
  Serial.begin(1000000); // JCB
}

static unsigned int t;

static void sprite(unsigned int x, int y, byte anim, byte rot = 0)
{ 
  draw_sprite(x % 256, y, anim, rot);
} 

void loop()
{
  GD.waitvblank();
  draw_score(atxy(3, 1), t);

  GD.__wstartspr(0);

  // JCB-ROAD-A
  // Trucks
  sprite(-t/2,       152, 5);
  sprite(-t/2 + 16,  152, 6);
  sprite(-t/2 + 100, 152, 5);
  sprite(-t/2 + 116, 152, 6);

  // Green and white racecars
  sprite(2 * t,    168, 8);

  // Purple cars
  sprite(-t,       184, 7);
  sprite(-t + 75,  184, 7);
  sprite(-t + 150, 184, 7);

  // Dozers
  sprite(t,        200, 4);
  sprite(t + 50,   200, 4);
  sprite(t + 150,  200, 4);

  // Yellow cars
  sprite(-t,       216, 3);
  sprite(-t + 128, 216, 3);
  // JCB-ROAD-B

  GD.__end();

  GD.screenshot(t); // JCB
  t++;
}
