<commit_before>$(document).ready(function() {
    $('.slideDiv').on("click", function(){ $(this).slideUp();});
    $(".color").on("mouseleave", function() {
    $(this).css("background-color","blue");});
    $(".color").on("mouseenter", function() {
    $(this).css("background-color","red");});
    $("#green").css("background-color", "green").show("slow");
    $("#fadeIn").fadeIn("slow");
    $("p").css("font-style", "italic");
    $("fadeIn").css("font-size", "50px");
    $(".color").on("click", function(){ $(this).slideToggle();});
    $("#eg2").on("click", function(){ $(this).fadeOut();});
    $("img").animate({ opacity: 0.25 }, 5000).css("float", "right");
    $("#insert").html("
This paragraph is added with jquery
");
    $("#default").val("Default");
});

//Load Json without jquery
function doXMLHttpRequest() {
  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange=function()  {
   if (xhr.readyState==4) {
     if(xhr.status == 200) {
        processResponse(xhr.responseText);
    } else {
      responseArea.innerHTML="Error code " + xhr.status;
    }
   }
  }
  xhr.open("GET", "data.json", true);
  xhr.send(null);
}

function processResponse(responseJSON) {
        var responseObject = JSON.parse(responseJSON);
        var displayText =
                "Today's Prices: "
                + responseObject.stocks.length
                + " stocks:
";
        for (var i = 0; i<responseObject.stocks.length; i++) {
                var stock = responseObject.stocks[i];
                displayText += "
"
                                        +stock.stockName + " "
                                        + stock.price + "<\/li>";
        }
        displayText += "<\/ol>";
        document.getElementById("responseArea").innerHTML = displayText;
}

//Load Json with jquery
$(function() {    // do once original document loaded and ready
        $('form[name="eg2"] input').click(function() {
                $.getJSON("http://btc.blockr.io/api/v1/coin/info", function(responseObject, diditwork) {
                        console.log(diditwork);
                        var displayText = responseObject.data.coin

                $("#responseArea2").html(displayText);
                } );  // getJSON
        } );  // click
  } ); // onReady

<commit_msg>new api<commit_after>$(document).ready(function() {
    $('.slideDiv').on("click", function(){ $(this).slideUp();});
    $(".color").on("mouseleave", function() {
    $(this).css("background-color","blue");});
    $(".color").on("mouseenter", function() {
    $(this).css("background-color","red");});
    $("#green").css("background-color", "green").show("slow");
    $("#fadeIn").fadeIn("slow");
    $("p").css("font-style", "italic");
    $("fadeIn").css("font-size", "50px");
    $(".color").on("click", function(){ $(this).slideToggle();});
    $("#eg2").on("click", function(){ $(this).fadeOut();});
    $("img").animate({ opacity: 0.25 }, 5000).css("float", "right");
    $("#insert").html("
This paragraph is added with jquery
");
    $("#default").val("Default");
});

//Load Json without jquery
function doXMLHttpRequest() {
  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange=function()  {
   if (xhr.readyState==4) {
     if(xhr.status == 200) {
        processResponse(xhr.responseText);
    } else {
      responseArea.innerHTML="Error code " + xhr.status;
    }
   }
  }
  xhr.open("GET", "data.json", true);
  xhr.send(null);
}

function processResponse(responseJSON) {
        var responseObject = JSON.parse(responseJSON);
        var displayText =
                "Today's Prices: "
                + responseObject.stocks.length
                + " stocks:
";
        for (var i = 0; i<responseObject.stocks.length; i++) {
                var stock = responseObject.stocks[i];
                displayText += "
"
                                        +stock.stockName + " "
                                        + stock.price + "<\/li>";
        }
        displayText += "<\/ol>";
        document.getElementById("responseArea").innerHTML = displayText;
}

//Load Json with jquery
$(function() {    // do once original document loaded and ready
        $('form[name="eg2"] input').click(function() {
                $.getJSON("http://btc.blockr.io/api/v1/coin/info", function(responseObject, diditwork) {
                        console.log(diditwork);
                        var displayText = responseObject.status.data.coin

                $("#responseArea2").html(displayText);
                } );  // getJSON
        } );  // click
  } ); // onReady

<|endoftext|>


<commit_before>//adds a specific player
game.PlayerEntity = me.Entity.extend({
	init: function(x, y, settings) {
		this._super(me.Entity, 'init', [x, y, {
			image: "player",
			width: 64,
			height: 64,
			spritewidth: "64",
			spriteheight: "64",
			getShape: function() {
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
			}
		}]);
			//sets the spawn
		this.body.setVelocity(5, 20);
		//makes the screen follow the player
		this.facing = "right";
		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);
			//grabs animation from image
		this.renderable.addAnimation("idle", [78]);
		this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);

		this.renderable.setCurrentAnimation("idle");

	},

	update: function(delta){
			//binds a key
		if(me.input.isKeyPressed("right")){
			//adds to the position of my x by the velocity defined above in
			//setVelocity() and multiplying it by me.timer.tick.
			//me.timer.tick makes the movement look smooth
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			this.facing = "right";
			this.flipX(true);
			//set player to move left
		}else if(me.input.isKeyPressed("left")){
			this.facing = "left";
			this.body.vel.x -=this.body.accel.x * me.timer.tick;
			//flips animation
			this.flipX(false);
		}else{
			this.body.vel.x = 0;
		}
			//sets animation
			// && !this.jumping && !this.falling makes it so you can't
			// double jump while jumping or falling
		if(me.input.isKeyPressed("jump") && !this.body.jumping && !this.body.falling){
			this.body.jumping = true;
			this.body.vel.y -= this.body.accel.y * me.timer.tick;
		}

			//takes binded key from play.js and uses it
		if(me.input.isKeyPressed("attack")){
			if(!this.renderable.isCurrentAnimation("attack")){
				console.log(!this.renderable.isCurrentAnimation("attack"));
			//sets the current animation to attack and once that is over
			//goes back to the idle animation
				this.renderable.setCurrentAnimation("attack", "idle");
			//makes it so that the next time we start this sequence, we begin
			//from the first animation, not wherever we left off when we
			//switched to another animation
				this.renderable.setAnimationFrame();
			}
		}

			//sets current animation
		else if(this.body.vel.x !== 0){
			if(!this.renderable.isCurrentAnimation("walk")){
				this.renderable.setCurrentAnimation("walk");
			}
		}
		else{
			this.renderable.setCurrentAnimation("idle");
		}

		if(me.input.isKeyPressed("attack")){
			if(!this.renderable.isCurrentAnimation("attack")){
				this.renderable.setCurrentAnimation("attack", "idle");
				this.renderable.setAnimationFrame();
			}
		}

		me.collision.check(this, true, this.collideHandler.bind(this), true);

		this.body.update(delta);

		this._super(me.Entity, "update", [delta]);
		return true;

	},

	collideHandler: function(response){
		if(response.b.type==='EnemyBaseEntity'){
			var ydif = this.pos.y - response.b.pos.y;
			var xdif = this.pos.x - response.b.pos.x;

			console.log("xdif" + xdif + ydif);

			if(xdif>-35 && this.facing=='right' && (xdif<0)){
				this.body.vel.x = 0;
				this.pos.x = this.pos.x -1;
			}else if(xdif<70 && this.facing=='left' && xdif>0){
				this.body.vel.x = 0;
				this.pos.x = this.pos.x +1;

			}
		}
	}
});
	//adds base class
game.PlayerBaseEntity = me.Entity.extend({
	init : function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			//adds image
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function() {
				return (new me.Rect(0, 0, 100, 70)).toPolygon();
			}
		}]);
			//variable that say that tower is not destroyed
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		//if someone runs with the tower, they will collide
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "PlayerBaseEntity";

		//adds animation for PlayerBase
		this.renderable.addAnimation("idle", [0]);
		//burning animation
		this.renderable.addAnimation("broken", [1]);
		//normal animation
		this.renderable.setCurrentAnimation("idle");
	},

	update:function(delta) {
		//if health is below 0, then you should die
		if(this.health<=0){
			this.broken = true;
			this.renderable.setCurrentAnimation("broken");
		}
		this.body.update(delta);

	this._super(me.Entity, "update", [delta]);
	return true;
	},

	onCollision: function(){

	}

});

game.EnemyBaseEntity = me.Entity.extend({
	init : function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			//adds image
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function() {
				return (new me.Rect(0, 0, 100, 70)).toPolygon();
			}
		}]);
			//variable that say that tower is not destroyed
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		//if someone runs with the tower, they will collide
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "EnemyBaseEntity";
			//sets animation for EnemyBase
		this.renderable.addAnimation("idle", [0]);
			//burned base
		this.renderable.addAnimation("broken", [1]);
			//fixed base
		this.renderable.setCurrentAnimation("idle");
	},

	update:function(delta) {
		//if health is below 0, then you should die
		if(this.health<=0){
			this.broken = true;
			this.renderable.setCurrentAnimation("broken");
		}
		this.body.update(delta);

	this._super(me.Entity, "update", [delta]);
	return true;
	},

	onCollision: function(){

	}

});<commit_msg>Video 15 Comments<commit_after>//adds a specific player
game.PlayerEntity = me.Entity.extend({
	init: function(x, y, settings) {
		this._super(me.Entity, 'init', [x, y, {
			image: "player",
			width: 64,
			height: 64,
			spritewidth: "64",
			spriteheight: "64",
			getShape: function() {
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
			}
		}]);
			//sets the spawn
		this.body.setVelocity(5, 20);
		//Keeps track of which direction your character is going
		this.facing = "right";
		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);
			//grabs animation from image
		this.renderable.addAnimation("idle", [78]);
		this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);

		this.renderable.setCurrentAnimation("idle");

	},

	update: function(delta){
			//binds a key
		if(me.input.isKeyPressed("right")){
			//adds to the position of my x by the velocity defined above in
			//setVelocity() and multiplying it by me.timer.tick.
			//me.timer.tick makes the movement look smooth
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			this.facing = "right";
			this.flipX(true);
			//set player to move left
		}else if(me.input.isKeyPressed("left")){
			this.facing = "left";
			this.body.vel.x -=this.body.accel.x * me.timer.tick;
			//flips animation
			this.flipX(false);
		}else{
			this.body.vel.x = 0;
		}
			//sets animation
			// && !this.jumping && !this.falling makes it so you can't
			// double jump while jumping or falling
		if(me.input.isKeyPressed("jump") && !this.body.jumping && !this.body.falling){
			this.body.jumping = true;
			this.body.vel.y -= this.body.accel.y * me.timer.tick;
		}

			//takes binded key from play.js and uses it
		if(me.input.isKeyPressed("attack")){
			if(!this.renderable.isCurrentAnimation("attack")){
				console.log(!this.renderable.isCurrentAnimation("attack"));
			//sets the current animation to attack and once that is over
			//goes back to the idle animation
				this.renderable.setCurrentAnimation("attack", "idle");
			//makes it so that the next time we start this sequence, we begin
			//from the first animation, not wherever we left off when we
			//switched to another animation
				this.renderable.setAnimationFrame();
			}
		}

			//sets current animation
		else if(this.body.vel.x !== 0){
			if(!this.renderable.isCurrentAnimation("walk")){
				this.renderable.setCurrentAnimation("walk");
			}
		}
		else{
			this.renderable.setCurrentAnimation("idle");
		}

		if(me.input.isKeyPressed("attack")){
			if(!this.renderable.isCurrentAnimation("attack")){
				this.renderable.setCurrentAnimation("attack", "idle");
				this.renderable.setAnimationFrame();
			}
		}
			//Makes perameter
		me.collision.check(this, true, this.collideHandler.bind(this), true);

		this.body.update(delta);

		this._super(me.Entity, "update", [delta]);
		return true;

	},
			//Hold all information for collision
	collideHandler: function(response){
		if(response.b.type==='EnemyBaseEntity'){
			var ydif = this.pos.y - response.b.pos.y;
			var xdif = this.pos.x - response.b.pos.x;

			console.log("xdif" + xdif + ydif);
			//sets barrier on right side of the enemy base
			if(xdif>-35 && this.facing=='right' && (xdif<0)){
				this.body.vel.x = 0;
				this.pos.x = this.pos.x -1;
			//sets barrier on left side of the enemy base
			// && x(y)dif>(<)0 makes it so the barrier doesn't work while facibg the other way
			}else if(xdif<70 && this.facing=='left' && xdif>0){
				this.body.vel.x = 0;
				this.pos.x = this.pos.x +1;

			}
		}
	}
});
	//adds base class
