#include "digirule1.h"

///////////////////////////////////////////////////////////////////////////////
// private data

static const uint8 score_to_time[15] =
{
	250, 237, 225, 212, 200, 187, 175, 162, 150, 137, 125, 112, 100, 87, 75		// in milliseconds
};

static uint8 time, timer;

static enum
{
	StatePlay,
	StateGameOver,
} state;

static enum
{
	DirFwd,
	DirRev,
} dir;

///////////////////////////////////////////////////////////////////////////////
// public functions

void mode_game_init( void )
{
	all_leds_set( 0 );
	NOT_LED = 1;
	time = score_to_time[0];
	timer = 0;
	state = StatePlay;
	dir = DirFwd;
}

void mode_game_process( void )
{
	switch( state )
	{
		case StatePlay:
			if( ++timer == time )
			{
				switch( dir )				// scan LEDs
				{
					case DirFwd:
						if( NOT_LED )
						{
							NOT_LED = 0;
							OR_LED = 1;
						}
						else if( OR_LED )
						{
							OR_LED = 0;
							AND_LED = 1;
						}
						else if( AND_LED )
						{
							AND_LED = 0;
							XOR_LED = 1;
						}
						else if( XOR_LED )
						{
							XOR_LED = 0;
							NOR_LED = 1;
						}
						else if( NOR_LED )
						{
							NOR_LED = 0;
							NAND_LED = 1;
						}
						else if( NAND_LED )
						{
							NAND_LED = 0;
							XNOR_LED = 1;
							dir = DirRev;
						}

						break;

					case DirRev:
						if( XNOR_LED )
						{
							XNOR_LED = 0;
							NAND_LED = 1;
						}
						else if( NAND_LED )
						{
							NAND_LED = 0;
							NOR_LED = 1;
						}
						else if( NOR_LED )
						{
							NOR_LED = 0;
							XOR_LED = 1;
						}
						else if( XOR_LED )
						{
							XOR_LED = 0;
							AND_LED = 1;
						}
						else if( AND_LED )
						{
							AND_LED = 0;
							OR_LED = 1;
						}
						else if( OR_LED )
						{
							OR_LED = 0;
							NOT_LED = 1;
							dir = DirFwd;
						}

						break;
				}

				time = score_to_time[ctr_leds_get()];		// adjust speed based on score
				timer = 0;
			}
			
			if( button.b.pressed )			// shoot
			{
				if( !XOR_LED )				// miss, reset score
					ctr_leds_set( 0 );
				
				else if( ctr_leds_set( ctr_leds_get() + 1 ) == 15 )		// hit, increment score, check for game over
				{
					XOR_LED = 0;
					state = StateGameOver;
				}
			}
			
			break;
			
		case StateGameOver:
			break;
	}
}
