/**
In this game, bugs come down at random from the top of the screen and the player 
has to zap them. We’ll be using keyboard controls to move the ninja, but using the 
mouse is also acceptable.

Decomposition:
* bugs cloning from top at random x
* keyboard controls to move ninja
* bullet fired
* collision with bugs adds to score

*/

//****************Scene Object - Initialize When Scene Starts Even***************//
// game variables 
$this.totalScore = 0;
bullet.fired = false; // set up boolean to control shooting
if($this.scene.state() == "PLAY") { //cloning of bugs
    createTimer(1000, function() {
        var nbug = bug.clone();
        nbug.x(random(720, 80)); // set bug starting position
        nbug.y(-80);
    });
}

//******************ninja Object - Update Every Frame Event**********************//
// set up controls
var rightArrowPressed = isKeyPressed(Keys.rightArrow);
var leftArrowPressed = isKeyPressed(Keys.leftArrow);
var spacePressed = isKeyPressed(Keys.space);

if(rightArrowPressed && this.x() < 777) {
    $this.moveX(100);
}

if(leftArrowPressed && this.x() > 23) {
    $this.moveX(-100);
}

if(spacePressed && bullet.fired === false) {
    bullet.fired = true; //send true to bullet
}

//******************bug Object - Update Every Frame Event************************//
if($this.y() < 600) {
    $this.moveY(50);
    $this.incrementAnimation();
} else {
    $this.remove();
    $this.scene.totalScore -= 1;
    score.text($this.scene.totalScore);
}
if($this.isTouching(bullet)) {
    $this.remove();
    $this.scene.totalScore += 1;
    score.text($this.scene.totalScore);
    bullet.fired = false;
}

//****************bullet Object - Update Every Frame****************************//
if($this.fired && $this.y() > 0) { //bullet listening for fired = true 
    $this.moveY(-250);
} else {
    $this.fired = false;
    $this.x(ninja.x()); //reset bullet to ninja.x, y
    $this.y(ninja.y()); 
}