game.PlayerBaseEntity = me.Entity.extend({
	init : function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			//adds image
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function() {
				return (new me.Rect(0, 0, 100, 70)).toPolygon();
			}
		}]);
			//variable that say that tower is not destroyed
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		//if someone runs with the tower, they will collide
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "PlayerBaseEntity";

		//adds animation for PlayerBase
		this.renderable.addAnimation("idle", [0]);
		//burning animation
		this.renderable.addAnimation("broken", [1]);
		//normal animation
		this.renderable.setCurrentAnimation("idle");
	},

	update:function(delta) {
		//if health is below 0, then you should die
		if(this.health<=0){
			this.broken = true;
			this.renderable.setCurrentAnimation("broken");
		}
		this.body.update(delta);

	this._super(me.Entity, "update", [delta]);
	return true;
	},

	onCollision: function(){

	}

});

game.EnemyBaseEntity = me.Entity.extend({
	init : function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			//adds image
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function() {
				return (new me.Rect(0, 0, 100, 70)).toPolygon();
			}
		}]);
			//variable that say that tower is not destroyed
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		//if someone runs with the tower, they will collide
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "EnemyBaseEntity";
			//sets animation for EnemyBase
		this.renderable.addAnimation("idle", [0]);
			//burned base
		this.renderable.addAnimation("broken", [1]);
			//fixed base
		this.renderable.setCurrentAnimation("idle");
	},

	update:function(delta) {
		//if health is below 0, then you should die
		if(this.health<=0){
			this.broken = true;
			this.renderable.setCurrentAnimation("broken");
		}
		this.body.update(delta);

	this._super(me.Entity, "update", [delta]);
	return true;
	},

	onCollision: function(){

	}

});<|endoftext|>


<commit_before>// TODO
game.PlayerEntity = me.Entity.extend({
    //initializes the function
    init: function(x, y, settings) {
        this.setSuper();
        this.setPlayerTimers();
        this.setAttributes();
        this.type = "PlayerEntity";
        this.setFlags();

        me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

        this.addAnimation();

        //adds animation to non-moving position
        this.renderable.setCurrentAnimation("idle");

    },
    setSuper: function(){
    	this._super(me.Entity, 'init', [x, y, {
                //makes the image of the player appear
                image: "player",
                //the width of the space created
                width: 64,
                //the height of the space created
                height: 64,
                //height for the player
                spriteheight: "64",
                //width for the player
                spritewidth: "64",
                //function of the shape of the screen
                getShape: function() {
                    //creates a rectangle of 64 by 64 so the player can go inside
                    //0 , 0 is the origin
                    return(new me.Rect(0, 0, 64, 64)).toPolygon();
                }
            }]);

    },
    setPlayerTimers: function(){
    	//checks the time for the game
        this.now = new Date().getTime();
        this.lastHit = this.now;
        //stop the player from hitting over and over again
        this.lastAttack = new Date().getTime();

    },

    setAttributes: function(){
    	 this.health = game.data.playerHealth;
        //it sets the speed of the player when it moves to the right
        //y location changes
        //it moved down to the player
        //changed velocity to global variable
        this.body.setVelocity(game.data.playerMoveSpeed, 20);
         //makes the player get attacked..?
        this.attack = game.data.playerAttack;
    },
    setFlags: function(){
    	  //keeps track of which direction your character is going
        this.facing = "right";
        //states  that the player is alive.
        this.dead = false;
        this.attacking = false;
    },
    addAnimation: function(){
    	//adds animation to standing starting position
        this.renderable.addAnimation("idle", [78]);
        //adds animation to walking
        this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
        //animation for character attack
        this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);
    },
    //updates the function
    //whole set for just the x-axis
    update: function(delta) {
        //keeps it up to date
        this.now = new Date().getTime();
        this.dead = checkIfDead();
        this.checkKeyPressesAndMove();
        this.setAnimation();
        //checks for collisions
        me.collision.check(this, true, this.collideHandler.bind(this), true);
        //updates the function to true
        this.body.update(delta);
        //updates the animation
        this._super(me.Entity, "update", [delta]);
        return true;

    },

    checkIfDead: function(){
    	  //if statement for haelth
        if (this.health <= 0){
        	//if health 0, player dies
        	return true;

        }
        return false;

    },

    checkKeyPressesAndMove: function(){
    //moves the player right
        if (me.input.isKeyPressed("right")) {
        	this.moveRight();
        //moves the player left
        }else if (me.input.isKeyPressed("left")) {
        	this.moveLeft();
        }else {
            //for when the righ arrow isnt clicked
            this.body.vel.x = 0;
        }
        //set for the y-axis
        //so the player can go right or left and still jump
        //no double jumping
        if (me.input.isKeyPressed("jump") && !this.body.jumping && !this.body.falling) {
            this.jump();
        }
        this.attacking = me.input.isKeyPressed("attack");

    },

    moveRight: function(){

            //sets the position of my x by adding the velocity defined above in setVelocity and multiplying it by me.timer.tick
            //me.timer.tick makes the movement look smooth
            this.body.vel.x += this.body.accel.x * me.timer.tick;
            //keeps track of which direction your character is going
            this.facing = "right";
            //makes the charcter face to right
            this.flipX(true);

    },

    moveLeft: function(){
    	//keeps track of which direction your character is going
            this.facing = "left";
            this.body.vel.x -= this.body.accel.x * me.timer.tick;
            this.flipX(false);

    },

    jump: function(){
    	this.body.jumping = true;
            this.body.vel.y -= this.body.accel.y * me.timer.tick;
            //this plays soud effects when jumping
            me.audio.play("jump");

    },

    setAnimation: function(){
    	if (this.attacking) {
            if (!this.renderable.isCurrentAnimation("attack")) {
                console.log(!this.renderable.isCurrentAnimation("attack"));
                //sets the current animation to attck and once that is over goes back to idle animation
                this.renderable.setCurrentAnimation("attack", "idle");
                //makes it so that the next time we start this sequence we begin from the first animation not whenever we left off when we switched to another animation
                this.renderable.setAnimationFrame();
            }
        }

        //if the button is pushed then it will walk but it not it will execute the else code
        else if (this.body.vel.x !== 0 && !this.renderable.isCurrentAnimation("attack")) {
            if (!this.renderable.isCurrentAnimation("walk")) {
                this.renderable.setCurrentAnimation("walk");
            }
        } else if (!this.renderable.isCurrentAnimation("attack")) {
            //if not, make it stand still
            this.renderable.setCurrentAnimation("idle");
        }

    },

    loseHealth: function(damage) {
    	this.health = this.health - damage;
    },
    //new function that is passing the parameter response
    //holds info about collision
    collideHandler: function(response) {
        if (response.b.type === 'EnemyBaseEntity') {
            //the y difference between the players y position and the base y position
            //keep track of the position of both objects
            var ydif = this.pos.y - response.b.pos.y;
            var xdif = this.pos.x - response.b.pos.x;
            //makes the player jump on top of the tower
            if (ydif < -40 && xdif < 70 && xdif > -35) {
                this.body.falling = false;
                this.body.vel.y = -1
            }
            //stops the player on the left side of the tower
            //prevent from over lapping
            else if (xdif > -35 && this.facing === 'right' && (xdif < 0)) {
                //stop the player from moving
                this.body.vel.x = 0;
                //move player backwards
                //this.pos.x = this.pos.x - 1;
            }
            //stops the player on the right side of the tower
            //prevent from over lapping
            else if (xdif < 70 && this.facing === 'left' && xdif > 0) {
                //stop the player from moving
                this.body.vel.x = 0;
                //moves player forward
                //this.pos.x = this.pos.x + 1;
            }
            //added global variable for playerAttackTimer
            if (this.renderable.isCurrentAnimation("attack") && this.now - this.lastHit >= game.data.playerAttackTimer) {
                //check when it is called
                console.log("tower Hit");
                this.lastHit = this.now;
                //call the losehealth function
                //added global variable for playerAttack
                response.b.loseHealth(game.data.playerAttack);
            }
            //if the player collide with the enemy creep, this code gets executed.
        }else if(response.b.type==='EnemyCreep'){
        	//the y difference between the players y position and the creep y position
            //keep track of the position of both objects
        	var xdif = this.pos.x - response.b.pos.x;
        	var ydif = this.pos.y - response.b.pos.y;
        	//
        	if (xdif>0){
        		//moves it to the right
        		//this.pos.x = this.pos.x + 1;
        		//when the player and creep are facing each other, the player can attack.
        		if(this.facing==="left"){
        			//sets the velocity to 0
        			this.body.vel.x = 0;
        		}
        	}else{
        		//moves it to the left
        		//this.pos.x = this.pos.x -1;
        		//when the player and creep are facing each other, the player can attack.
        		if(this.facing==="right"){
        			// sets the velocity to 0
        			this.body.vel.x = 0;
        		}
        	}
        	//added a global variable for playerAttackTimer
        	if(this.renderable.isCurrentAnimation("attack") && this.now - this.lastHit >= game.data.playerAttackTimer
        			&& (Math.abs(ydif) <=40) &&
        			(((xdif>0) && this.facing==="left") || ((xdif<0) && this.facing==="right"))) {
        		//
        		this.lastHit = this.now;
        		//if the creeps health is less than our attack, execute code in if statement
        		if(response.b.health <= game.data.playerAttack){
        			//adds one gold for a creep gold
        			game.data.gold += 1;
        			//shows in the console log
        			console.log("Current gold: " + game.data.gold);

        		}
        		//calls the lose health function from the creep.
        		//aded a global variable for playerAttack
        		response.b.loseHealth(game.data.playerAttack);
        	}
        }
    }
});

