#include <vectrex.h>


#define ASTEROIDS 12


#define BIG    -1,120,120, -1,120,0,  -1,120,-120, -1,0,-120,  -1,-120,-120, -1,-120,0,  -1,-120,120,  -1,0,120,  1

#define MEDIUM -1,80,80,   -1,80,0,   -1,80,-80,   -1,0,-80,   -1,-80,-80,   -1,-80,0,   -1,-80,80,  -1,0,80,     1

#define SMALL  -1,60,60,   -1,60,0,   -1,60,-60,   -1,0,-60,   -1,-60,-60,   -1,-60,0,   -1,-60,60,  -1,0,60,     1


const int vector[((unsigned long)ASTEROIDS) * (8UL * 3UL + 1UL)] = { /* octagons for now, later asteroids */
  /*  0 */ BIG,
  /*  1 */ BIG,
  /*  2 */ MEDIUM,
  /*  3 */ MEDIUM,
  /*  4 */ MEDIUM,
  /*  5 */ MEDIUM,
  /*  6 */ SMALL,
  /*  7 */ SMALL,
  /*  8 */ SMALL,
  /*  9 */ SMALL,
  /* 10 */ SMALL,
  /* 11 */ SMALL,
};

static int x[ASTEROIDS], y[ASTEROIDS];

static int dx[ASTEROIDS*2] = {
  1,1,2,1,1,2,1,1,1,2,-1,-1,
  2,2,2,2,2,2,2,2,2,2,-2,-2,
};

static int dy[ASTEROIDS*2] = {
  -1,1,-1,1,-1,1,-1,1,-1,1,-1,1,
  -1,2,-2,1,-2,2,-2,1,-2,2,-2,1,
};

static char DEMO[15];

const signed char BouncerTitle[7][17] = { // count, moveto, drawtos...

 {+0x05, +0x67, -0x5A, -0x2E, -0x05, +0x11, +0x1C, +0x08, -0x0D, +0x0E, +0x09, +0x07, -0x13,},
 {+0x06, +0x51, -0x38, -0x0D, -0x0C, -0x0E, +0x04, +0x03, +0x11, +0x0C, +0x07, +0x0F, -0x05, -0x02, -0x0A,},
 {+0x03, +0x57, -0x1F, -0x18, -0x09, -0x09, +0x13, +0x19, +0x06,},
 {+0x04, +0x56, -0x05, -0x1F, -0x05, +0x1F, +0x0A, +0x01, +0x0D, -0x20, +0x00,},
 {+0x04, +0x59, +0x26, -0x03, -0x0F, -0x11, -0x04, -0x0E, +0x03, +0x04, +0x13,},
 {+0x07, +0x4D, +0x38, +0x04, +0x0D, +0x06, +0x03, +0x03, -0x0F, -0x05, -0x0A, -0x0F, -0x02, -0x0E, +0x03, +0x02, +0x15,},
 {+0x04, +0x5A, +0x50, -0x04, +0x03, -0x1E, -0x03, +0x20, +0x06, +0x02, +0x0F,},
};

#include "graphics.inc"


// USER CODE:


static char *p;

int init(void) {
  int row;

  cstrcpy(DEMO, "TICK: 0000000\x80"); // long enough to allow freewheeling counter...

  p = DEMO+12;

  for (row = 0; row < ASTEROIDS; row++) {
    x[row] = random(); y[row] = random();
  }

  return 0;
}

static int base=0;

int loop(void) {
  int row, tmp1, idx;

  while (*p == '9') { // find digit to increment - X9999 becomes (X+1)0000

    *p-- = '0';
    if (*p == ' ') {
      cstrcpy(DEMO, "TICK: 0000000\x80");
      p = DEMO+12;
    }
  }
  *p += 1;
  p = DEMO+12;

  for (row = 0; row < ASTEROIDS; row++) {
    // Bounce off wall - detected when incrementing or decrementing causes over/under-flow

    tmp1 = x[row] + dx[idx=base+row];
    if ((dx[idx] > 0 && x[row] > 0 && tmp1 < 0) || (dx[idx] < 0 && x[row] < 0 && tmp1 > 0)) {
      dx[idx] = -dx[idx];
    } else {
      x[row] = tmp1;
    }
    tmp1 = y[row] + dy[idx];
    if ((dy[idx] > 0 && y[row] > 0 && tmp1 < 0) || (dy[idx] < 0 && y[row] < 0 && tmp1 > 0)) {
      dy[idx] = -dy[idx];
    } else {
      y[row] = tmp1;
    }        
  }
  base ^= ASTEROIDS;

  return 0;
}