/* Game.js */

/*

Asteroid, by Radnen 2009;
Guide your asteroid around,
be weary of the space ships.

Aliens are your friend!

*/

var Player_Image = LoadImage("Asteroid.png");
var Enemy_Image = LoadImage("Ship.png");
const SW = GetScreenWidth();
const SH = GetScreenHeight();

function SpaceEntity(image, x, y, s, a)
{
	if (image === undefined) Abort("No image in created entity");
	this.image = image;
	
	if (x === undefined) this.x = Math.floor(Math.random()*GetScreenWidth());
	else this.x = x;
	
	if (y === undefined) this.y = Math.floor(Math.random()*GetScreenHeight());
	else this.y = y;
	
	if (a === undefined) this.a = Math.floor(Math.random()*360)/180*Math.PI;
	else this.a = a;

	if (s === undefined) this.s = 2;
	else this.s = s;

	this.vx = Math.cos(this.a)*this.s;
	this.vy = Math.sin(this.a)*this.s;
	this.timer = 0;
	this.bullet_timer = 0;
	this.bullet_rate = 1200;
}

SpaceEntity.prototype.draw = function()
{
	this.image.rotateBlit(this.x, this.y, this.a);
}

SpaceEntity.prototype.updateVelocity = function()
{
	this.vx = Math.cos(this.a)*this.s;
	this.vy = Math.sin(this.a)*this.s;	
}

// Warps the Space Entity left to right, top to bottom.
SpaceEntity.prototype.doEdgeWarp = function()
{
	if (this.x > SW) this.x = 0;
	else if (this.x < 0) this.x = SW;
	
	if (this.y > SH) this.y = 0;
	else if (this.y < 0) this.y = SH;	
}

SpaceEntity.prototype.AI = function()
{
	if (this.timer == 0) this.timer = GetTime();
	
	if (this.timer + 8000 > GetTime()) {
		this.new_a = Math.floor(Math.random()*360)/180*Math.PI;
	}
	
	if (this.a > this.new_a) this.a -= Math.PI/64;
	else this.a += Math.PI/64;
	
	this.updateVelocity();
	this.x += this.vx;
	this.y += this.vy;
	this.doEdgeWarp();
}

SpaceEntity.prototype.handleInput = function()
{
	if (IsKeyPressed(KEY_UP)) {
		if (this.s < 3) this.s += 0.2;
		else this.s = 3;

		this.updateVelocity();
	}
	
	if (IsKeyPressed(KEY_LEFT)) {
		this.a -= Math.PI/64;
	}
	
	if (IsKeyPressed(KEY_RIGHT)) {
		this.a += Math.PI/64;
	}
	
	this.x += this.vx;
	this.y += this.vy;
	this.doEdgeWarp();	
}

function game()
{
	SetFrameRate(60);
	var player = new SpaceEntity(Player_Image, SW/2-32, SH/2-32, 3, 0);
	var timer = GetTime();
	var enemies = [];

	while(!IsKeyPressed(KEY_ESCAPE)) {
		
		// after around 4 seconds, add another enemy.
		if (timer + 4000 < GetTime()) {
			enemies.push(new SpaceEntity(Enemy_Image));
			timer = GetTime();
		}
		
		// update all the enemies stuipd AI's ...
		for (var i = 0; i < enemies.length; ++i) {
			enemies[i].draw();
			enemies[i].AI();
		}

		player.handleInput();
		player.draw();

		FlipScreen();
	}
}