//Added a second player
game.Player2 = me.Entity.extend({
// sets properties of enemy player
	init: function(x, y, settings){
		this._super(me.Entity, "init", [x, y, {
			image: "Player2",
			width: 100,
			height: 85,
			spritewidth: "100",
			spriteheight: "85",
			getShape: function(){
				return(new me.Rect(0, 0 ,100, 85)).toPolygon();
			}
		}]);

		// sets health of player starting at 10
		this.health = game.data.playerHealth;
		// always keeps the enemy player updated
		this.alwaysUpdate = true;

		// this.attacking lets us know if thge enemy is currently attacking
		this.attacking = false;

		// keeps track of when our creep last attacked anything
		this.lastAttacking = new Date().getTime();

		// keeps track of the ;ast time our creep hit anything
		this.lastHit = new Date().getTime();

		// timer
		this.now = new Date().getTime();

		// sets were player is located
		this.body.setVelocity(3, 20);

		// sets type of player
		this.type = "Player2";

		// sets the animation of enemy player
		this.renderable.addAnimation("walk", [0, 1, 2, 3, 4], 80);
		this.renderable.setCurrentAnimation("walk");
	},

	update: function(delta){
		// Timer set to check collisons refreshes every single time
		this.now = new Date().getTime();

		// makes creeps move
		this.body.vel.x += this.body.accel.x * me.timer.tick;
		this.flipX(true);

		// checks of creep is colliding with player
		// me.collison.check(this, true, this.collideHandler.bind(this), true);

		this.body.update(delta);

		this._super(me.Entity, "update", [delta]);

		return true;

	},

	collideHandler: function(response){
		if (response.b.type === 'EnemyBaseEntity') {
			this.attacking = true;
			// this.lastAttacking = this.now;
			this.body.vel.x = 0;
			// keeps creep moving to the right to maintain its position
			this.pos.x = this.pos.x + 1;
			// checks that it has been at least 1 second since this creep hit a base
			if ((this.now-this.lastHit >= 1000)) {
				// updates the lasthit timer
				this.lastHit = this.now;
				// makes the player base call its loseHealth function and passes at a damge of 1
				response.b.loseHealth(1);
			}
		}
		else if (response.b.type === 'EnemyCreep') {
			var xdif = this.pos.x - response.b.pos.x;

			this.attacking = true;

			// this.lastAttacking = this.now;

			if (xdif>0) {
			// Kepps moving the creep to the right to maintain its position
				this.pos.x = this.pos.x + 1;
				this.body.vel.x = 0;
			}
			// checks that it has been less then 1 second since it hit somehting
			if ((this.now-this.lastHit >= 1000) && xdif>0) {
				// updates the last hit time
				this.lastHit = this.now;
				// makes the player call its lose health function and passes it as a damage of one
				response.b.loseHealth(1);
			}
		}
	}

});

<commit_msg>Coded video 33<commit_after>// TODO
game.PlayerEntity = me.Entity.extend({
    //initializes the function
    init: function(x, y, settings) {
        this.setSuper();
        this.setPlayerTimers();
        this.setAttributes();
        this.type = "PlayerEntity";
        this.setFlags();

        me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

        this.addAnimation();

        //adds animation to non-moving position
        this.renderable.setCurrentAnimation("idle");

    },
    setSuper: function(){
    	this._super(me.Entity, 'init', [x, y, {
                //makes the image of the player appear
                image: "player",
                //the width of the space created
                width: 64,
                //the height of the space created
                height: 64,
                //height for the player
                spriteheight: "64",
                //width for the player
                spritewidth: "64",
                //function of the shape of the screen
                getShape: function() {
                    //creates a rectangle of 64 by 64 so the player can go inside
                    //0 , 0 is the origin
                    return(new me.Rect(0, 0, 64, 64)).toPolygon();
                }
            }]);

    },
    setPlayerTimers: function(){
    	//checks the time for the game
        this.now = new Date().getTime();
        this.lastHit = this.now;
        //stop the player from hitting over and over again
        this.lastAttack = new Date().getTime();

    },

    setAttributes: function(){
    	 this.health = game.data.playerHealth;
        //it sets the speed of the player when it moves to the right
        //y location changes
        //it moved down to the player
        //changed velocity to global variable
        this.body.setVelocity(game.data.playerMoveSpeed, 20);
         //makes the player get attacked..?
        this.attack = game.data.playerAttack;
    },
    setFlags: function(){
    	  //keeps track of which direction your character is going
        this.facing = "right";
        //states  that the player is alive.
        this.dead = false;
        this.attacking = false;
    },
    addAnimation: function(){
    	//adds animation to standing starting position
        this.renderable.addAnimation("idle", [78]);
        //adds animation to walking
        this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
        //animation for character attack
        this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);
    },
    //updates the function
    //whole set for just the x-axis
    update: function(delta) {
        //keeps it up to date
        this.now = new Date().getTime();
        this.dead = checkIfDead();
        this.checkKeyPressesAndMove();
        this.setAnimation();
        //checks for collisions
        me.collision.check(this, true, this.collideHandler.bind(this), true);
        //updates the function to true
        this.body.update(delta);
        //updates the animation
        this._super(me.Entity, "update", [delta]);
        return true;

    },

    checkIfDead: function(){
    	  //if statement for haelth
        if (this.health <= 0){
        	//if health 0, player dies
        	return true;

        }
        return false;

    },

    checkKeyPressesAndMove: function(){
    //moves the player right
        if (me.input.isKeyPressed("right")) {
        	this.moveRight();
        //moves the player left
        }else if (me.input.isKeyPressed("left")) {
        	this.moveLeft();
        }else {
            //for when the righ arrow isnt clicked
            this.body.vel.x = 0;
        }
        //set for the y-axis
        //so the player can go right or left and still jump
        //no double jumping
        if (me.input.isKeyPressed("jump") && !this.body.jumping && !this.body.falling) {
            this.jump();
        }
        this.attacking = me.input.isKeyPressed("attack");

    },

    moveRight: function(){

            //sets the position of my x by adding the velocity defined above in setVelocity and multiplying it by me.timer.tick
            //me.timer.tick makes the movement look smooth
            this.body.vel.x += this.body.accel.x * me.timer.tick;
            //keeps track of which direction your character is going
            this.facing = "right";
            //makes the charcter face to right
            this.flipX(true);

    },

    moveLeft: function(){
    	//keeps track of which direction your character is going
            this.facing = "left";
            this.body.vel.x -= this.body.accel.x * me.timer.tick;
            this.flipX(false);

    },

    jump: function(){
    	this.body.jumping = true;
            this.body.vel.y -= this.body.accel.y * me.timer.tick;
            //this plays soud effects when jumping
            me.audio.play("jump");

    },

    setAnimation: function(){
    	if (this.attacking) {
            if (!this.renderable.isCurrentAnimation("attack")) {
                console.log(!this.renderable.isCurrentAnimation("attack"));
                //sets the current animation to attck and once that is over goes back to idle animation
                this.renderable.setCurrentAnimation("attack", "idle");
                //makes it so that the next time we start this sequence we begin from the first animation not whenever we left off when we switched to another animation
                this.renderable.setAnimationFrame();
            }
        }

        //if the button is pushed then it will walk but it not it will execute the else code
        else if (this.body.vel.x !== 0 && !this.renderable.isCurrentAnimation("attack")) {
            if (!this.renderable.isCurrentAnimation("walk")) {
                this.renderable.setCurrentAnimation("walk");
            }
        } else if (!this.renderable.isCurrentAnimation("attack")) {
            //if not, make it stand still
            this.renderable.setCurrentAnimation("idle");
        }

    },

    loseHealth: function(damage) {
    	this.health = this.health - damage;
    },
    //new function that is passing the parameter response
    //holds info about collision
    collideHandler: function(response) {
        if (response.b.type === 'EnemyBaseEntity') {
            this.collideWithEnemyBase(response);
            //if the player collide with the enemy creep, this code gets executed.
        }else if(response.b.type==='EnemyCreep'){
        	this.colliseWithEnemyCreep(response);

        }
    },

collideWithEnemyBase: function(response){
//the y difference between the players y position and the base y position
            //keep track of the position of both objects
            var ydif = this.pos.y - response.b.pos.y;
            var xdif = this.pos.x - response.b.pos.x;
            //makes the player jump on top of the tower
            if (ydif < -40 && xdif < 70 && xdif > -35) {
                this.body.falling = false;
                this.body.vel.y = -1
            }
            //stops the player on the left side of the tower
            //prevent from over lapping
            else if (xdif > -35 && this.facing === 'right' && (xdif < 0)) {
                //stop the player from moving
                this.body.vel.x = 0;
            }
            //stops the player on the right side of the tower
            //prevent from over lapping
            else if (xdif < 70 && this.facing === 'left' && xdif > 0) {
                //stop the player from moving
                this.body.vel.x = 0;
            }
            //added global variable for playerAttackTimer
            if (this.renderable.isCurrentAnimation("attack") && this.now - this.lastHit >= game.data.playerAttackTimer) {
                //check when it is called
                console.log("tower Hit");
                this.lastHit = this.now;
                //call the losehealth function
                //added global variable for playerAttack
                response.b.loseHealth(game.data.playerAttack);
            }
},

collideWithEnemyCreep: function(response){
//the y difference between the players y position and the creep y position
            //keep track of the position of both objects
        	var xdif = this.pos.x - response.b.pos.x;
        	var ydif = this.pos.y - response.b.pos.y;
        	this.stopMovement(xdif);
        	if(this.checkAttack(xdif, ydif)){
        	this.hitCreep(response);

        	};
	},

	stopMovement: function(xdif){
	if (xdif>0){
        		//when the player and creep are facing each other, the player can attack.
        		if(this.facing==="left"){
        			//sets the velocity to 0
        			this.body.vel.x = 0;
        		}
        	}else{
        		//when the player and creep are facing each other, the player can attack.
        		if(this.facing==="right"){
        			// sets the velocity to 0
        			this.body.vel.x = 0;
        		}
        	}
	},

	checkAttack: function(xdif, ydif){
	//added a global variable for playerAttackTimer
        	if(this.renderable.isCurrentAnimation("attack") && this.now - this.lastHit >= game.data.playerAttackTimer
        			&& (Math.abs(ydif) <=40) &&
        			(((xdif>0) && this.facing==="left") || ((xdif<0) && this.facing==="right"))) {

        		this.lastHit = this.now;
      			return true;
        	}
        	return false;
	},

	hitCreep: function(response){
	//if the creeps health is less than our attack, execute code in if statement
        		if(response.b.health <= game.data.playerAttack){
        			//adds one gold for a creep gold
        			game.data.gold += 1;
        			//shows in the console log
        			console.log("Current gold: " + game.data.gold);
        		}
        		//calls the lose health function from the creep.
        		//aded a global variable for playerAttack
        		response.b.loseHealth(game.data.playerAttack);
	}
});

