#include "main.h"

#include "graphics/sprites.raw.c"
#include "graphics/sprites.pal.c"
#include "graphics/font.raw.c"

void write_score(u16* map, u16 map_width, u16 x, u16 y, int val, int pad)
{
	char buf[pad];
	char fmtstr[5];
	int i;

	fmtstr[0] = '%'; fmtstr[1] = '0';
	fmtstr[2] = pad + '0';
	fmtstr[3] = 'd'; fmtstr[4] = 0;
	sprintf(buf, fmtstr, val);

	for(i=0; i < pad; i++)
	{
		map[(y * map_width) + x + i] = buf[i] - ('0' - 1);
	}
}

/**
 * Run the game
 * @return player's score
 */
int game_run()
{
	Bg bg;
	game g;
	u16 loop;
	u16* temp;
	int wave_timer = 0;
	int score;
	int die = 0;

	SetMode(MODE_0 | BG2_ENABLE | OBJ_ENABLE | OBJ_MAP_1D);

	bg.number = 0;
	bg.charBaseBlock = 0;
	bg.screenBaseBlock = 28;
	bg.colorMode = BG_COLOR_256;
	bg.size = TEXTBG_SIZE_256x256;
	bg.x_scroll = 0; bg.y_scroll = 0;
	g.ship = playership_new();

	SetMode(MODE_0 | BG2_ENABLE | OBJ_ENABLE | OBJ_MAP_1D);

	EnableBackground(&bg);
	UpdateBackground(&bg);
	/* set up palette for text background */
	BGPaletteMem[0] = 0x0000;
	BGPaletteMem[1] = 0x7fff;

	/* copy text images into tile ram */
	temp = (u16*) font_Bitmap;
	for(loop = 0; loop < (4 * 8) * 64; loop++)
		bg.tileData[loop] = temp[loop];

	/* load sprite palette and tile data */
	for(loop = 0; loop < 256; loop++)
	{
		OBJPaletteMem[loop] = sprites_Palette[loop];
	}
	
	InitialiseSprites();
	temp = (u16*) sprites_Bitmap;
	for(loop = 0; loop < (2 * 16) * (32*4); loop++)
	{
		OAMData[loop] = temp[loop];
	}
	
	g.num_aliens = 5;
	g.aliens = calloc(g.num_aliens, sizeof(alien));
	g.charMap = bg.mapData;

	//Main Game loop
	while(!die)
	{
		u32 keys = *KEYS;

		if(wave_timer == 0)
		{
			aliens_create_wave(g.aliens, g.num_aliens);
			wave_timer = 350;
		}
		wave_timer--;

		playership_read_keys(g.ship, keys);
		aliens_draw(&g);
		playership_draw(&g);
		if(collide_aliens_bullets_ship(&g))
		{
			die = 1;
		}

		CopyOAM();
		gba_vsync();
	}
	score = g.ship->score;
	
	return(score);
}
