/*
* Copyright 2023, Ali Arya
* Anyone Can Code: Algorithmic Thinking
* Example 4.2c
*/

#include "Main.h"

int main(int argc, char* argv[])
{
	/////////////////////////////////////////////////////////////////
	// INIT part of the game
	// things that are done only once at the start (initialization)
	/////////////////////////////////////////////////////////////////

	//init SDL library and graphics window
	SDLX_Init("Simple 2D Game", 640, 480, true);

	//game map (background)
	SDLX_Bitmap* map = SDLX_LoadBitmap("map.bmp", false, NULL); //do not use any mask for transparent color
												   //player
	SDLX_Bitmap* player = SDLX_LoadBitmap("Player.bmp");
	int playerX = 0;
	int playerY = 0;

	SDLX_Bitmap* enemy = SDLX_LoadBitmap("Enemy.bmp"); 
	int enemyX = 100;
	int enemyY = 180;

	SDLX_Bitmap* prize = SDLX_LoadBitmap("Prize.bmp"); 
	int prizeX = 200;
	int prizeY = 200;

	bool quit = false;
	bool win = false;

	/////////////////////////////////////////////////////////////////
	//--------Main game Loop---------- -
	// things that are done repeatedly
	/////////////////////////////////////////////////////////////////
	while (!quit)
	{
		/////////////////////////////////////////////
		// UPDATE
		/////////////////////////////////////////////
		
		//check if we hit the prize
		int distanceX = abs(playerX - prizeX);
		int distanceY = abs(playerY - prizeY);
		if (distanceX < 10 && distanceY < 10)
		{
			prizeX = prizeY = 1000;
			quit = true;
			win = true;
		}
		//check if we hit the enemy
		distanceX = abs(playerX - enemyX);
		distanceY = abs(playerY - enemyY);
		if (distanceX < 10 && distanceY < 10)
		{
			quit = true;
		}

		//check if there is any moevement
		//player controlled by keyboard
		SDLX_Event e;
		//keyboard events
		if (SDLX_PollEvent(&e))
		{
			if (e.type == SDL_KEYDOWN)
			{
				//press escape to end the game
				if (e.keycode == SDLK_ESCAPE)
					quit = true;
				//update player  
				if (e.keycode == SDLK_RIGHT)
					playerX++;
				if (e.keycode == SDLK_LEFT)
					playerX--;
				if (e.keycode == SDLK_UP)
					playerY--;
				if (e.keycode == SDLK_DOWN)
					playerY++;
			}
		}

		//update enemy
		enemyX += rand() %5 - 2;
		enemyY += rand() %5 - 2;

		/////////////////////////////////////////////
		// DRAW
		/////////////////////////////////////////////
		//note the order (last one will be drawn on top)
		SDLX_DrawBitmap(map, 0, 0);
		SDLX_DrawBitmap(prize, prizeX, prizeY);
		SDLX_DrawBitmap(enemy, enemyX, enemyY);
		SDLX_DrawBitmap(player, playerX, playerY);

		//Update the screen
		SDLX_Render();


		//now wait for loop timing
		SDLX_Delay(1);
	}

	if (win)
		printf("you win");
	else
		printf("you lose");
	return 0;
}