//Added a second player
game.Player2 = me.Entity.extend({
// sets properties of enemy player
	init: function(x, y, settings){
		this._super(me.Entity, "init", [x, y, {
			image: "Player2",
			width: 100,
			height: 85,
			spritewidth: "100",
			spriteheight: "85",
			getShape: function(){
				return(new me.Rect(0, 0 ,100, 85)).toPolygon();
			}
		}]);

		// sets health of player starting at 10
		this.health = game.data.playerHealth;
		// always keeps the enemy player updated
		this.alwaysUpdate = true;

		// this.attacking lets us know if thge enemy is currently attacking
		this.attacking = false;

		// keeps track of when our creep last attacked anything
		this.lastAttacking = new Date().getTime();

		// keeps track of the ;ast time our creep hit anything
		this.lastHit = new Date().getTime();

		// timer
		this.now = new Date().getTime();

		// sets were player is located
		this.body.setVelocity(3, 20);

		// sets type of player
		this.type = "Player2";

		// sets the animation of enemy player
		this.renderable.addAnimation("walk", [0, 1, 2, 3, 4], 80);
		this.renderable.setCurrentAnimation("walk");
	},

	update: function(delta){
		// Timer set to check collisons refreshes every single time
		this.now = new Date().getTime();

		// makes creeps move
		this.body.vel.x += this.body.accel.x * me.timer.tick;
		this.flipX(true);

		// checks of creep is colliding with player
		// me.collison.check(this, true, this.collideHandler.bind(this), true);

		this.body.update(delta);

		this._super(me.Entity, "update", [delta]);

		return true;

	},

	collideHandler: function(response){
		if (response.b.type === 'EnemyBaseEntity') {
			this.attacking = true;
			// this.lastAttacking = this.now;
			this.body.vel.x = 0;
			// keeps creep moving to the right to maintain its position
			this.pos.x = this.pos.x + 1;
			// checks that it has been at least 1 second since this creep hit a base
			if ((this.now-this.lastHit >= 1000)) {
				// updates the lasthit timer
				this.lastHit = this.now;
				// makes the player base call its loseHealth function and passes at a damge of 1
				response.b.loseHealth(1);
			}
		}
		else if (response.b.type === 'EnemyCreep') {
			var xdif = this.pos.x - response.b.pos.x;

			this.attacking = true;

			// this.lastAttacking = this.now;

			if (xdif>0) {
			// Kepps moving the creep to the right to maintain its position
				this.pos.x = this.pos.x + 1;
				this.body.vel.x = 0;
			}
			// checks that it has been less then 1 second since it hit somehting
			if ((this.now-this.lastHit >= 1000) && xdif>0) {
				// updates the last hit time
				this.lastHit = this.now;
				// makes the player call its lose health function and passes it as a damage of one
				response.b.loseHealth(1);
			}
		}
	}

});<|endoftext|>


<commit_before>// TODO
game.PlayerEntity = me.Entity.extend ({
		init: function(x, y, settings) {
		// this is a class
		this.setSuper();
		// going to make the init function easier
		this.setPlayerTimers();
		// setting timers
		this.setAttributes();
		this.type = 'PlayerEntity';
		this.setFlags();

		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);
		// this says wherever the player goes the screen will follow him
		this.addAnimation();

		this.renderable.setCurrentAnimation("idle");

	},
	// making functions so that the code can look clean and function easier
	setSuper: function() {
		// melon js uses this constructor on most things to help us set up
		this._super(me.Entity, "init", [x, y, {
			// this means reaching to the constructor of entites
			image: "player",
			width: 64,
			// tells the screen what amount of space to reserve
			height: 64,
			spritewidth: "64",
			// spritewidth/height are passing the main information tells what to do with the image
			spriteheight: "64",
			// these are setting the properties of the picture o the right demensions so the picture appears properly
			getShape: function() {
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
				// rect is what the guy can walk in to
			}
		}]);
	},

	setPlayerTimers: function() {
		this.now = new Date().getTime();
		// keeps track of what time it is in the game
		this.lastHit = this.now;
		// keeps track of what time it is in the game basically doing the this.now variable
		this.lastAttack = new Date().getTime();
		// this is stopping the attacks
	},

	setAttributes: function() {
		this.health = game.data.playerHealth;
		// using the games file to set the movements
		this.body.setVelocity(game.data.playerMoveSpeed, 20);
		// this also changes the y velocity of the character
		this.attack = game.data.playerAttack;
	},

	setFlags: function() {
		this.facing = "right";
		// keeps track of which direction the character is going
		// this is the movement speed of the character
		this.dead = false;
		// local variable being kept track in the fly
	},

	addAnimation: function() {
		this.renderable.addAnimation("idle", [78]);
		// when the character is still this is what he will look like
		this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
		// this is going to be what the cahracter is going to change into
		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72] , 80);
	},

	update: function(delta) {
		this.now = new Date().getTime();
		// this function is what happens on the fly
		this.dead = checkIfDead();

		this.checkKeyPressesAndMove();

		if(me.input.isKeyPressed("attack")) {
			if (!this.renderable.isCurrentAnimation("attack")) {
				// set current animation to attack and once that is over
				// goes back to the idle animations
				this.renderable.setCurrentAnimation("attack", "idle");
				// makes it so that the next time we start this sequence we begin from the first animation not where we left off when we switched to another animation
				this.renderable.setAnimationFrame();
			}
		}
		if(this.body.vel.x !== 0 && !this.renderable.isCurrentAnimation("attack"))
		//allowing the guy to not immediately walk
		{
			if(!this.renderable.isCurrentAnimation("walk")) {
				this.renderable.setCurrentAnimation("walk");
				// this says it doesnt want to start the walk animation if it is already walking
			}
		}
		else if(!this.renderable.isCurrentAnimation("attack")) {
			this.renderable.setCurrentAnimation("idle");
		}
		me.collision.check(this, true, this.collideHandler.bind(this), true);
		// passing a parameter into collide function
		// delta is the change in time that has happens
		this.body.update(delta);

		this._super(me.Entity, "update", [delta]);
		// this is updating the animations on the fly
		return true;
	},

	checkIfDead: function () {
		if (this.health <= 0) {
			return true;
			// this is killing my player enemy
		}
	},

	checkKeyPressesAndMove: function () {

		if(me.input.isKeyPressed("right")) {
			this.moveRight();

		}
		else if(me.input.isKeyPressed("left")) {
			this.moveLeft();

		}
		else {
			this.body.vel.x = 0;
		}
		if (me.input.isKeyPressed('jump') && !this.body.jumping && !this.body.falling) {
     	 	this.jump();
        }
	},
	moveRight: function() {
		// set the position of my x by adding the velocity to find above in set veloctiy
			// setVeloctiy() and multiplying it by timer.tick
			// me.timer.tick makes the movement look smooth
			this.facing = "right";
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			this.flipX(true);
			// this is flipping the animation around
	},
	moveLeft: function() {
		// set the position of my x by adding the velocity to find above in set veloctiy
			// setVeloctiy() and multiplying it by timer.tick
			// me.timer.tick makes the movement look smooth
			this.facing = "left";
			this.body.vel.x -= this.body.accel.x * me.timer.tick;
			this.flipX(false);
			// this is flipping the animation around
	},
	jump: function() {
		 // make sure we are not already jumping or falling
      		this.body.jumping = true;
        // set current vel to the maximum defined value
        // gravity will then do the rest
        	this.body.vel.y -= this.body.accel.y * me.timer.tick;
        	me.audio.play("jump");
	},

	loseHealth: function(damage) {
		this.health = this.health - damage;
		// subtracting players health

	},

	collideHandler: function(response) {
		if(response.b.type === 'EnemyBase'){
			this.collideWithEnemyBase(response);
		}
		else if(response.b.type==='EnemyCreep') {
			this.collideWithEnemyCreep(response);
		},

	collideWithEnemyBase: function () {
			var ydif = this.pos.y - response.b.pos.y;
			var xdif = this.pos.x - response.b.pos.x;

			if (ydif< -40 && xdif< 70 && xdif > -35) {
				this.body.falling = false;
				this.body.vel.y = -1;
			}

			else if (xdif > -30 && this.facing === 'right' && (xdif < 0)) {
				this.body.vel.x = 0;
				// stops the player from moving
				// this.pos.x = this.pos.x - 1;
				// slighty turns the character
			}
			else if (xdif< 70 && this.facing === 'left' && xdif > 0) {
				this.body.vel.x = 0;
				// stops the player from moving
				// this.pos.x = this.pos.x + 1;
				// cant walk into castle from left or right
			}
			if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer) {
				this.lastHit = this.now;
				response.b.loseHealth(game.data.playerAttack);
				// if we are attacking and hitting the castle it looses health
			}
	},
	collideWithEnemyCreep: function() {
		var xdif = this.pos.x - response.b.pos.x;
			var ydif = this.pos.y - response.b.pos.y;

			this.stopMovement(xdif);
			if (this.checkAttack(xif, ydif, response)) {
				this.hitCreep(response);
			};

	},
	stopMovement: function () {
			if (xdif >0) {
				this.pos.x = this.pos.x +1;
			// pushing the player a little to the right if coming in from the right and allowing us not to crash into the creep
			if(this.facing ==="left") {
					this.body.vel.x = 0;
				}
			}
			else {
			//pushing the player to the left if coming in from the left, and allowing us not to crash into the creep
			if(this.facing ==="right") {
					this.body.vel.x = 0;
				}

			}
		},

	checkAttack: function (xdif, ydif) {
		if(this.renderable.isCurrentAnimation("attack")&& this.now-this.lastHit >= game.data.playerAttackTimer && (Math.abs(ydif) <= 40) && (((xdif >0) && this.facing==="left") || ((xdif<0 && this.facing==="right")))
				) {
				// if the character is to the right of the creep and you are facing left it should be able to be attacked and vice vera
				// making sure we can hit the creep
				this.lastHit = this.now;
				// if the creeps health is less than our attack, execute code in our statements
				return true;

		}
				return false;
		},

	hitCreep: function () {
		if(response.b.health <= game.data.playerAttack) {
				// adds one gold for a creep kill
				game.data.gold += 1;
				console.log("Current gold: " + game.data.gold);
			}
				response.b.loseHealth(game.data.playerAttack);
				// making the creep loose one energy when hit
			}
		// this is going to determine what happens when we hit the enemy entity
	},
	// all these functions are simply breaking down the code into diiferent funcitons so it is easier for us

});<commit_msg>finished 34<commit_after>// TODO
game.PlayerEntity = me.Entity.extend ({
		init: function(x, y, settings) {
		// this is a class
		this.setSuper(x,y);
		// going to make the init function easier
		this.setPlayerTimers();
		// setting timers
		this.setAttributes();
		this.type = 'PlayerEntity';
		this.setFlags();

		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);
		// this says wherever the player goes the screen will follow him
		this.addAnimation();

		this.renderable.setCurrentAnimation("idle");

	},
	// making functions so that the code can look clean and function easier
	setSuper: function(x,y) {
		// melon js uses this constructor on most things to help us set up
		this._super(me.Entity, "init", [x, y, {
			// this means reaching to the constructor of entites
			image: "player",
			width: 64,
			// tells the screen what amount of space to reserve
			height: 64,
			spritewidth: "64",
			// spritewidth/height are passing the main information tells what to do with the image
			spriteheight: "64",
			// these are setting the properties of the picture o the right demensions so the picture appears properly
			getShape: function() {
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
				// rect is what the guy can walk in to
			}
		}]);
	},

	setPlayerTimers: function() {
		this.now = new Date().getTime();
		// keeps track of what time it is in the game
		this.lastHit = this.now;
		// keeps track of what time it is in the game basically doing the this.now variable
		this.lastAttack = new Date().getTime();
		// this is stopping the attacks
	},

	setAttributes: function() {
		this.health = game.data.playerHealth;
		// using the games file to set the movements
		this.body.setVelocity(game.data.playerMoveSpeed, 20);
		// this also changes the y velocity of the character
		this.attack = game.data.playerAttack;
	},

	setFlags: function() {
		this.facing = "right";
		// keeps track of which direction the character is going
		// this is the movement speed of the character
		this.dead = false;
		this.attacking = false;
		// local variable being kept track in the fly
	},

	addAnimation: function() {
		this.renderable.addAnimation("idle", [78]);
		// when the character is still this is what he will look like
		this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
		// this is going to be what the cahracter is going to change into
		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72] , 80);
	},

	update: function(delta) {
		this.now = new Date().getTime();
		// this function is what happens on the fly
		this.dead = this.checkIfDead();

		this.checkKeyPressesAndMove();

		if(me.input.isKeyPressed("attack")) {
			if (!this.renderable.isCurrentAnimation("attack")) {
				// set current animation to attack and once that is over
				// goes back to the idle animations
				this.renderable.setCurrentAnimation("attack", "idle");
				// makes it so that the next time we start this sequence we begin from the first animation not where we left off when we switched to another animation
				this.renderable.setAnimationFrame();
			}
		}
		if(this.body.vel.x !== 0 && !this.renderable.isCurrentAnimation("attack"))
		//allowing the guy to not immediately walk
		{
			if(!this.renderable.isCurrentAnimation("walk")) {
				this.renderable.setCurrentAnimation("walk");
				// this says it doesnt want to start the walk animation if it is already walking
			}
		}
		else if(!this.renderable.isCurrentAnimation("attack")) {
			this.renderable.setCurrentAnimation("idle");
		}
		me.collision.check(this, true, this.collideHandler.bind(this), true);
		// passing a parameter into collide function
		// delta is the change in time that has happens
		this.body.update(delta);

		this._super(me.Entity, "update", [delta]);
		// this is updating the animations on the fly
		return true;
	},

	checkIfDead: function () {
		if (this.health <= 0) {
			return true;
			// this is killing my player enemy
		}
	},

	checkKeyPressesAndMove: function () {

		if(me.input.isKeyPressed("right")) {
			this.moveRight();

		}
		else if(me.input.isKeyPressed("left")) {
			this.moveLeft();

		}
		else {
			this.body.vel.x = 0;
		}
		if (me.input.isKeyPressed('jump') && !this.body.jumping && !this.body.falling) {
     	 	this.jump();
        }
        this.attacking = me.input.isKeyPressed("attack");
	},
	moveRight: function() {
		// set the position of my x by adding the velocity to find above in set veloctiy
			// setVeloctiy() and multiplying it by timer.tick
			// me.timer.tick makes the movement look smooth
			this.facing = "right";
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			this.flipX(true);
			// this is flipping the animation around
	},
	moveLeft: function() {
		// set the position of my x by adding the velocity to find above in set veloctiy
			// setVeloctiy() and multiplying it by timer.tick
			// me.timer.tick makes the movement look smooth
			this.facing = "left";
			this.body.vel.x -= this.body.accel.x * me.timer.tick;
			this.flipX(false);
			// this is flipping the animation around
	},
	jump: function() {
		 // make sure we are not already jumping or falling
      		this.body.jumping = true;
        // set current vel to the maximum defined value
        // gravity will then do the rest
        	this.body.vel.y -= this.body.accel.y * me.timer.tick;
        	me.audio.play("jump");
	},

	loseHealth: function(damage) {
		this.health = this.health - damage;
		// subtracting players health

	},

	collideHandler: function(response) {
		if(response.b.type === 'EnemyBase'){
			this.collideWithEnemyBase(response);
		}
		else if(response.b.type==='EnemyCreep') {
			this.collideWithEnemyCreep(response);
		}
	},

	collideWithEnemyBase: function (response) {
			var ydif = this.pos.y - response.b.pos.y;
			var xdif = this.pos.x - response.b.pos.x;

			if (ydif< -40 && xdif< 70 && xdif > -35) {
				this.body.falling = false;
				this.body.vel.y = -1;
			}

			else if (xdif > -30 && this.facing === 'right' && (xdif < 0)) {
				this.body.vel.x = 0;
				// stops the player from moving
				// this.pos.x = this.pos.x - 1;
				// slighty turns the character
			}
			else if (xdif< 70 && this.facing === 'left' && xdif > 0) {
				this.body.vel.x = 0;
				// stops the player from moving
				// this.pos.x = this.pos.x + 1;
				// cant walk into castle from left or right
			}
			if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer) {
				this.lastHit = this.now;
				response.b.loseHealth(game.data.playerAttack);
				// if we are attacking and hitting the castle it looses health
			}
	},
	collideWithEnemyCreep: function(response) {
		var xdif = this.pos.x - response.b.pos.x;
		var ydif = this.pos.y - response.b.pos.y;

			this.stopMovement(xdif);
			if (this.checkAttack(xdif, ydif)) {
				this.hitCreep(response);
			};

	},
	stopMovement: function (xdif) {
			if (xdif > 0) {
				this.pos.x = this.pos.x +1;
			// pushing the player a little to the right if coming in from the right and allowing us not to crash into the creep
			if(this.facing ==="left") {
					this.body.vel.x = 0;
				}
			}
			else {
			//pushing the player to the left if coming in from the left, and allowing us not to crash into the creep
			if(this.facing ==="right") {
					this.body.vel.x = 0;
				}

			}
		},

	checkAttack: function (xdif, ydif) {
		if(this.renderable.isCurrentAnimation("attack")&& this.now-this.lastHit >= game.data.playerAttackTimer && (Math.abs(ydif) <= 40) && (((xdif >0) && this.facing==="left") || ((xdif<0 && this.facing==="right")))
				) {
				// if the character is to the right of the creep and you are facing left it should be able to be attacked and vice vera
				// making sure we can hit the creep
				this.lastHit = this.now;
				// if the creeps health is less than our attack, execute code in our statements
				return true;

		}
				return false;
		},
	hitCreep: function (response) {
		if(response.b.health <= game.data.playerAttack) {
				// adds one gold for a creep kill
				game.data.gold += 1;
				console.log("Current gold: " + game.data.gold);
			}
				response.b.loseHealth(game.data.playerAttack);
				// making the creep loose one energy when hit
			}
		// this is going to determine what happens when we hit the enemy entity
	// all these functions are simply breaking down the code into diiferent funcitons so it is easier for us

});<|endoftext|>


