/*
 * mini2.cpp
 *
 *  Created on: 2010.04.18.
 *      Author: Szabó László
 */

#include "mini2.hpp"

void mini2( int & score, SDL_Surface* & screen ){
	SDL_Surface* bg = load( "minigames/cave.png" );
	SDL_Surface* t_sheet = load( "minigames/t_box.png" );

	Mix_Chunk *effect1 = Mix_LoadWAV( "sfx/treasure.wav" );
	Mix_Chunk *effect2 = Mix_LoadWAV( "sfx/dig.wav" );

	int i;

	bool end = false;
	SDL_Event minievent;

	bool treasures[ 4 ];
	SDL_Rect offsets[ 3 ];

	bool choose1 = true, choose2 = true;
	int where = rand() % 4;

	for( i = 0; i < 4; i++ ){
		treasures[ i ] = false;
	}

	offsets[ 0 ].x = 0;
	offsets[ 0 ].y = 0;
	offsets[ 0 ].w = 60;
	offsets[ 0 ].h = 120;

	offsets[ 1 ].x = 60;
	offsets[ 1 ].y = 0;
	offsets[ 1 ].w = 60;
	offsets[ 1 ].h = 120;

	offsets[ 2 ].x = 120;
	offsets[ 2 ].y = 0;
	offsets[ 2 ].w = 60;
	offsets[ 2 ].h = 120;

	while( !end ){



		while( SDL_PollEvent( &minievent ) ){

			if( minievent.type == SDL_QUIT || ( minievent.type == SDL_KEYDOWN && minievent.key.keysym.sym == SDLK_ESCAPE ) ){
				end = true;
			}

			if( minievent.type == SDL_KEYDOWN ){

				if( choose1 ){
				switch( minievent.key.keysym.sym ){

					case SDLK_UP : choose1 = false; treasures[ 0 ] = true; break;
					case SDLK_LEFT : choose1 = false; treasures[ 1 ] = true; break;
					case SDLK_DOWN : choose1 = false; treasures[ 2 ] = true; break;
					case SDLK_RIGHT: choose1 = false; treasures[ 3 ] = true; break;

					default : break;
				}
				Mix_PlayChannel( -1, effect2, 0 );
				}

				if( choose2 ){
				switch( minievent.key.keysym.sym ){

					case SDLK_w : choose2 = false; treasures[ 0 ] = true; break;
					case SDLK_a : choose2 = false; treasures[ 1 ] = true; break;
					case SDLK_s : choose2 = false; treasures[ 2 ] = true; break;
					case SDLK_d: choose2 = false; treasures[ 3 ] = true; break;

					default : break;
				}
				Mix_PlayChannel( -1, effect2, 0 );
				}
			}

		}

		apply( 0, 0, bg, screen );

		for( i = 0; i < 4; i++ ){
			if( !treasures[ i ] ){
				apply( (640/4)*i + 40, 340, t_sheet, screen, &offsets[ 0 ] );
			}
			if( treasures[ i ] ){
				if( i == where ){
					apply( (640/4)*i + 40, 340, t_sheet, screen, &offsets[ 1 ] );
					end = true;
					score += 10000;
					Mix_PlayChannel( -1, effect1, 0 );
				}
				else
					apply( (640/4)*i + 40, 340, t_sheet, screen, &offsets[ 2 ] );
			}
		}

		SDL_Flip( screen );

		if( !choose1 && !choose2 ) end = true;


	}

	SDL_Delay( 1000 );
	SDL_FreeSurface( bg );

	Mix_FreeChunk( effect1 );
	Mix_FreeChunk( effect2 );

	SDL_FreeSurface( t_sheet );
}
