/* ---------------------------------------------------------------------------
| Filename:     mines.c
|
| Authors:	Thomas Braunl   
|
| Description:  find the mines
| ------------------------------------------------------------------------- */

#include "eyebot.h" 
#include <stdlib.h>

#define len        7    /* # rows      */
#define wid       12    /* # columns   */
#define mine_fac  25    /* mine factor */

int field[len+2][wid+2];  /* 0 or 1 for mine, with 1 surrounding line */
int calc [len+2][wid+2];  /* # of neighboring mines */
int check[len+2][wid+2];  /* checked for empty neighbors */

void clear(int y, int x)
/* write spaces around elements with zero count */
{ int i,j;
  if (!check[y][x])
    {  check[y][x] = 1;
       LCDSetChar(y-1,x-1, ' ');  /* current position */

       for (i=y-1; i<=y+1; i++) for (j=x-1; j<=x+1; j++)
        if ((i>=1) && (i<=len) && (j>=1) && (j<=wid))
        { if (calc[i][j])
            LCDSetChar(i-1,j-1, (char) (48 +calc[i][j]) );
          else clear(i,j);
        }
    }
}


int main()
{ int i,j,k, hit=0, x=0, y=0, xd=1, yd=1;

  /* display menu */
  LCDMenu("Y","X","+/-","CHK");

  /* init field, border 0, inner random */
  for (i=0; i<=len+1; i++) for (j=0; j<=wid+1; j++)
  { field[i][j] = 0;
    check[i][j] = 0;
  }
  for (i=1; i<=len  ; i++) for (j=1; j<=wid;   j++)
    if ((rand() % 100) < mine_fac) field[i][j] = 1;

  /* do neighbor calculation */
  for (i=1; i<=len; i++) for (j=1; j<=wid; j++)
    calc[i][j] = field[i-1][j-1] +field[i-1][j] +field[i-1][j+1]
                +field[i  ][j-1] +field[i  ][j] +field[i  ][j+1]
                +field[i+1][j-1] +field[i+1][j] +field[i+1][j+1];
  /* print field */
  for (i=1; i<=len; i++) for (j=1; j<=wid; j++) LCDSetChar(i-1,j-1,'_');

  do{
    k=KEYRead();
    switch (k) {
      case KEY1: y = (y + yd + len) % len;  break;  /* up/down 0..len-1 */
      case KEY2: x = (x + xd + wid) % wid;  break;  /* left/right */
      case KEY3: xd = -xd; yd = -yd;  break;        /* +/-        */
      case KEY4: if (field[y+1][x+1])               /* mine hit   */
                 { hit=1;
                   for (i=1; i<=len; i++) for (j=1; j<=wid; j++)
                     if (field[i][j]) LCDSetChar(i-1,j-1,'*'); 
                 }
                 else if (calc[y+1][x+1] == 0)      /* zero field */
                      clear(y+1,x+1);
                 else LCDSetChar(y,x, (char) (48 +calc[y+1][x+1]) );
                 break;                       /* just print count */
    }
    LCDSetPos(y,x);
  } while (!hit);
  return 0;
}