<commit_before>var BirdEntity = me.ObjectEntity.extend({
    init: function(x, y) {
        var settings = {};
        var rand = Math.floor((Math.random() * 6) + 1);
        if(rand == 1){
            settings.image = me.loader.getImage('alimesbah');
        }
        else if(rand == 2){
            settings.image = me.loader.getImage('clumsy2');
        }
        else if(rand == 3){
            settings.image = me.loader.getImage('clumsy3');
        }
        else if (rand == 4){
            settings.image = me.loader.getImage('clumsy4');
        }
        else if(rand == 5){
            settings.image = me.loader.getImage('clumsy');
        }
        else if(rand == 6){
            settings.image = me.loader.getImage('clumsy5');
        }
        settings.width = 85;
        settings.height = 60;
        settings.spritewidth = 85;
        settings.spriteheight= 60;

        this.parent(x, y, settings);
        this.alwaysUpdate = true;
        this.gravity = 0.2;
        this.gravityForce = 0.01;
        this.maxAngleRotation = Number.prototype.degToRad(30);
        this.maxAngleRotationDown = Number.prototype.degToRad(90);
        this.renderable.addAnimation("flying", [0, 1, 2]);
        this.renderable.addAnimation("idle", [0]);
        this.renderable.setCurrentAnimation("flying");
        this.renderable.anchorPoint = new me.Vector2d(0.2, 0.5);
        this.animationController = 0;
        // manually add a rectangular collision shape
        this.addShape(new me.Rect(new me.Vector2d(5, 5), 70, 50));

        // a tween object for the flying physic effect
        this.flyTween = new me.Tween(this.pos);
        this.flyTween.easing(me.Tween.Easing.Exponential.InOut);

        this.endTween = new me.Tween(this.pos);
        this.flyTween.easing(me.Tween.Easing.Exponential.InOut);
    },

    update: function(dt) {
        // mechanics
        if (!game.data.start) {
            return this.parent(dt);
        }
        if (me.input.isKeyPressed('pause')) {
            game.data.paused = !game.data.paused;
        }
        if (game.data.paused){
            return this.parent(dt);
        }
        if (me.input.isKeyPressed('fly')) {
            me.audio.play('wing');
            this.gravityForce = 0.02;

            var currentPos = this.pos.y;
            // stop the previous one
            this.flyTween.stop();
            this.flyTween.to({y: currentPos - 72}, 100);
            this.flyTween.start();

            this.renderable.angle = -this.maxAngleRotation;
        } else {
            this.gravityForce += 0.2;
            this.pos.y += me.timer.tick * this.gravityForce;
            this.renderable.angle += Number.prototype.degToRad(3) * me.timer.tick;
            if (this.renderable.angle > this.maxAngleRotationDown)
                this.renderable.angle = this.maxAngleRotationDown;
        }

        var res = me.game.world.collide(this);
        var collided = false;

        if (res) {
            if (res.obj.type === 'pipe' || res.obj.type === 'ground') {
                me.device.vibrate(500);
                collided = true;
            }
            // remove the hit box
            if (res.obj.type === 'hit') {
                me.game.world.removeChildNow(res.obj);
                // the give dt parameter to the update function
                // give the time in ms since last frame
                // use it instead ?
                game.data.steps++;
                me.audio.play('hit');
            }

        }
        // var hitGround = me.game.viewport.height - (96 + 60);
        var hitSky = -80; // bird height + 20px
        if (this.pos.y <= hitSky || collided) {
            game.data.start = false;
            me.audio.play("lose");
            this.endAnimation();
            return false;
        }
        return this.parent(dt);
    },

    endAnimation: function() {
        me.game.viewport.fadeOut("#fff", 100);
        var that = this;
        var currentPos = this.pos.y;
        this.flyTween.stop();
        this.renderable.angle = this.maxAngleRotationDown;
        this.endTween
            .to({y: currentPos - 72}, 1500)
            .to({y: me.video.getHeight() - 96 - that.renderable.width}, 500)
            .onComplete(function() {
                me.state.change(me.state.GAME_OVER);
            });
        this.endTween.start();
        return false;
    }

});

var PipeEntity = me.ObjectEntity.extend({
    init: function(x, y) {
        var settings = {};
        settings.image = me.loader.getImage('pipe');
        settings.width = 148;
        settings.height= 1664;
        settings.spritewidth = 148;
        settings.spriteheight= 1664;

        this.parent(x, y, settings);
        this.alwaysUpdate = true;
        this.gravity = 5;
        this.updateTime = false;
        this.type = 'pipe';
    },

    update: function(dt) {
        // mechanics
        if (!game.data.start) {
            return this.parent(dt);
        }
        if (game.data.paused){
            return this.parent(dt);
        }
        this.pos.add(new me.Vector2d(-this.gravity * me.timer.tick, 0));
        if (this.pos.x < -148) {
            me.game.world.removeChild(this);
        }
        return this.parent(dt);
    },

});

var PipeGenerator = me.Renderable.extend({
    init: function() {
        this.parent(new me.Vector2d(), me.game.viewport.width, me.game.viewport.height);
        this.alwaysUpdate = true;
        this.generate = 0;
        this.pipeFrequency = 92;
        this.pipeHoleSize = 1240;
        this.posX = me.game.viewport.width;
    },

    update: function(dt) {
        if (game.data.paused){
            return this.parent(dt);
        }
        if (this.generate++ % this.pipeFrequency == 0) {
            var posY = Number.prototype.random(
                    me.video.getHeight() - 100,
                    200
            );
            var posY2 = posY - me.video.getHeight() - this.pipeHoleSize;
            var pipe1 = new me.pool.pull("pipe", this.posX, posY);
            var pipe2 = new me.pool.pull("pipe", this.posX, posY2);
            var hitPos = posY - 100;
            var hit = new me.pool.pull("hit", this.posX, hitPos);
            pipe1.renderable.flipY();
            me.game.world.addChild(pipe1, 10);
            me.game.world.addChild(pipe2, 10);
            me.game.world.addChild(hit, 11);
        }
        return true;
    },

});

var HitEntity = me.ObjectEntity.extend({
    init: function(x, y) {
        var settings = {};
        settings.image = me.loader.getImage('hit');
        settings.width = 148;
        settings.height= 60;
        settings.spritewidth = 148;
        settings.spriteheight= 60;

        this.parent(x, y, settings);
        this.alwaysUpdate = true;
        this.gravity = 5;
        this.updateTime = false;
        this.type = 'hit';
        this.renderable.alpha = 0;
        this.ac = new me.Vector2d(-this.gravity, 0);
    },

    update: function() {
        // mechanics
        this.pos.add(this.ac);
        if (this.pos.x < -148) {
            me.game.world.removeChild(this);
        }
        return true;
    },

});

var Ground = me.ObjectEntity.extend({
    init: function(x, y) {
        var settings = {};
        settings.image = me.loader.getImage('ground');
        settings.width = 900;
        settings.height= 96;

        this.parent(x, y, settings);
        this.alwaysUpdate = true;
        this.gravity = 0;
        this.updateTime = false;
        this.accel = new me.Vector2d(-4, 0);
        this.type = 'ground';
    },

    update: function(dt) {
        // mechanics
        if (!game.data.start) {
            return this.parent(dt);
        }
        if (game.data.paused){
            return this.parent(dt);
        }
        this.pos.add(this.accel);
        if (this.pos.x < -this.renderable.width) {
            this.pos.x = me.video.getWidth() - 10;
        }
        return this.parent(dt);
    },

});<commit_msg>Pipes move now. Fixed scoring glitch<commit_after>var BirdEntity = me.ObjectEntity.extend({
    init: function(x, y) {
        var settings = {};
        var rand = Math.floor((Math.random() * 6) + 1);
        if(rand == 1){
            settings.image = me.loader.getImage('alimesbah');
        }
        else if(rand == 2){
            settings.image = me.loader.getImage('clumsy2');
        }
        else if(rand == 3){
            settings.image = me.loader.getImage('clumsy3');
        }
        else if (rand == 4){
            settings.image = me.loader.getImage('clumsy4');
        }
        else if(rand == 5){
            settings.image = me.loader.getImage('clumsy');
        }
        else if(rand == 6){
            settings.image = me.loader.getImage('clumsy5');
        }
        settings.width = 85;
        settings.height = 60;
        settings.spritewidth = 85;
        settings.spriteheight= 60;

        this.parent(x, y, settings);
        this.alwaysUpdate = true;
        this.gravity = 0.2;
        this.gravityForce = 0.01;
        this.maxAngleRotation = Number.prototype.degToRad(30);
        this.maxAngleRotationDown = Number.prototype.degToRad(90);
        this.renderable.addAnimation("flying", [0, 1, 2]);
        this.renderable.addAnimation("idle", [0]);
        this.renderable.setCurrentAnimation("flying");
        this.renderable.anchorPoint = new me.Vector2d(0.2, 0.5);
        this.animationController = 0;
        // manually add a rectangular collision shape
        this.addShape(new me.Rect(new me.Vector2d(5, 5), 70, 50));

        // a tween object for the flying physic effect
        this.flyTween = new me.Tween(this.pos);
        this.flyTween.easing(me.Tween.Easing.Exponential.InOut);

        this.endTween = new me.Tween(this.pos);
        this.flyTween.easing(me.Tween.Easing.Exponential.InOut);
    },

    update: function(dt) {
        // mechanics
        if (!game.data.start) {
            return this.parent(dt);
        }
        if (me.input.isKeyPressed('pause')) {
            game.data.paused = !game.data.paused;
        }
        if (game.data.paused){
            return this.parent(dt);
        }
        if (me.input.isKeyPressed('fly')) {
            me.audio.play('wing');
            this.gravityForce = 0.02;

            var currentPos = this.pos.y;
            // stop the previous one
            this.flyTween.stop();
            this.flyTween.to({y: currentPos - 72}, 100);
            this.flyTween.start();

            this.renderable.angle = -this.maxAngleRotation;
        } else {
            this.gravityForce += 0.2;
            this.pos.y += me.timer.tick * this.gravityForce;
            this.renderable.angle += Number.prototype.degToRad(3) * me.timer.tick;
            if (this.renderable.angle > this.maxAngleRotationDown)
                this.renderable.angle = this.maxAngleRotationDown;
        }

        var res = me.game.world.collide(this);
        var collided = false;

        if (res) {
            if (res.obj.type === 'pipe' || res.obj.type === 'ground') {
                me.device.vibrate(500);
                collided = true;
            }
            // remove the hit box
            if (res.obj.type === 'hit') {
                me.game.world.removeChildNow(res.obj);
                // the give dt parameter to the update function
                // give the time in ms since last frame
                // use it instead ?
                game.data.steps++;
                me.audio.play('hit');
            }

        }
        // var hitGround = me.game.viewport.height - (96 + 60);
        var hitSky = -80; // bird height + 20px
        if (this.pos.y <= hitSky || collided) {
            game.data.start = false;
            me.audio.play("lose");
            this.endAnimation();
            return false;
        }
        return this.parent(dt);
    },

    endAnimation: function() {
        me.game.viewport.fadeOut("#fff", 100);
        var that = this;
        var currentPos = this.pos.y;
        this.flyTween.stop();
        this.renderable.angle = this.maxAngleRotationDown;
        this.endTween
            .to({y: currentPos - 72}, 1500)
            .to({y: me.video.getHeight() - 96 - that.renderable.width}, 500)
            .onComplete(function() {
                me.state.change(me.state.GAME_OVER);
            });
        this.endTween.start();
        return false;
    }

});

var PipeEntity = me.ObjectEntity.extend({
    init: function(x, y) {
        var settings = {};
        settings.image = me.loader.getImage('pipe');
        settings.width = 148;
        settings.height= 1664;
        settings.spritewidth = 148;
        settings.spriteheight= 1664;

        this.parent(x, y, settings);
        this.alwaysUpdate = true;
        this.gravity = 5;
        this.updateTime = false;
        this.type = 'pipe';
        this.tempY;
        this.downDirectionFlag;
        if(this.pos.y < 0){
            this.tempY = this.pos.y + 1840;
        } else{
            this.tempY = this.pos.y;
        }
        console.log(this.tempY);
        if(this.tempY < 325){
            this.downDirectionFlag = true;
        }
        else{
            this.downDirectionFlag = false;
        }
    },

    update: function(dt) {
        // mechanics

        if (!game.data.start) {
            return this.parent(dt);
        }
        if (game.data.paused){
            return this.parent(dt);
        }
        if(this.downDirectionFlag){
             this.pos.add(new me.Vector2d(-this.gravity * me.timer.tick, 0.5));
        } else{
            this.pos.add(new me.Vector2d(-this.gravity * me.timer.tick, -0.5));
        }

        if (this.pos.x < -148) {
            me.game.world.removeChild(this);
        }
        return this.parent(dt);
    },

});

var PipeGenerator = me.Renderable.extend({
    init: function() {
        this.parent(new me.Vector2d(), me.game.viewport.width, me.game.viewport.height);
        this.alwaysUpdate = true;
        this.generate = 0;
        this.pipeFrequency = 92;
        this.pipeHoleSize = 1240;
        this.posX = me.game.viewport.width;
        this.posY;
    },

    update: function(dt) {
        if (game.data.paused){
            return this.parent(dt);
        }
        if (this.generate++ % this.pipeFrequency == 0) {
            var posY = Number.prototype.random(
                    me.video.getHeight() - 100,
                    200
            );
            var posY2 = posY - me.video.getHeight() - this.pipeHoleSize;
            this.posY = posY2;
            var pipe1 = new me.pool.pull("pipe", this.posX, posY);
            var pipe2 = new me.pool.pull("pipe", this.posX, posY2);
            if(posY < 325){
                var hitPos = posY - 100;
            } else {
                var hitPos = posY - 150;
            }
            var hit = new me.pool.pull("hit", this.posX, hitPos);
            pipe1.renderable.flipY();
            me.game.world.addChild(pipe1, 10);
            me.game.world.addChild(pipe2, 10);
            me.game.world.addChild(hit, 11);
        }
        return true;
    },

});

var HitEntity = me.ObjectEntity.extend({
    init: function(x, y) {
        var settings = {};
        settings.image = me.loader.getImage('hit');
        settings.width = 148;
        settings.height= 60;
        settings.spritewidth = 148;
        settings.spriteheight= 60;

        this.parent(x, y, settings);
        this.alwaysUpdate = true;
        this.gravity = 5;
        this.updateTime = false;
        this.type = 'hit';
        this.renderable.alpha = 0;
        this.ac = new me.Vector2d(-this.gravity, 0);
    },

    update: function() {
        // mechanics
        this.pos.add(this.ac);
        if (this.pos.x < -148) {
            me.game.world.removeChild(this);
        }
        return true;
    },

});

var Ground = me.ObjectEntity.extend({
    init: function(x, y) {
        var settings = {};
        settings.image = me.loader.getImage('ground');
        settings.width = 900;
        settings.height= 96;

        this.parent(x, y, settings);
        this.alwaysUpdate = true;
        this.gravity = 0;
        this.updateTime = false;
        this.accel = new me.Vector2d(-4, 0);
        this.type = 'ground';
    },

    update: function(dt) {
        // mechanics
        if (!game.data.start) {
            return this.parent(dt);
        }
        if (game.data.paused){
            return this.parent(dt);
        }
        this.pos.add(this.accel);
        if (this.pos.x < -this.renderable.width) {
            this.pos.x = me.video.getWidth() - 10;
        }
        return this.parent(dt);
    },

});<|endoftext|>


<commit_before>/**
 * Reveal module.
 * @module foundation.reveal
 * @requires foundation.util.keyboard
 * @requires foundation.util.size-and-collision
 * @requires foundation.util.triggers
 * @requires foundation.util.mediaQuery
 */
!function(Foundation, $) {
  'use strict';

  /**
   * Creates a new instance of Reveal.
   * @class
   * @fires Reveal#init
   * @param {jQuery} element - jQuery object to use for the modal.
   * @param {Object} options - optional parameters.
   */

  function Reveal(element, options) {
    this.$element = element;
    this.options = $.extend({}, Reveal.defaults, this.$element.data(), options);
    this._init();

    Foundation.registerPlugin(this);
    Foundation.Keyboard.register('Reveal', {
      'ENTER': 'open',
      'SPACE': 'open',
      'ESCAPE': 'close',
      'TAB': 'tab_forward',
      'SHIFT_TAB': 'tab_backward'
    });
    // /**
    //  * Fires when the plugin has been successfuly initialized.
    //  * @event Reveal#init
    //  */
    // this.$element.trigger('init.zf.reveal');
  }

  Reveal.defaults = {
    animationIn: '',
    animationOut: '',
    showDelay: 0,
    hideDelay: 0,
    closeOnClick: true,
    closeOnEsc: true,
    multipleOpened: false,
    vOffset: 100,
    hOffset: 0,
    fullScreen: false,
    btmOffsetPct: 10,
    overlay: true
  };

  /**
   * Initializes the modal by adding the overlay and close buttons, (if selected).
   * @private
   */
  Reveal.prototype._init = function(){
    this.id = this.$element.attr('id');
    this.isActive = false;

    this.$anchor = $('[data-open="' + this.id + '"]').length ? $('[data-open="' + this.id + '"]') : $('[data-toggle="' + this.id + '"]');

    if(this.$anchor.length){
      var anchorId = this.$anchor[0].id || Foundation.GetYoDigits(6, 'reveal');

      this.$anchor.attr({
        'aria-controls': this.id,
        'id': anchorId,
        'aria-haspopup': true,
        'tabindex': 0
      });
      this.$element.attr({'aria-labelledby': anchorId});
    }

    // this.options.fullScreen = this.$element.hasClass('full');
    if(this.options.fullScreen || this.$element.hasClass('full')){
      this.options.fullScreen = true;
      this.options.overlay = false;
    }
    if(this.options.overlay){
      this.$overlay = this._makeOverlay(this.id);
    }

    this.$element.attr({
        'role': 'dialog',
        'aria-hidden': true,
        'data-yeti-box': this.id,
        'data-resize': this.id
    });

    this._events();
  };

  /**
   * Creates an overlay div to display behind the modal.
   * @private
   */
  Reveal.prototype._makeOverlay = function(id){
    var $overlay = $('

')
                    .addClass('reveal-overlay')
                    .attr({'tabindex': -1, 'aria-hidden': true})
                    .appendTo('body');
    if(this.options.closeOnClick){
      $overlay.attr({
        'data-close': id
      });
    }
    return $overlay;
  };

  /**
   * Adds event handlers for the modal.
   * @private
   */
  Reveal.prototype._events = function(){
    var _this = this;

    this.$element.on({
      'open.zf.trigger': this._open.bind(this),
      'close.zf.trigger': this._close.bind(this),
      'toggle.zf.trigger': this.toggle.bind(this),
      'resizeme.zf.trigger': function(){
        if(_this.$element.is(':visible')){
          _this._setPosition(function(){});
        }
      }
    });

    if(this.$anchor.length){
      this.$anchor.on('keydown.zf.reveal', function(e){
        if(e.which === 13 || e.which === 32){
          e.stopPropagation();
          e.preventDefault();
          _this._open();
        }
      });
    }

    if(this.options.closeOnClick && this.options.overlay){
      this.$overlay.off('.zf.reveal').on('click.zf.reveal', this._close.bind(this));
    }
  };
  /**
   * Sets the position of the modal before opening
   * @param {Function} cb - a callback function to execute when positioning is complete.
   * @private
   */
  Reveal.prototype._setPosition = function(cb){
    var eleDims = Foundation.GetDimensions(this.$element);
    var elePos = this.options.fullScreen ? 'reveal full' : (eleDims.height >= (0.5 * eleDims.windowDims.height)) ? 'reveal' : 'center';

    if(elePos === 'reveal full'){
      console.log('full');
      //set to full height/width
      this.$element
          .offset(Foundation.GetOffsets(this.$element, null, elePos, this.options.vOffset))
          .css({
            'height': eleDims.windowDims.height,
            'width': eleDims.windowDims.width
          });
    }else if(!Foundation.MediaQuery.atLeast('medium') || !Foundation.ImNotTouchingYou(this.$element, null, true, false)){
      //if smaller than medium, resize to 100% width minus any custom L/R margin
      this.$element
          .css({
            'width': eleDims.windowDims.width - (this.options.hOffset * 2)
          })
          .offset(Foundation.GetOffsets(this.$element, null, 'center', this.options.vOffset, this.options.hOffset));
      //flag a boolean so we can reset the size after the element is closed.
      this.changedSize = true;
    }else{
      this.$element
          .css({
            'max-height': eleDims.windowDims.height - (this.options.vOffset * (this.options.btmOffsetPct / 100 + 1)),
            'width': ''
          })
          .offset(Foundation.GetOffsets(this.$element, null, elePos, this.options.vOffset));
          //the max height based on a percentage of vertical offset plus vertical offset
    }

    cb();
  };

  /**
   * Opens the modal controlled by `this.$anchor`, and closes all others by default.
   * @fires Reveal#closeAll
   * @fires Reveal#open
   */
  Reveal.prototype._open = function(){
    var _this = this;
    this.isActive = true;
    //make element invisible, but remove display: none so we can get size and positioning
    this.$element
        .css({'visibility': 'hidden'})
        .show()
        .scrollTop(0);

    this._setPosition(function(){
      _this.$element.hide()
                   .css({'visibility': ''});
      if(!_this.options.multipleOpened){
        /**
         * Fires immediately before the modal opens.
         * Closes any other modals that are currently open
         * @event Reveal#closeAll
         */
        _this.$element.trigger('closeme.zf.reveal', _this.id);
      }
      if(_this.options.animationIn){
        if(_this.options.overlay){
          Foundation.Motion.animateIn(_this.$overlay, 'fade-in', function(){
            Foundation.Motion.animateIn(_this.$element, _this.options.animationIn, function(){
            });
          });
        }else{
          Foundation.Motion.animateIn(_this.$element, _this.options.animationIn, function(){
          });
        }
      }else{
        if(_this.options.overlay){
          _this.$overlay.show(0, function(){
            _this.$element.show(_this.options.showDelay, function(){
            });
          });
        }else{
          _this.$element.show(_this.options.showDelay, function(){
          });
        }
      }
    });

    // handle accessibility
    this.$element.attr({'aria-hidden': false}).attr('tabindex', -1).focus()
    /**
     * Fires when the modal has successfully opened.
     * @event Reveal#open
     */
                 .trigger('open.zf.reveal');

    $('body').addClass('is-reveal-open')
             .attr({'aria-hidden': (this.options.overlay || this.options.fullScreen) ? true : false});
    setTimeout(function(){
      _this._extraHandlers();
      // Foundation.reflow();
    }, 0);
  };

  /**
   * Adds extra event handlers for the body and window if necessary.
   * @private
   */
  Reveal.prototype._extraHandlers = function(){
    var _this = this;
    var visibleFocusableElements = this.$element.find('a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, *[tabindex], *[contenteditable]').filter(function() {
      if (!$(this).is(':visible') || $(this).attr('tabindex') < 0){ return false; }//only have visible elements and those that have a tabindex greater or equal 0
      return true;
    });

    if(!this.options.overlay && this.options.closeOnClick && !this.options.fullScreen){
      $('body').on('click.zf.reveal', function(e){
        // if()
          _this._close();
      });
    }
    if(this.options.closeOnEsc){
      $(window).on('keydown.zf.reveal', function(e){
        if (visibleFocusableElements.length === 0) { // no focusable elements inside the modal at all, prevent tabbing in general
          e.preventDefault();
        }
        Foundation.Keyboard.handleKey(e, _this, {
          close: function() {
            if (this.options.closeOnEsc) {
              this._close();
            }
          }
        });
      });
    }

    // lock focus within modal while tabbing
    this.$element.on('keydown.zf.reveal', function(e) {
      // handle keyboard event with keyboard util
      Foundation.Keyboard.handleKey(e, _this, {
        tab_forward: function() {
          if (this.$element.find(':focus').is(visibleFocusableElements.eq(-1))) { // left modal downwards, setting focus to first element
            visibleFocusableElements.eq(0).focus();
            e.preventDefault();
          }
        },
        tab_backward: function() {
          if (this.$element.find(':focus').is(visibleFocusableElements.eq(0)) || this.$element.is(':focus')) { // left modal upwards, setting focus to last element
            visibleFocusableElements.eq(-1).focus();
            e.preventDefault();
          }
        },
        open: function() {
          this._open();
        },
        close: function() {
          if (this.options.closeOnEsc) {
            this._close();
          }
        }
      });
      if (visibleFocusableElements.length === 0) { // no focusable elements inside the modal at all, prevent tabbing in general
        e.preventDefault();
      }
    });

  };

  /**
   * Closes the modal
   * @fires Reveal#closed
   */
  Reveal.prototype._close = function(){
    if(!this.isActive || !this.$element.is(':visible')){
      return false;
    }
    var _this = this;

    if(this.options.animationOut){
      Foundation.Motion.animateOut(this.$element, this.options.animationOut, function(){
        if(_this.options.overlay){
          Foundation.Motion.animateOut(_this.$overlay, 'fade-out', function(){
          });
        }
      });
    }else{
      this.$element.hide(_this.options.hideDelay, function(){
        if(_this.options.overlay){
          _this.$overlay.hide(0, function(){
          });
        }
      });
    }
    //conditionals to remove extra event listeners added on open
    if(this.options.closeOnEsc){
      $(window).off('keydown.zf.reveal');
    }
    if(!this.options.overlay && this.options.closeOnClick){
      $('body').off('click.zf.reveal');
    }
    this.$element.off('keydown.zf.reveal');

    //if the modal changed size, reset it
    if(this.changedSize){
      this.$element.css({
        'height': '',
        'width': ''
      });
    }

    $('body').removeClass('is-reveal-open').attr({'aria-hidden': false, 'tabindex': ''});

    this.isActive = false;
    this.$element.attr({'aria-hidden': true})
    /**
     * Fires when the modal is done closing.
     * @event Reveal#closed
     */
                 .trigger('closed.zf.reveal');
  };

  Reveal.prototype.toggle = function(){
    if(this.isActive){
      this._close();
    }else{
      this._open();
    }
  };

  /**
   * Destroys an instance of a modal.
   * @fires Reveal#destroyed
   */
  Reveal.prototype.destroy = function() {
    if(this.options.overlay){
      this.$overlay.hide().off();
    }
    this.$element.hide();
    this.$anchor.off();

    Foundation.unregisterPlugin(this);

    /**
     * Fires when the plugin has been destroyed.
     * @event Reveal#destroyed
     */
    // this.$element.trigger('destroyed.zf.reveal');
  };

  Foundation.plugin(Reveal);

  // Exports for AMD/Browserify
  if (typeof module !== 'undefined' && typeof module.exports !== 'undefined')
    module.exports = Reveal;
  if (typeof define === 'function')
    define(['foundation'], function() {
      return Reveal;
    });

}(Foundation, jQuery);
<commit_msg>Fixed keyboard input being interpreted by keyboard util when within input elements.<commit_after>/**
 * Reveal module.
 * @module foundation.reveal
 * @requires foundation.util.keyboard
 * @requires foundation.util.size-and-collision
 * @requires foundation.util.triggers
 * @requires foundation.util.mediaQuery
 */
!function(Foundation, $) {
  'use strict';

  /**
   * Creates a new instance of Reveal.
   * @class
   * @fires Reveal#init
   * @param {jQuery} element - jQuery object to use for the modal.
   * @param {Object} options - optional parameters.
   */

  function Reveal(element, options) {
    this.$element = element;
    this.options = $.extend({}, Reveal.defaults, this.$element.data(), options);
    this._init();

    Foundation.registerPlugin(this);
    Foundation.Keyboard.register('Reveal', {
      'ENTER': 'open',
      'SPACE': 'open',
      'ESCAPE': 'close',
      'TAB': 'tab_forward',
      'SHIFT_TAB': 'tab_backward'
    });
    // /**
    //  * Fires when the plugin has been successfuly initialized.
    //  * @event Reveal#init
    //  */
    // this.$element.trigger('init.zf.reveal');
  }

  Reveal.defaults = {
    animationIn: '',
    animationOut: '',
    showDelay: 0,
    hideDelay: 0,
    closeOnClick: true,
    closeOnEsc: true,
    multipleOpened: false,
    vOffset: 100,
    hOffset: 0,
    fullScreen: false,
    btmOffsetPct: 10,
    overlay: true
  };

  /**
   * Initializes the modal by adding the overlay and close buttons, (if selected).
   * @private
   */
  Reveal.prototype._init = function(){
    this.id = this.$element.attr('id');
    this.isActive = false;

    this.$anchor = $('[data-open="' + this.id + '"]').length ? $('[data-open="' + this.id + '"]') : $('[data-toggle="' + this.id + '"]');

    if(this.$anchor.length){
      var anchorId = this.$anchor[0].id || Foundation.GetYoDigits(6, 'reveal');

      this.$anchor.attr({
        'aria-controls': this.id,
        'id': anchorId,
        'aria-haspopup': true,
        'tabindex': 0
      });
      this.$element.attr({'aria-labelledby': anchorId});
    }

    // this.options.fullScreen = this.$element.hasClass('full');
    if(this.options.fullScreen || this.$element.hasClass('full')){
      this.options.fullScreen = true;
      this.options.overlay = false;
    }
    if(this.options.overlay){
      this.$overlay = this._makeOverlay(this.id);
    }

    this.$element.attr({
        'role': 'dialog',
        'aria-hidden': true,
        'data-yeti-box': this.id,
        'data-resize': this.id
    });

    this._events();
  };

  /**
   * Creates an overlay div to display behind the modal.
   * @private
   */
  Reveal.prototype._makeOverlay = function(id){
    var $overlay = $('

')
                    .addClass('reveal-overlay')
                    .attr({'tabindex': -1, 'aria-hidden': true})
                    .appendTo('body');
    if(this.options.closeOnClick){
      $overlay.attr({
        'data-close': id
      });
    }
    return $overlay;
  };

  /**
   * Adds event handlers for the modal.
   * @private
   */
  Reveal.prototype._events = function(){
    var _this = this;

    this.$element.on({
      'open.zf.trigger': this._open.bind(this),
      'close.zf.trigger': this._close.bind(this),
      'toggle.zf.trigger': this.toggle.bind(this),
      'resizeme.zf.trigger': function(){
        if(_this.$element.is(':visible')){
          _this._setPosition(function(){});
        }
      }
    });

    if(this.$anchor.length){
      this.$anchor.on('keydown.zf.reveal', function(e){
        if(e.which === 13 || e.which === 32){
          e.stopPropagation();
          e.preventDefault();
          _this._open();
        }
      });
    }

    if(this.options.closeOnClick && this.options.overlay){
      this.$overlay.off('.zf.reveal').on('click.zf.reveal', this._close.bind(this));
    }
  };
  /**
   * Sets the position of the modal before opening
   * @param {Function} cb - a callback function to execute when positioning is complete.
   * @private
   */
  Reveal.prototype._setPosition = function(cb){
    var eleDims = Foundation.GetDimensions(this.$element);
    var elePos = this.options.fullScreen ? 'reveal full' : (eleDims.height >= (0.5 * eleDims.windowDims.height)) ? 'reveal' : 'center';

    if(elePos === 'reveal full'){
      console.log('full');
      //set to full height/width
      this.$element
          .offset(Foundation.GetOffsets(this.$element, null, elePos, this.options.vOffset))
          .css({
            'height': eleDims.windowDims.height,
            'width': eleDims.windowDims.width
          });
    }else if(!Foundation.MediaQuery.atLeast('medium') || !Foundation.ImNotTouchingYou(this.$element, null, true, false)){
      //if smaller than medium, resize to 100% width minus any custom L/R margin
      this.$element
          .css({
            'width': eleDims.windowDims.width - (this.options.hOffset * 2)
          })
          .offset(Foundation.GetOffsets(this.$element, null, 'center', this.options.vOffset, this.options.hOffset));
      //flag a boolean so we can reset the size after the element is closed.
      this.changedSize = true;
    }else{
      this.$element
          .css({
            'max-height': eleDims.windowDims.height - (this.options.vOffset * (this.options.btmOffsetPct / 100 + 1)),
            'width': ''
          })
          .offset(Foundation.GetOffsets(this.$element, null, elePos, this.options.vOffset));
          //the max height based on a percentage of vertical offset plus vertical offset
    }

    cb();
  };

  /**
   * Opens the modal controlled by `this.$anchor`, and closes all others by default.
   * @fires Reveal#closeAll
   * @fires Reveal#open
   */
  Reveal.prototype._open = function(){
    var _this = this;
    this.isActive = true;
    //make element invisible, but remove display: none so we can get size and positioning
    this.$element
        .css({'visibility': 'hidden'})
        .show()
        .scrollTop(0);

    this._setPosition(function(){
      _this.$element.hide()
                   .css({'visibility': ''});
      if(!_this.options.multipleOpened){
        /**
         * Fires immediately before the modal opens.
         * Closes any other modals that are currently open
         * @event Reveal#closeAll
         */
        _this.$element.trigger('closeme.zf.reveal', _this.id);
      }
      if(_this.options.animationIn){
        if(_this.options.overlay){
          Foundation.Motion.animateIn(_this.$overlay, 'fade-in', function(){
            Foundation.Motion.animateIn(_this.$element, _this.options.animationIn, function(){
            });
          });
        }else{
          Foundation.Motion.animateIn(_this.$element, _this.options.animationIn, function(){
          });
        }
      }else{
        if(_this.options.overlay){
          _this.$overlay.show(0, function(){
            _this.$element.show(_this.options.showDelay, function(){
            });
          });
        }else{
          _this.$element.show(_this.options.showDelay, function(){
          });
        }
      }
    });

    // handle accessibility
    this.$element.attr({'aria-hidden': false}).attr('tabindex', -1).focus()
    /**
     * Fires when the modal has successfully opened.
     * @event Reveal#open
     */
                 .trigger('open.zf.reveal');

    $('body').addClass('is-reveal-open')
             .attr({'aria-hidden': (this.options.overlay || this.options.fullScreen) ? true : false});
    setTimeout(function(){
      _this._extraHandlers();
      // Foundation.reflow();
    }, 0);
  };

  /**
   * Adds extra event handlers for the body and window if necessary.
   * @private
   */
  Reveal.prototype._extraHandlers = function(){
    var _this = this;
    var visibleFocusableElements = this.$element.find('a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, *[tabindex], *[contenteditable]').filter(function() {
      if (!$(this).is(':visible') || $(this).attr('tabindex') < 0){ return false; }//only have visible elements and those that have a tabindex greater or equal 0
      return true;
    });

    if(!this.options.overlay && this.options.closeOnClick && !this.options.fullScreen){
      $('body').on('click.zf.reveal', function(e){
        // if()
          _this._close();
          console.log('Closing here');
      });
    }
    if(this.options.closeOnEsc){
      $(window).on('keydown.zf.reveal', function(e){
        if (visibleFocusableElements.length === 0) { // no focusable elements inside the modal at all, prevent tabbing in general
          e.preventDefault();
        }
        Foundation.Keyboard.handleKey(e, _this, {
          close: function() {
            if (this.options.closeOnEsc) {
              this._close();
            }
          }
        });
      });
    }

    // lock focus within modal while tabbing
    this.$element.on('keydown.zf.reveal', function(e) {
      var $target = $(this);
      // handle keyboard event with keyboard util
      Foundation.Keyboard.handleKey(e, _this, {
        tab_forward: function() {
          if (this.$element.find(':focus').is(visibleFocusableElements.eq(-1))) { // left modal downwards, setting focus to first element
            visibleFocusableElements.eq(0).focus();
            e.preventDefault();
          }
        },
        tab_backward: function() {
          if (this.$element.find(':focus').is(visibleFocusableElements.eq(0)) || this.$element.is(':focus')) { // left modal upwards, setting focus to last element
            visibleFocusableElements.eq(-1).focus();
            e.preventDefault();
          }
        },
        open: function() {
          if ($target.is(visibleFocusableElements)) { // dont't trigger if acual element has focus (i.e. inputs, links, ...)
            this._open();
          }
        },
        close: function() {
          if (this.options.closeOnEsc) {
            this._close();
          }
        }
      });
      if (visibleFocusableElements.length === 0) { // no focusable elements inside the modal at all, prevent tabbing in general
        e.preventDefault();
      }
    });

  };

  /**
   * Closes the modal
   * @fires Reveal#closed
   */
  Reveal.prototype._close = function(){
    if(!this.isActive || !this.$element.is(':visible')){
      return false;
    }
    var _this = this;

    if(this.options.animationOut){
      Foundation.Motion.animateOut(this.$element, this.options.animationOut, function(){
        if(_this.options.overlay){
          Foundation.Motion.animateOut(_this.$overlay, 'fade-out', function(){
          });
        }
      });
    }else{
      this.$element.hide(_this.options.hideDelay, function(){
        if(_this.options.overlay){
          _this.$overlay.hide(0, function(){
          });
        }
      });
    }
    //conditionals to remove extra event listeners added on open
    if(this.options.closeOnEsc){
      $(window).off('keydown.zf.reveal');
    }
    if(!this.options.overlay && this.options.closeOnClick){
      $('body').off('click.zf.reveal');
    }
    this.$element.off('keydown.zf.reveal');

    //if the modal changed size, reset it
    if(this.changedSize){
      this.$element.css({
        'height': '',
        'width': ''
      });
    }

    $('body').removeClass('is-reveal-open').attr({'aria-hidden': false, 'tabindex': ''});

    this.isActive = false;
    this.$element.attr({'aria-hidden': true})
    /**
     * Fires when the modal is done closing.
     * @event Reveal#closed
     */
                 .trigger('closed.zf.reveal');
  };

  Reveal.prototype.toggle = function(){
    if(this.isActive){
      this._close();
    }else{
      this._open();
    }
  };

  /**
   * Destroys an instance of a modal.
   * @fires Reveal#destroyed
   */
  Reveal.prototype.destroy = function() {
    if(this.options.overlay){
      this.$overlay.hide().off();
    }
    this.$element.hide();
    this.$anchor.off();

    Foundation.unregisterPlugin(this);

    /**
     * Fires when the plugin has been destroyed.
     * @event Reveal#destroyed
     */
    // this.$element.trigger('destroyed.zf.reveal');
  };

  Foundation.plugin(Reveal);

  // Exports for AMD/Browserify
  if (typeof module !== 'undefined' && typeof module.exports !== 'undefined')
    module.exports = Reveal;
  if (typeof define === 'function')
    define(['foundation'], function() {
      return Reveal;
    });

}(Foundation, jQuery);
<|endoftext|>