<commit_before>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();
			}
		}]);
		this.type = "PlayerEntity";
		this.health = 20;
		//changes the characters Y position
		this.body.setVelocity(5, 20);
		this.facing = "right";
		this.now = new Date().getTime();
		this.lastHit = this.now;
		//sets hit delay
		this.lastAttack = new Date().getTime();

		this.renderable.addAnimation("idle", [78]);
		this.renderable.addAnimation("walk", [143, 144, 145, 146, 147, 148, 149, 150, 151], 80);
		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80)

		this.renderable.setCurrentAnimation("idle");
	},

	update: function(delta) {
		//keeps timer up to date
		this.now = new Date().getTime();
		if(me.input.isKeyPressed("right")) {
//adds to the position of my x by the velocity defined above
//in setVelocity and by multiplying 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);

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

			this.body.vel.x -=this.body.accel.x * me.time.tick;
			this.facing = "left";
			this.flipX(false);
		}
		else
		{
			this.body.vel.x = 0;
		}

		if(me.input.isKeyPressed("jump") && !this.body.jumping && !this.body.falling){
			this.jumping = true;
			this.body.vel.y -= this.body.accel.y * me.timer.tick;
		}

		if(me.input.isKeyPressed("attack")) {
			if(!this.renderable.isCurrentAnimation("attack")) {
				console.log(!this.renderable.isCurrentAnimation("attack"))
				//sets the current animation to the attack and once that is over
				//goes back to the idle animation
				this.renderable.setCurrentAnimation("attack", "idle");
				//makes it so that the nnect time we star this sequence we begin
				//from the first animation, not wherevere we keft off when we
				//switched to a another animation
				this.renderable.setAnimationFrame();
			}
		}

		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")){
			this.renderable.setCurrentAnimation("idle");
		}

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

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

	},
	loseHealth: function(Damage) {
		this.health = this.health - damage;
		consol.log(this.health);
	},

	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 " + ydif);

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

			else if (xdif>-35 && 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
			}
													//checks if it has been 400 milliseconds
													//the player can attack again
			if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= 1000){
				console.log("tower Hit");
				//once it is done, it is gonna update the last hit variable so
				//player can attack again
				this.lastHit = this.now;
				response.b.losehealth();
				//function that makes the tower lose health
				//if we are attacking or in contact with the base the tower will
				//lose health
			}

		}
		// this is going to determine what happens when we hit the enemy entity
	}
});
//setting the properties to the player's tower
game.PlayerBaseEntity = me.Entity.extend({
	init:function(x, y, settings) {
		this._super(me.Entity, 'init', [x, y, {
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function(){
				return (new me.Rect(0, 0, 100)).toPolygon();
			}
		}]);
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		this.body.onCollision = this.onCollision.bind(this);
		this.type = "PlayerBase";
		//we are setting animation for tower
		this.renderable.addAnimation("idle", [0]);
		this.renderable.addAnimation("borken", [1]);
		this.renderable.setCurrentAnimation("idle");

	},
	//basically if the tower's health is less then 0 then, its dead
	update:function(){
		if(this.health<=0) {
			this.broken = true;
			this.renderable.setCurrentAnimation("broken");
		}
		this.body.update(delta);

		this._super(me.Entity, "update", [delta]);
		return true
	},
	// makes our base lose a little bit of
	//health everytime it is damaged
	loseHealth: function(damage) {
		this.health = this.health - damage;
	},

	onCollision: function(delta){

	}

});
//just copied and pasted the other but changed a couple
//thingsto make the enemy tower
game.EnemyBaseEntity = me.Entity.extend({
	init:function(x, y, settings) {
		this._super(me.Entity, 'init', [x, y, {
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function(){
				return (new me.Rect(0, 0, 100, 70)).toPolygon();
			}
		}]);
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "EnemybaseEntity";
		//we are setting enemy tower animation
		this.renderable.addAnimation("idle", [0]);
		this.renderable.addAnimation("borken", [1]);
		this.renderable.setCurrentAnimation("idle");

	},

	update:function(){
		if(this.health<=0) {
			this.broken = true;
			this.renderable.setCurrentAnimation("broken");
		}
		this.body.update(delta);
	},

	onCollision: function(){

	},

	loseHealth: function() {
		this.health--;
	}

});
//creating a new class
game.EnemyCreep = me.Entity.extend({
	init: function(x, y, settings) {
		this._super(me.Entity, 'init', [x, y, {
			image:"creep1",
			width: 32,
			height: 64,
			spritewidth: "32",
			spriteheight: "64",
			getShape: function() {
				return (new me.Rect(0, 0, 32, 64)).toPolygon();
			}
		}]);
		this.health = 10;
		this.alwaysUpdate = true;
		//this.attacking lets us know if the enemy is currently attacking
		this.attacking = false;
		//keeps trackof when our creep last attacks anything
		this.lastAttacking = new Date().getTime();
		//keep track of the last time our creep hit anything
		this.lastHit = new Date().getTime();
		this.now = new Date().getTime();
		this.body.setVelocity(3, 20);

		this.type = "EnemyCreep";

		this.renderable.addAnimation("walk", [3, 4, 5], 80);
		this.renderable.setCurrentAnimation("walk");
	},

	update: function(delta){
		this.now = Date().getTime();

		this.body.vel.x -= this.accel.x * me.timer.tick

		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==='PlayerBase') {
			this.attacking=true;
			//this.lastAttacking=this.now;
			this.body.vel.x = 0;
			//keeps moving the creep to the right to maintain its position
			this.pos.x = this.pos.x + 1;
			//checks that is has been at lelast 1 second since the 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 it a
				//damage of1
				response.b.loseHealth(1);
			}
			//else if so that our enemy doesnt hit multiple stuff at once
		}else if (response.b.type==='PlayerEntity') {
			var cdif = this.pos.x - respons.b.pos.x;

			this.attacking=true;
			//this.lastAttacking=this.now;

			if(xdif>0) {
				//keeps moving the creep to the right to maintain its position
				this.pos.x = this.pos.x + 1;
				this.body.vel.x = 0;
			}
			//checks that is has been at lelast 1 second since the creep hit something
			if((this.now-this.lastHit >= 1000) && xdif>0){
				//updates the lasthit timer
				this.lastHit = this.now;
				//makes the player base call its losehealth function and passes it a
				//damage of 1
				response.b.loseHealth(1);
			}
		}
	}

});

game.GameManager = Object.extend({
	init: function(x, y, settings) {
		this.now = new Date().getTime();
		this.lastCreep = new Date().getTime();

		this.alwaysUpdate = true;
	},

	update: function(){
		this.now = new Date().getTime();
		//function that checks
		//to make sure that we have a multiple of 10
		if(Math.round(this.now/1000)%10 ===0 && (this.now - this.lasCreep >= 1000)){
			this.lastCreep = this.now;
			var creepe = me.pool.pull("EnemyCreep", 1000, 0, {})
			me.game.world.addChild(creepe, 5);
		}

		return true;
	}

});
<commit_msg>coded and commented video 23: Player can Kill Creeps<commit_after>game.PlayerEntity = me.Entity.extend ({
	// this is a class
	init: function(x, y, settings) {
		// 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
			}
		}]);
		this.type = "PlayerEntity";
		this.health = 20;
		this.body.setVelocity(7, 20);
		// this also changes the y velocity of the character
		// this is the movement speed of the character
		this.facing = "right";
		// keeps track of which direction the character is going
		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
		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);
		// this says wherever the player goes the screen will follow him

		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.setCurrentAnimation("idle");
		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
		if(me.input.isKeyPressed("right")) {
			// 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

		}
		else if(me.input.isKeyPressed("left")) {
			// 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

		}
		else {
			this.body.vel.x = 0;
		}
		if (me.input.isKeyPressed('jump') && !this.body.jumping && !this.body.falling) {
     	 // 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;
    }
		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;
	},

	looseHealth: function(damage){
		this.health = this.health - damage;
		console.log(this.health);
	}

	collideHandler: function(response) {
		if(response.b.type === 'EnemyBase'){
			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 >= 1000) {
				this.lastHit = this.now;
				response.b.loseHealth();
				// if we are attacking and hitting the castle it looses health
			}
		}else if(response.b.type==='enemyCreep'){

			var xdif = this.pos.x - response.b.pos.x;
			var ydif = this.pos.y - response.b.pos.y;

			//this line of code keeps our player from walking
			//right through our enemy
			if (xdif>0){
				this.pos.x = this.pos.x + 1;
				//this keeps track of where the player
				//is facing
				if(this.facing==="left"){
					this.body.vel.x = 0;
				}
			}else{
				this.pos.x = this.pos.x - 1;
				if(this.facing==="right"){
					this.body.vel.x = 0;
				}
			}
			if(his.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= 1000
				&& (Math.abs(ydif) <=40) &&
				//if the player is to the right of the creep and it is
				//facing left then i have the right away to attack
				(((xdif>0 ) && this.facing==="left") || ((xdif<0) && this.facing==="right"))
				){
				this.lastHit = this.now;
				response.b.loseHealth(1);
			}
		}
		// this is going to determine what happens when we hit the enemy entity
	}
});

game.PlayerBaseEntity = me.Entity.extend ({
	init: function(x, y, settings) {
		this._super(me.Entity, 'init', [x, y, {
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",

			getShape: function() {
				return (new me.Rect(0, 0, 100, 70)).toPolygon();
				// this shows the height of the bases
			}
}]);
		this.broken = false;
		// this is saying that the tower has not yet been touched/attacked
		this.health = 10;
		// starting energy for tower
		this.alwaysUpdate = true;
		// this.attacking lets us know if the enemy us currently attacking
		this.attacking=false;
		// Keeps track of when our creeps last attacked anything
		this.lastAttacking = new Date() . getTime();
		// Keep track of the last time our creep hit anything
		this.lastHit = new Date() . getTime();
		// updates the screen whether or not we are not looking at it
		this.body.onCollision = this.onCollision.bind(this);
		// if somebody runs into the tower it will be able to collide with it

		this.type = "PlayerBase";
		// this is a type you can use to check to see what you are running into
		this.renderable.addAnimation("idle", [0]);
		this.renderable.addAnimation("broken", [1]);
		this.renderable.setCurrentAnimation("idle");
		// renderable is a class built in melon js that we can play with the animation with

	},

	update: function(delta) {
		if( this.health <= 0) {
			this.broken =  true;
			// this means that the character is dead
			this.renderable.setCurrentAnimation("broken");
	}
		this.body.update(delta);
		// updates the code

		this._super(me.Entity, "update", [delta]);
		// telling the superclass to update
		return true;
	},
		onCollision: function() {

		}

});
game.EnemyBaseEntity = me.Entity.extend ({
	init: function(x, y, settings) {
		this._super(me.Entity, "init", [x, y, {
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",

			getShape: function() {
				return (new me.Rect(0, 0, 100, 70)).toPolygon();
				// this shows the hight of the bases
			}
}]);
		this.broken = false;
		// this is saying that the tower has not yet been
		this.health = 10;
		// starting energy for tower
		this.alwaysUpdate = true;
		// updates the screen whether or not we are not looking at it
		this.body.onCollision = this.onCollision.bind(this);
		// if somebody runs into the tower it will be able to collide with it

		this.type = "EnemyBase";
		// this is a type you can use to check to see what you are running into
		this.renderable.addAnimation("idle", [0]);
		this.renderable.addAnimation("broken", [1]);
		this.renderable.setCurrentAnimation("idle");
		// renderable is a class built in melon js that we can play with the animation with

	},

	update: function(delta) {
		if( this.health <= 0) {
			this.broken =  true;
			// this means that the character is dead
			this.renderable.setCurrentAnimation("broken");
	}
		this.body.update(delta);
		// updates the code

		this._super(me.Entity, "update", [delta]);
		// telling the super class to update
		return true;
	},
		onCollision: function() {

		}, +
		loseHealth: function() {
			this.health--;
		}

});
game.EnemyCreep = me.Entity.extend({
	init: function(x, y, settings) {
		this._super(me.Entity, "init", [x, y, {
			image: "creep1",
			width: 32,
			height: 64,
			spritewidth: "32",
			spriteheight: "64",

			getShape: function() {
				return (new me.Rect(0, 0, 32, 64)).toPolygon();
				// this shows the hight of the base
			}
		}]);

			this.health = 10;
			this.alwaysUpdate = true;
			// A timer for when attacking
			this.now = new Date() .getTime();

			this.type = "EnemyCreep";

			this.renderable.addAnimation("walk", [3, 4, 5], 80);
			this.renderable.setCurrentAnimation("walk");
	},

	loseHealth: function(damage){
		this.health = this.health - damage;
	},

			update: function(delta) {
				console.log(this.health);
				if(this.health <= 0) {
					me.game.world.removeChild(this);
				}

				// It will refresh every single time
				this.now = new Date() .getTime();

				this.body.vel.x -= this.body.accel.x * me.timer.tick;
				// cahnging the drection of the creep

				// Checks for collisions with my player, if there are, it'll passit to our CollideHandler function
				me.collision.check(this, true, this.collideHandler.bind(this), true);
				this.body.update(delta);

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

			// Make our base loose a little bit of health everytime it's attacked
			loseHealth: funtcion(damage) {
				this.health = this.health - damage;
			},

			collideHandler: function(response){
				if (response.b.type==='PlayerBase') {
					this.attacking=true;
					this.lastAttacking=this.now;
					this.body.vel.x = 0;

					if(xdif>0){
						console.log(xdif)
					// Keeps 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 at least 1 second since the creep hit the base
					if ((this.now-this.lastHit >= 1000)) {
						this.lastHit = this.now;
						// Makes the player base call its looseHealth function and passes it a damage of 1
						response.b.loseHealth(1);
					}
			}else if (response.b.type==='PlayerEntity'){
					var xdif = this.pos.x - response.b.pos.x;
				this.attacking=true;
					this.lastAttacking=this.now;
					this.pos.x = this.pos.x + 1;
					// Checks that it has been at least 1 second since the creep hit something
					if ((this.now-this.lastHit >= 1000)) {
						this.lastHit = this.now;
						// Makes the player base call its looseHealth function and passes it a damage of 1
						response.b.loseHealth(1);
					}
			}
		}

});
game.GameManager = Object.extend({
	// this is an object but we still need and init function
	init: function(x, y, settings) {
		this.now = new Date().getTime();
		this.lastCreep = new Date().getTime();
		this.alwaysUpdate = true;
	},
	update: function() {
		 this.now = new Date().getTime();

		 if(Math.round(this.now/1000)%10 ===0 && (this.now - this.lastCreep >= 1000) && xdif>0 ) {
		 	// checking to see if we have multiples of ten
		 	// this.now - .. makes sure the spawn isnt repeating
		 	this.lastCreep = this.now;
		 	var creepe = me.pool.pull("EnemyCreep", 1000, 0, {});
		 	me.game.world.addChild(creepe, 5);

		 };
		 return true;
	}

});<|endoftext|>


<commit_before>game.PlayerEntity = me.Entity.extend({
	init: function(x, y, settings) {
		this.setSuper();
		this.setPlayerTimers();
		this.setAttributes();
		this.type = "PlayerEntity";
		this.setFlags();
		/*velocity represents current position*/

		/*following the player on the screen*/
		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

		this.addAnimation();
		/*when the action is done, the sprite tat is equal to the number is put into play*/
		this.renderable.setCurrentAnimation("idle");
	},
	/**/
	setSuper: function(){
		this._super(me.Entity, 'init', [x, y, {
			image:"player",
			/*telling the screen how much space to preserve*/
			width: 64,
			height: 64,
			/*spritewidth and height are passing us information. telling us the size of image*/
			spritewidth: "64",
			spriteheight: "64",
			getShape: function(){
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
			}
		}]);
	},

	setPlayerTimers: function(){
		this.now = new Date().getTime();
		this.lastHit = this.now;
		this.lastAttack = new Date().getTime();
	},

	setAttributes: function(){
		this.health = game.data.playerHealth;
		this.body.setVelocity(game.data.playerMoveSpeed, 20);
		this.attack = game.data.playerAttack;
	},

	setFlags: function(){
		/*keeps track of which direction your character is going*/
		this.facing = "right";
		this.dead = false;
		this.attacking = false;
	},

	addAnimation: function(){
		this.renderable.addAnimation("idle", [78]);
		/*the image number are olny used when the action "walk" is played*/
		this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
		/*this is the current animatio when no keys are pressed. the sprite is idle and standing still.*/
		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);

	},

	update: function(delta){
		this.now = new Date().getTime();

		this.dead = checkIfDead();

		this.checkKeyPressedAndMove();

		this.setAnimation();

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

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

	checkIfDead: function(){
		if (this.health <= 0){
			return true;
		}
		return false;
	},

	checkKeyPressedAndMove: function(){
		if(me.input.isKeyPressed("right")){
			this.moveRight();
		}else if(me.input.isKeyPressed("left")){
			  this.moveLeft();
/*adding the jump function*/
		}else if (me.input.isKeyPressed('jump')) {
		if (!this.body.jumping && !this.body.falling) {
		this.jump();
		}
		}else{
		this.body.vel.x = 0;
		}

		this.attacking = me.input.isKeyPressed("attack");

	},

	moveRight: function(){
		/*adds to the position of my x by the velocity defined above in
			setVelocity() and multiplying it by me.time.tick.
			me.time.tick makes the movement look smooth*/
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			this.facing = "right";
			this.flipX(true);
	},

	moveLeft: function(){
		this.body.vel.x -=this.body.accel.x * me.timer.tick;
		this.facing = "left";
		this.flipX(false);
	},

jump: function(){
	/*set current vel to the maximim defined value
	gravity will do the rest*/
	this.body.vel.y = -this.body.maxVel.y * me.timer.tick;
	/*set the jumping flag*/
	this.body.jumping = true;
},

setAnimation: function(){
	if(this.attacking){
			if(!this.renderable.isCurrentAnimation("attack")){
				/*console.log(!this.renderable.isCurrentAnimation("attack"));*/
				/*sets the currents 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 whereever we left off when we switched to another animation*/
				this.renderable.setAnimationFrame();
			}
		}

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

	loseHealth: function(damage){
		this.health = this.health - damage;
		console.log(this.health);
	},
/*setting what is going to happen tothe player when it gets to the enemy base and also setting our own methods*/
	collideHandler: function(response){
		if(response.b.type==='EnemyBaseEntity'){
			this.collideWithEnemyBase(response);
		}
		else if(response.b.type==='EnemyCreep'){
			this.collideWithEnemyCreep(response)''
		}
	},

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

/*what is going to happen when we are cgetting near the enemy base from the left*/
			if(ydif<-40 && xdif< 70 && xdif>-35){
				this.body.vel.x = 0;
				this.pos.x = this.pos.x -1;

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

			if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer){
				console.log("tower Hit");
				this.lastHit = this.now;
				response.b.loseHealth(game.data.playerAttack);
			}
	},

	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)){

		},

	},

	stopMovement: function(xdif){
					/*keeping the enemy from going through the base*/
		if (xdif>0){
			/*pushing the player to the right if the x dif is greater than zero*/
				if(this.facing==="left"){
					this.body.vel.x - 0;
				}
				/*keeping track of which the player is facing*/
			}
			else
			{
				/*we can not do damage to the creep*/
				/*cant walk through the creep no matter what direction we are coming from*/
				if(this.facing==="right"){
					this.body.vel.x = 0;
				}
			}
	},

	checkAttack: function(xdif, ydif){
		if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttack
				/*making sure that we can only kill the creep if the player is facing it*/
				&& (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 pur attack, execute the code in our if statement */

				 return true;
			}
	}
});<commit_msg>video 33 fixed indentation<commit_after>game.PlayerEntity = me.Entity.extend({
	init: function(x, y, settings) {
		this.setSuper();
		this.setPlayerTimers();
		this.setAttributes();
		this.type = "PlayerEntity";
		this.setFlags();
		/*velocity represents current position*/

		/*following the player on the screen*/
		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

		this.addAnimation();
		/*when the action is done, the sprite tat is equal to the number is put into play*/
		this.renderable.setCurrentAnimation("idle");
	},
	/**/
	setSuper: function(){
		this._super(me.Entity, 'init', [x, y, {
			image:"player",
			/*telling the screen how much space to preserve*/
			width: 64,
			height: 64,
			/*spritewidth and height are passing us information. telling us the size of image*/
			spritewidth: "64",
			spriteheight: "64",
			getShape: function(){
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
			}
		}]);
	},

	setPlayerTimers: function(){
		this.now = new Date().getTime();
		this.lastHit = this.now;
		this.lastAttack = new Date().getTime();
	},

	setAttributes: function(){
		this.health = game.data.playerHealth;
		this.body.setVelocity(game.data.playerMoveSpeed, 20);
		this.attack = game.data.playerAttack;
	},

	setFlags: function(){
		/*keeps track of which direction your character is going*/
		this.facing = "right";
		this.dead = false;
		this.attacking = false;
	},

	addAnimation: function(){
		this.renderable.addAnimation("idle", [78]);
		/*the image number are olny used when the action "walk" is played*/
		this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
		/*this is the current animatio when no keys are pressed. the sprite is idle and standing still.*/
		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);

	},

	update: function(delta){
		this.now = new Date().getTime();

		this.dead = checkIfDead();

		this.checkKeyPressedAndMove();

		this.setAnimation();

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

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

	checkIfDead: function(){
		if (this.health <= 0){
			return true;
		}
		return false;
	},

	checkKeyPressedAndMove: function(){
		if(me.input.isKeyPressed("right")){
			this.moveRight();
		}else if(me.input.isKeyPressed("left")){
			  this.moveLeft();
/*adding the jump function*/
		}else if (me.input.isKeyPressed('jump')) {
		if (!this.body.jumping && !this.body.falling) {
		this.jump();
		}
		}else{
		this.body.vel.x = 0;
		}

		this.attacking = me.input.isKeyPressed("attack");

	},

	moveRight: function(){
		/*adds to the position of my x by the velocity defined above in
			setVelocity() and multiplying it by me.time.tick.
			me.time.tick makes the movement look smooth*/
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			this.facing = "right";
			this.flipX(true);
	},

	moveLeft: function(){
		this.body.vel.x -=this.body.accel.x * me.timer.tick;
		this.facing = "left";
		this.flipX(false);
	},

jump: function(){
	/*set current vel to the maximim defined value
	gravity will do the rest*/
	this.body.vel.y = -this.body.maxVel.y * me.timer.tick;
	/*set the jumping flag*/
	this.body.jumping = true;
},

setAnimation: function(){
	if(this.attacking){
			if(!this.renderable.isCurrentAnimation("attack")){
				/*console.log(!this.renderable.isCurrentAnimation("attack"));*/
				/*sets the currents 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 whereever we left off when we switched to another animation*/
				this.renderable.setAnimationFrame();
			}
		}

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

	loseHealth: function(damage){
		this.health = this.health - damage;
		console.log(this.health);
	},
/*setting what is going to happen tothe player when it gets to the enemy base and also setting our own methods*/
	collideHandler: function(response){
		if(response.b.type==='EnemyBaseEntity'){
			this.collideWithEnemyBase(response);
		}
		else if(response.b.type==='EnemyCreep'){
			this.collideWithEnemyCreep(response)''
		}
	},

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

/*what is going to happen when we are cgetting near the enemy base from the left*/
			if(ydif<-40 && xdif< 70 && xdif>-35){
				this.body.vel.x = 0;
				this.pos.x = this.pos.x -1;

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

			if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer){
				console.log("tower Hit");
				this.lastHit = this.now;
				response.b.loseHealth(game.data.playerAttack);
			}
	},

	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){
					/*keeping the enemy from going through the base*/
		if (xdif>0){
			/*pushing the player to the right if the x dif is greater than zero*/
				if(this.facing==="left"){
					this.body.vel.x - 0;
				}
				/*keeping track of which the player is facing*/
			}
			else
			{
				/*we can not do damage to the creep*/
				/*cant walk through the creep no matter what direction we are coming from*/
				if(this.facing==="right"){
					this.body.vel.x = 0;
				}
			}
	},

	checkAttack: function(xdif, ydif){
		if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttack
				/*making sure that we can only kill the creep if the player is facing it*/
				&& (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 pur attack, execute the code in our if statement */

				 return true;
			}
			return false;
	}

	hitCreep: function(response){
		if(response.b.health <= game.data.playerAttack){
				game.data.gold +1;
				console.log("Current gold" + game.data.gold);
			}

			response.b.loseHealth(game.data.playerAttack);
	}
});<|endoftext|>


<commit_before>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();
                }
            }]);

        this.body.setVelocity(5, 20);
        me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

        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) {
        if (me.input.isKeyPressed("right")) {
            //adds to the position of my x by the velocity defined above
            //setVelocity() and multipyling 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.flipX(true);

        }else if(me.input.isKeyPressed("left")){
            this.facing = "left";
            this.body.vel.x -= this.body.accel.x * me.timer.tick;
            this.flipX(false);
        }else {
            this.body.vel.x = 0;
        }
        if (me.input.isKeyPressed("jump")&& !this.jumping && !this.falling){
            this.jumping = true;
            this.body.vel.y -= this.body.accel.y * me.timer.tick;
        }
        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 rhe first animation, not wherever we left off
                this.renderable.setAnimationFrame();
            }
        }else if (this.body.vel.x !== 0) {
            if (!this.renderable.isCurrentAnimation("walk")) {
                this.renderable.setCurrentAnimation("walk");
            }
        } else {
            this.renderable.setCurrentAnimation("idle");
        }

        this.body.update(delta);

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

game.PlayerBaseEntity = me.Entity.extend({
    init : function(x, y, settings){
        this._super(me.Entity, 'init', [x, y, {
                image: "tower",
                width: 100,
                height: 100,
                spritewidth: "100",
                spriteheight: "100",
                getShape: function(){
                    return (new me.Rect(0, 0, 100, 70)).toPolygon();
                }
        }]);
        this.broken = false;
        this.health = 10;
        this.alwaysUpdate = true;
        this.body.onCollision = this.onCollision.bind(this);

        this.type = "PlayeBaseEntity";

        this.renderable.addAnimation("idle", [0]);
        this.renderable.addAnimation("broken", [1]);
        this.renderable.setCurrentAnimation("idle");

    },

    update:function(delta){
        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, {
                image: "tower",
                width: 100,
                height: 100,
                spritewidth: "100",
                spriteheight: "100",
                getShape: function(){
                    return (new me.Rect(0, 0, 100, 70)).toPolygon();
                }
        }]);
        this.broken = false;
        this.health = 10;
        this.alwaysUpdate = true;
        this.body.onCollision = this.onCollision.bind(this);

        this.type = "EnemyEntityBase";

        this.renderable.addAnimation("idle", [0]);
        this.renderable.addAnimation("broken", [1]);
        this.renderable.setCurrentAnimation("idle");

    },

    update:function(delta){
        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>Spring Break<commit_after>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();
                }
            }]);

        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);

        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) {
        if (me.input.isKeyPressed("right")) {
            //adds to the position of my x by the velocity defined above
            //setVelocity() and multipyling 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);
        }else if(me.input.isKeyPressed("left")){
            this.facing = "left";
            this.body.vel.x -= this.body.accel.x * me.timer.tick;
            this.flipX(false);
        }else {
            this.body.vel.x = 0;
        }
        if (me.input.isKeyPressed("jump")&& !this.jumping && !this.falling){
            this.jumping = true;
            this.body.vel.y -= this.body.accel.y * me.timer.tick;
        }
        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 rhe first animation, not wherever we left off
                this.renderable.setAnimationFrame();
            }
        }else if (this.body.vel.x !== 0) {
            if (!this.renderable.isCurrentAnimation("walk")) {
                this.renderable.setCurrentAnimation("walk");
            }
        } else {
            this.renderable.setCurrentAnimation("idle");
        }

        me.collisions.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;

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

            else 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;
            }
        }
    }
});

game.PlayerBaseEntity = me.Entity.extend({
    init : function(x, y, settings){
        this._super(me.Entity, 'init', [x, y, {
                image: "tower",
                width: 100,
                height: 100,
                spritewidth: "100",
                spriteheight: "100",
                getShape: function(){
                    return (new me.Rect(0, 0, 100, 70)).toPolygon();
                }
        }]);
        this.broken = false;
        this.health = 10;
        this.alwaysUpdate = true;
        this.body.onCollision = this.onCollision.bind(this);

        this.type = "PlayeBaseEntity";

        this.renderable.addAnimation("idle", [0]);
        this.renderable.addAnimation("broken", [1]);
        this.renderable.setCurrentAnimation("idle");

    },

    update:function(delta){
        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, {
                image: "tower",
                width: 100,
                height: 100,
                spritewidth: "100",
                spriteheight: "100",
                getShape: function(){
                    return (new me.Rect(0, 0, 100, 70)).toPolygon();
                }
        }]);
        this.broken = false;
        this.health = 10;
        this.alwaysUpdate = true;
        this.body.onCollision = this.onCollision.bind(this);

        this.type = "EnemyEntityBase";

        this.renderable.addAnimation("idle", [0]);
        this.renderable.addAnimation("broken", [1]);
        this.renderable.setCurrentAnimation("idle");

    },

    update:function(delta){
        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>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*/

if (typeof __VST_PLAYBACK_SPEED__ === 'undefined') {
    window.__VST_PLAYBACK_SPEED__ = 1;
}
const nativeRaf = window.requestAnimationFrame;
const nativeSetTimeout = window.setTimeout;
const nativeSetInterval = window.setInterval;
const FIXED_FRAME_TIME = 16;
const MAX_FRAME_TIME = 80;
const TIMELINE_START = 1566458693300;

window.__VST_TIMELINE_PAUSED__ = true;

let realFrameStartTime = 0;

/** Control timeline loop */
let rafCbs = [];
let frameIdx = 0;
let timelineTime = 0;

function runFrame() {
    realFrameStartTime = NativeDate.now();
    frameIdx++;
    timelineTime += FIXED_FRAME_TIME;
    const currentRafCbs = rafCbs;
    // Clear before calling the callbacks. raf may be registered in the callback
    rafCbs = [];
    currentRafCbs.forEach((cb) => {
        try {
            cb();
        }
        catch (e) {
            // Catch error to avoid following tasks.
            __VST_LOG_ERRORS__(e.toString());
        }
    });
    flushTimeoutHandlers();
    flushIntervalHandlers();
}
function timelineLoop() {
    if (!__VST_TIMELINE_PAUSED__) {
        runFrame();
    }
    nativeRaf(timelineLoop);
}
nativeRaf(timelineLoop);

window.requestAnimationFrame = function (cb) {
    rafCbs.push(cb);
};

/** Mock setTimeout, setInterval */
let timeoutHandlers = [];
let intervalHandlers = [];

let timeoutId = 1;
let intervalId = 1;
window.setTimeout = function (cb, timeout) {
    const elapsedFrame = Math.ceil(Math.max(timeout || 0, 1) / FIXED_FRAME_TIME);
    timeoutHandlers.push({
        callback: cb,
        id: timeoutId,
        frame: frameIdx + elapsedFrame
    });

    return timeoutId++;
}

window.clearTimeout = function (id) {
    const idx = timeoutHandlers.findIndex(handler => {
        handler.id === id
    });
    if (idx >= 0) {
        timeoutHandlers.splice(idx, 1);
    }
}

function flushTimeoutHandlers() {
    let newTimeoutHandlers = [];
    for (let i = 0; i < timeoutHandlers.length; i++) {
        const handler = timeoutHandlers[i];
        if (handler.frame === frameIdx) {
            try {
                handler.callback();
            }
            catch (e) {
                // Catch error to avoid following tasks.
                __VST_LOG_ERRORS__(e.toString());
            }
        }
        else {
            newTimeoutHandlers.push(handler);
        }
    }
    timeoutHandlers = newTimeoutHandlers;
}

window.setInterval = function (cb, interval) {
    const intervalFrame = Math.ceil(Math.max(interval || 0, 1) / FIXED_FRAME_TIME);
    intervalHandlers.push({
        callback: cb,
        id: intervalId,
        intervalFrame,
        frame: frameIdx + intervalFrame
    })

    return intervalId++;
}

window.clearInterval = function () {
    const idx = intervalHandlers.findIndex(handler => {
        handler.id === id
    });
    if (idx >= 0) {
        intervalHandlers.splice(idx, 1);
    }
}

function flushIntervalHandlers() {
    for (let i = 0; i < intervalHandlers.length; i++) {
        const handler = intervalHandlers[i];
        if (handler.frame === frameIdx) {
            try {
                handler.callback();
            }
            catch (e) {
                // Catch error to avoid following tasks.
                __VST_LOG_ERRORS__(e.toString());
            }
            handler.frame += handler.intervalFrame;
        }
    }
}

/** Mock Date */

const NativeDate = window.Date;

const mockNow = function () {
    // // Use same time in one frame.
    // var realFrameTime = NativeDate.now();
    // // Split frame. Add 8ms offset on the second half
    // // Avoid infinite loop when some logic determine whether to break the loop based on the execution time.
    // // For example https://github.com/apache/echarts/blob/737e23c0054e6b501ecc6f562920cffae953b5c6/src/core/echarts.ts#L537
    // var frameDeltaTime = realFrameTime - realFrameStartTime;
    var frameDeltaTime = 0;
    // Use same time in one frame.
    return TIMELINE_START + (timelineTime + frameDeltaTime) * window.__VST_PLAYBACK_SPEED__;
};
function MockDate(...args) {
    if (!args.length) {
        return new NativeDate(mockNow());
    }
    else {
        return new NativeDate(...args);
    }
}
MockDate.prototype = Object.create(NativeDate.prototype);
Object.setPrototypeOf(MockDate, NativeDate);
MockDate.now = mockNow;
window.Date = MockDate;

// TODO Do we need to mock performance? Or leave some API that can keep real.

export function start() {
    window.__VST_TIMELINE_PAUSED__ = false;
}

export function pause() {
    window.__VST_TIMELINE_PAUSED__ = true;
}

export function resume() {
    window.__VST_TIMELINE_PAUSED__ = false;
}

export { nativeRaf, nativeSetInterval, nativeSetTimeout };<commit_msg>test(visual): fix clearInterval mock error<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*/

if (typeof __VST_PLAYBACK_SPEED__ === 'undefined') {
    window.__VST_PLAYBACK_SPEED__ = 1;
}
const nativeRaf = window.requestAnimationFrame;
const nativeSetTimeout = window.setTimeout;
const nativeSetInterval = window.setInterval;
const FIXED_FRAME_TIME = 16;
const MAX_FRAME_TIME = 80;
const TIMELINE_START = 1566458693300;

window.__VST_TIMELINE_PAUSED__ = true;

let realFrameStartTime = 0;

/** Control timeline loop */
let rafCbs = [];
let frameIdx = 0;
let timelineTime = 0;

function runFrame() {
    realFrameStartTime = NativeDate.now();
    frameIdx++;
    timelineTime += FIXED_FRAME_TIME;
    const currentRafCbs = rafCbs;
    // Clear before calling the callbacks. raf may be registered in the callback
    rafCbs = [];
    currentRafCbs.forEach((cb) => {
        try {
            cb();
        }
        catch (e) {
            // Catch error to avoid following tasks.
            __VST_LOG_ERRORS__(e.toString());
        }
    });
    flushTimeoutHandlers();
    flushIntervalHandlers();
}
function timelineLoop() {
    if (!__VST_TIMELINE_PAUSED__) {
        runFrame();
    }
    nativeRaf(timelineLoop);
}
nativeRaf(timelineLoop);

window.requestAnimationFrame = function (cb) {
    rafCbs.push(cb);
};

/** Mock setTimeout, setInterval */
let timeoutHandlers = [];
let intervalHandlers = [];

let timeoutId = 1;
let intervalId = 1;
window.setTimeout = function (cb, timeout) {
    const elapsedFrame = Math.ceil(Math.max(timeout || 0, 1) / FIXED_FRAME_TIME);
    timeoutHandlers.push({
        callback: cb,
        id: timeoutId,
        frame: frameIdx + elapsedFrame
    });

    return timeoutId++;
}

window.clearTimeout = function (id) {
    const idx = timeoutHandlers.findIndex(handler => {
        return handler.id === id
    });
    if (idx >= 0) {
        timeoutHandlers.splice(idx, 1);
    }
}

function flushTimeoutHandlers() {
    let newTimeoutHandlers = [];
    for (let i = 0; i < timeoutHandlers.length; i++) {
        const handler = timeoutHandlers[i];
        if (handler.frame === frameIdx) {
            try {
                handler.callback();
            }
            catch (e) {
                // Catch error to avoid following tasks.
                __VST_LOG_ERRORS__(e.toString());
            }
        }
        else {
            newTimeoutHandlers.push(handler);
        }
    }
    timeoutHandlers = newTimeoutHandlers;
}

window.setInterval = function (cb, interval) {
    const intervalFrame = Math.ceil(Math.max(interval || 0, 1) / FIXED_FRAME_TIME);
    intervalHandlers.push({
        callback: cb,
        id: intervalId,
        intervalFrame,
        frame: frameIdx + intervalFrame
    });

    return intervalId++;
}

window.clearInterval = function (id) {
    const idx = intervalHandlers.findIndex(handler => {
        return handler.id === id;
    });
    if (idx >= 0) {
        intervalHandlers.splice(idx, 1);
    }
}

function flushIntervalHandlers() {
    for (let i = 0; i < intervalHandlers.length; i++) {
        const handler = intervalHandlers[i];
        if (handler.frame === frameIdx) {
            try {
                handler.callback();
            }
            catch (e) {
                // Catch error to avoid following tasks.
                __VST_LOG_ERRORS__(e.toString());
            }
            handler.frame += handler.intervalFrame;
        }
    }
}

/** Mock Date */

const NativeDate = window.Date;

const mockNow = function () {
    // // Use same time in one frame.
    // var realFrameTime = NativeDate.now();
    // // Split frame. Add 8ms offset on the second half
    // // Avoid infinite loop when some logic determine whether to break the loop based on the execution time.
    // // For example https://github.com/apache/echarts/blob/737e23c0054e6b501ecc6f562920cffae953b5c6/src/core/echarts.ts#L537
    // var frameDeltaTime = realFrameTime - realFrameStartTime;
    var frameDeltaTime = 0;
    // Use same time in one frame.
    return TIMELINE_START + (timelineTime + frameDeltaTime) * window.__VST_PLAYBACK_SPEED__;
};
function MockDate(...args) {
    if (!args.length) {
        return new NativeDate(mockNow());
    }
    else {
        return new NativeDate(...args);
    }
}
MockDate.prototype = Object.create(NativeDate.prototype);
Object.setPrototypeOf(MockDate, NativeDate);
MockDate.now = mockNow;
window.Date = MockDate;

// TODO Do we need to mock performance? Or leave some API that can keep real.

export function start() {
    window.__VST_TIMELINE_PAUSED__ = false;
}

export function pause() {
    window.__VST_TIMELINE_PAUSED__ = true;
}

export function resume() {
    window.__VST_TIMELINE_PAUSED__ = false;
}

export { nativeRaf, nativeSetInterval, nativeSetTimeout };<|endoftext|>


<commit_before>game.PlayerEntity = me.Entity.extend({
	init: function(x, y, settings) {
		this._super(me.Entity, 'init', [x, y, {
			image:"player",
			/*telling the screen how much space to preserve*/
			width: 64,
			height: 64,
			/*spritewidth and height are passing us information. telling us the size of image*/
			spritewidth: "64",
			spriteheight: "64",
			getShape: function(){
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
			}
		}]);
		/*velocity represents current position*/
		this.body.setVelocity(5, 20);
		/*following the player on the screen*/
		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);
		/*when the action is done, the sprite tat is equal to the number is put into play*/
		this.renderable.addAnimation("idle", [78]);
		/*the image number are olny used when the action "walk" is played*/
		this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
		/*this is the current animatio when no keys are pressed. the sprite is idle and standing still.*/
		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);
		this.renderable.setCurrentAnimation("idle");
	},

	update: function(delta){
		if(me.input.isKeyPressed("right")){
			/*adds to the position of my x by the velocity defined above in
			setVelocity() and multiplying it by me.time.tick.
			me.time.tick makes the movement look smooth*/
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			this.flipX(true);
			/*this is the current animation when the "right" key is pressed.*/

		}else{
			this.body.vel.x = 0;
		}

	if(me.input.isKeyPressed("attack")){
			if(!this.renderable.isCurrentAnimation("attack")){
				console.log(!this.renderable.isCurrentAnimation("attack"));
				/*sets the currents 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 whereever we left off when we switched to another animation*/
				this.renderable.setAnimationFrame();
			}
		}

		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")){
				console.log(!this.renderable.isCurrentAnimation("attack"));
				/*sets the currents 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 whereever we left off when we switched to another animation*/
				this.renderable.setAnimationFrame();
			}
		}

		this.body.update(delta);

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

});

/*seeting the player and enemy's bases*/
game.PlayerBaseEntity = me.Entity.extend({
	init : function(x, y, settings) {
		this._super(me.Entity, 'init', [x, y, {
			image: "tower",
			width: 100,
			height:100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function(){
				/*the how many pixels the rectangle is*/
				return (new me.Rect(0, 0, 100, 70)).toPolygon();
			}
		}]);
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		this.body.onCollision = this.onCollision.bind(this);
		this.type = "PlayerBaseEntity";

		this.renderable.addAnimation("idle", [0]);
		this.renderable.addAnimation("broken", [1]);
		this.renderable.setCurrentAnimation("idle");

	},

	update:function(delta){
		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, {
			image: "tower",
			width: 100,
			height:100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function(){
				/*the how many pixels the rectangle is*/
				return (new me.Rect(0, 0, 100, 70)).toPolygon();
			}
		}]);
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		this.body.onCollision = this.onCollision.bind(this);
		this.type = "EnemyBaseEntity";
		/*fixing the two towers*/
		this.renderable.addAnimation("idle", [0]);
		this.renderable.addAnimation("broken", [1]);
		this.renderable.setCurrentAnimation("idle");
	},

	update:function(delta){
		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 and 16 code and comments<commit_after>game.PlayerEntity = me.Entity.extend({
	init: function(x, y, settings) {
		this._super(me.Entity, 'init', [x, y, {
			image:"player",
			/*telling the screen how much space to preserve*/
			width: 64,
			height: 64,
			/*spritewidth and height are passing us information. telling us the size of image*/
			spritewidth: "64",
			spriteheight: "64",
			getShape: function(){
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
			}
		}]);
		/*velocity represents current position*/
		this.body.setVelocity(5, 20);
		this.facing = "right";
		/*following the player on the screen*/
		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);
		/*when the action is done, the sprite tat is equal to the number is put into play*/
		this.renderable.addAnimation("idle", [78]);
		/*the image number are olny used when the action "walk" is played*/
		this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
		/*this is the current animatio when no keys are pressed. the sprite is idle and standing still.*/
		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);
		this.renderable.setCurrentAnimation("idle");
	},

	update: function(delta){
		if(me.input.isKeyPressed("right")){
			/*adds to the position of my x by the velocity defined above in
			setVelocity() and multiplying it by me.time.tick.
			me.time.tick makes the movement look smooth*/
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			this.facing = "right";
			this.flipX(true);
		}else if(me.input.isKeyPressed("left")){
			this.facing = "left";
			this.body.vel.x -=this.body.accel.x * me.timer.tick;
			this.flipX(false);

		}else{
			this.body.vel.x = 0;
		}

	if(me.input.isKeyPressed("jump") && !this.jumping && !this.falling){
		this.jumping = true;
		this.body.vel.y -=this.body.accel.y * me.timer.tick;
	}

	if(me.input.isKeyPressed("attack")){
			if(!this.renderable.isCurrentAnimation("attack")){
				console.log(!this.renderable.isCurrentAnimation("attack"));
				/*sets the currents 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 whereever we left off when we switched to another animation*/
				this.renderable.setAnimationFrame();
			}
		}

		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")){
				console.log(!this.renderable.isCurrentAnimation("attack"));
				/*sets the currents 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 whereever we left off when we switched to another animation*/
				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;
	},
/*setting what is going to happen tothe player when it gets to the enemy base and also setting our own methods*/
	collideHandler: function(response){
		if(response.b.type==='EnemyBaseEntity'){
			var ydif = this.pos.y - response.b.pos.y;
			var xdif = this.pos.x - reponse.b.pos.x;

/*what is going to happen when we are cgetting near the enemy base from the left*/
			if(ydif<-40 && xdif< 70 && xdif>-35){
				this.body.vel.x = 0;
				this.pos.x = this.pos.x -1;

			}
			else 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.body.vel.x = this.pos.x +1;
			}
		}
	}
});

/*seeting the player and enemy's bases*/
game.PlayerBaseEntity = me.Entity.extend({
	init : function(x, y, settings) {
		this._super(me.Entity, 'init', [x, y, {
			image: "tower",
			width: 100,
			height:100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function(){
				/*the how many pixels the rectangle is*/
				return (new me.Rect(0, 0, 100, 70)).toPolygon();
			}
		}]);
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		this.body.onCollision = this.onCollision.bind(this);
		this.type = "PlayerBaseEntity";

		this.renderable.addAnimation("idle", [0]);
		this.renderable.addAnimation("broken", [1]);
		this.renderable.setCurrentAnimation("idle");

	},

	update:function(delta){
		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, {
			image: "tower",
			width: 100,
			height:100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function(){
				/*the how many pixels the rectangle is*/
				return (new me.Rect(0, 0, 100, 70)).toPolygon();
			}
		}]);
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		this.body.onCollision = this.onCollision.bind(this);
		this.type = "EnemyBaseEntity";
		/*fixing the two towers*/
		this.renderable.addAnimation("idle", [0]);
		this.renderable.addAnimation("broken", [1]);
		this.renderable.setCurrentAnimation("idle");
	},

	update:function(delta){
		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><commit_msg>Update project webtorrent to 0.63.0<commit_after><|endoftext|>


<commit_before>/**
 *
 * Display the objectives on the top left of the screen
 * If not changed on the Ken prototype, it's under his healthbar
 *
 *
 * @param Game
 *
 */

var Objective = function (game) {
    this.game = game;
    Phaser.BitmapText.call(this, game, 30, 60, 'gem', '', 20);
    this.smoothed = false;

};

Objective.prototype = Object.create(Phaser.BitmapText.prototype);
Objective.prototype.constructor = Objective;

Objective.prototype.update = function(){

    if(this.game.level.enemiesToKill){
        // Number of ennemies to kill before next level
        var enemiesToGo = ((this.game.level.enemiesToKill - this.game.enemiesKilled)>=0) ? (this.game.level.enemiesToKill - this.game.enemiesKilled) : 0 ;
        this.text = "ENEMIES REMAINING : " + enemiesToGo;
    }else if(this.game.level.timeLimit){
        // Time to survive before next level
        var timeToGo = ((this.game.level.timeLimit - this.game.elapsedTime) >= 0 ) ? (this.game.level.timeLimit - this.game.elapsedTime) : 0;
        this.text = "TIME REMAINING : " + Math.round(timeToGo);
    }else if(this.game.level.bossesToKill){
        // Bosses to kill
        this.text = "KILL THE BOSS !";
    }

};
<commit_msg>Changed objectives text<commit_after>/**
 *
 * Display the objectives on the top left of the screen
 * If not changed on the Ken prototype, it's under his healthbar
 *
 *
 * @param Game
 *
 */

var Objective = function (game) {
    this.game = game;
    Phaser.BitmapText.call(this, game, 30, 60, 'gem', '', 20);
    this.smoothed = false;

};

Objective.prototype = Object.create(Phaser.BitmapText.prototype);
Objective.prototype.constructor = Objective;

Objective.prototype.update = function(){

    if(this.game.level.enemiesToKill){
        // Number of ennemies to kill before next level
        var enemiesToGo = ((this.game.level.enemiesToKill - this.game.enemiesKilled)>=0) ? (this.game.level.enemiesToKill - this.game.enemiesKilled) : 0 ;
        this.text = "ENEMIES TO KILL : " + enemiesToGo;
    }else if(this.game.level.timeLimit){
        // Time to survive before next level
        var timeToGo = ((this.game.level.timeLimit - this.game.elapsedTime) >= 0 ) ? (this.game.level.timeLimit - this.game.elapsedTime) : 0;
        this.text = "TIME REMAINING : " + Math.round(timeToGo);
    }else if(this.game.level.bossesToKill){
        // Bosses to kill
        this.text = "KILL THE BOSS !";
        if(this.game.level.bossesToKill > 1)
            this.text = "KILL THE BOSSES !";
    }

};
<|endoftext|>


<commit_before>"use strict"; // run code in ES5 strict mode

var expect = require("expect.js"),
    rewire = require("rewire"),
    modelStatics = rewire("../../lib/shared/modelStatics.js");

describe("modelStatics", function () {
    describe(".getResourceUrl()", function () {
        var result = {},
            ids = {
                "blog": 1,
                "blog/post": 2,
                "blog/post/comment": 3
            },
            args;

        function getResourceUrlMock() {
            args = arguments;
            return result;
        }

        function CommentMock() {}
        CommentMock.prototype.url = "blog/post/comment";
        CommentMock.getResourceUrl = modelStatics.getResourceUrl;

        modelStatics.__set__("_getResourceUrl", getResourceUrlMock);

        it("should call getResourceUrl() with the model-url and the given ids and return the result", function () {
            expect(CommentMock.getResourceUrl(ids)).to.be(result);
            expect(args).to.eql([CommentMock.prototype.url, ids]);
        });
    });
});<commit_msg>Fix test for odelStatics.getResourceUrl()<commit_after>"use strict"; // run code in ES5 strict mode

var expect = require("expect.js"),
    rewire = require("rewire"),
    modelStatics = rewire("../../lib/shared/modelStatics.js");

var slice = Array.prototype.slice;

describe("modelStatics", function () {
    describe(".getResourceUrl()", function () {
        var result = {},
            ids = {
                "blog": 1,
                "blog/post": 2,
                "blog/post/comment": 3
            },
            args;

        function getResourceUrlMock() {
            args = slice.call(arguments);
            return result;
        }

        function CommentMock() {}
        CommentMock.prototype.url = "blog/post/comment";
        CommentMock.getResourceUrl = modelStatics.getResourceUrl;

        modelStatics.__set__("_getResourceUrl", getResourceUrlMock);

        it("should call getResourceUrl() with the model-url and the given ids and return the result", function () {
            expect(CommentMock.getResourceUrl(ids)).to.be(result);
            expect(args).to.eql([CommentMock.prototype.url, ids]);
        });
    });
});<|endoftext|>


<commit_before>
Highbrow.SettingsDialog = this.Highbrow.SettingsDialog = function(hb,conf) {

    "use strict;"

    if (! (this instanceof Highbrow.SettingsDialog)) throw "called Highbrow.SettingsDialog constructor as if it were a function: missing 'new'.";

    var ttId    = hb.prefix + "tt"; // track table
    var gtId    = hb.previx + "gt"; // group table

    var ttDivId = hb.prefix + "ttDiv";

    var ttData  = [];
    var ttCols  = [];
    var gtData  = [];
    var gtCols  = [];

    var newTT   = false;

    var ttjqd  ="";

    // public methods.

    this.onDraw = function(){
	// for some reason this has to happen after a bunch of other stuff.
	// wierd. but whatever. This works.
	// Actually it doesn't.
	if ( newTT && $('#'+ttId).length > 0 ) {
	    dataTabulate('#'+ttId,ttData,ttCols);
	    //dataTabulate('#'+gtId,gtData,gtCols);
	    newTT=false;
	}
    };

    this.trackAdded = function(t){
	var row = [t.id,t.visible,t.order,t.name,t.type,hb.notecount(t)];
	$('#'+ttId).dataTable().fnAddData(row);
	if ( t.type != "group" ) {
	    //$('#'+gtId).dataTable().fnAddData(row);
	};
    };

    var showTT = function(){
	// show the darn dialog.
	dataTabulate(ttId,ttData,ttCols);
	ttjqd.dialog('open');
	return false;
    };

    var groupLink = function(trackId){
	var t = hb.trackById[trackId];
	if ( t.type == "group" ) {
	    var onclick = "HB.openGroupEditDialog('" + t.id + "'); return false;";
	    return t.type + " (" + t.trackIds.length  + " members )";
	}
	return t.type;
    };

    var dataTabulate = function(tableId,tableData,tableColumns){
	// turn data and html table into a jquery datatable.
	// setup for track table and group table is identical.
	//alert("dataTabulating " + tableId + tableData + tableColumns);
	$(tableId).dataTable({
		"bJQueryUI": true,
		"aaData": tableData,
		"aoColumns": tableColumns,
		"aaSorting": [[ 1, "asc" ]],
		"oLanguage": {"sSearch": "Filter:" },
		"bPaginate": false,
		"bAutoWidth": false
	    });
    };

    var initTT = function(){
	newTT=true;
	for ( var i = 1; i < hb.tracks.length; i++ ) {
	    var t = hb.tracks[i];
	    ttData.push( [ t.id, t.visible, t.order, t.name, t.type, hb.notecount(t) ] );
	}
	ttCols = [
    { "sTitle": "id", "bVisible" : false, "width" : "0px" },
    { "width" : "100px", "sTitle": "Show?", "fnRender": function(cell) { return hb.cb( cell.aData[1], { "id" : "cb"+cell.aData[0] }); } },
    { "width" : "100px", "sTitle": "Order" },
    { "width" : "200px", "sTitle": "Name", "fnRender": function(cell) {  return '' + cell.aData[3] + ''; } },
    { "width" : "200px", "sTitle": "Type", "fnRender": function(cell) { return groupLink(cell.aData[0]);}},
    { "width" : "200px", "sTitle": "Notes" }
		     ];
    };

    var init = function(){
	$("#"+hb.prefix + "showSettingsDialog").click(function(e) { showTT() ; e.preventDefault(); });
	initTT();
	initTTJQD();
	attachListeners();
    };

    var attachListeners = function(){
	var selector = '.' + hb.prefix +'trackTitle';
	$("#"+ttDivId).on("click",selector,function(event){
		// make clicked title editable.
		event.preventDefault();
		var target = event.target;
		var trackId = target.getAttribute('data-track');
		if ( ! trackId ) {
		    return;
		}
		var row = target.getAttribute('data-row');
		var col = target.getAttribute('data-col');
		var track = hb.trackById[trackId];
		event.target.innerHTML = tag('input',
					     {'type': 'text',
					      'value': track.name,
					      'data-track': trackId,
					      'data-row':row,
					      'data-col':col
					     });
	    });
	$("#"+ttDivId).on("blur",selector+" input",function(event){
		updateTrackName(event);
	    });
	$("#"+ttDivId).on("keydown",selector+" input",function(event){
		hb.event=event;
		if ( event.keyCode === 13 ) {
		    updateTrackName(event);
		}
	    });
    };

    var updateTrackName = function(event){
	var target = event.target;
	var trackId = target.getAttribute('data-track');
	var row = target.getAttribute('data-row');
	var col = target.getAttribute('data-col');
	var track = hb.trackById[trackId];
	var t = hb.trackById[trackId];
	t.name = target.value;
	$('#'+ttId).dataTable().fnUpdate( t.name, row, col );
	hb.editor.queueSave("update","commentary",t,t);
    };

    var tag = function(name,attributes,text){
	var html='<'+name;
	$.each(attributes, function(key,value) {
		html+= ' ' + key + ' = ' + '"' + value + '"';
	    });
	if ( text !== undefined) {
	    html += text + '</' + name + '>';
	} else {
	    html += ' />';
	}
	return html;
    };

    var initTTJQD = function(){
	// initialized track table jquery dialog widget.
	var html = "";
	html += '
A commentary is a collection of comments or annotations on a text. In Highbrow, each commentary is drawn as a horizontal band plotting annotation density against the referenced text.'
	html += 'Toggle commentaries on and off by ticking the box in the "show" column.
';
	html += '
Commentaries may be grouped. Click on the "member" count for commentary groups to add or remove member commentaries.
';
	html += '
Create new commentaries or groups using the buttons at the bottom of this window.
';
	html += '

';
	ttjqd = $('

')
	.html(html)
	.dialog({
		autoOpen: false,
		title: 'Configure Highbrow Commentaries',
		height: 520,
		width: 650,
		buttons:
		{
		    "New Commentary" : function() {
			hb.createOrdinaryTrack();
			//alert("Created new track " + t.name);
		    },
		    "New Group" : function() {
			var g = hb.initTrack();
			g.name = "New Group";
			g.id = "group"+hb.tracks.length;
			g.type="group";
			g.trackIds=[];
			hb.addTrack(g);
			alert("Created new group " + g.name);
		    },
		    "Apply": function()  {
			var debug="";
			for (var i=1; i < hb.tracks.length; i++ ) {
			    var t = hb.tracks[i];
			    t.visible = $("#cb"+t.id+":checked").val() !== undefined;
			    debug+="t.id: " + t.id + " visible? " + t.visible;
			    debug+="\n";
			}
			//alert("Debug: " + debug);
			hb.filterTracks();
			hb.adjustBounds();
		    }
		}
	    });
    };

    init();

};
<commit_msg>fixed track renaming.<commit_after>
Highbrow.SettingsDialog = this.Highbrow.SettingsDialog = function(hb,conf) {

    "use strict;"

    if (! (this instanceof Highbrow.SettingsDialog)) throw "called Highbrow.SettingsDialog constructor as if it were a function: missing 'new'.";

    var ttId    = hb.prefix + "tt"; // track table
    var gtId    = hb.prefix + "gt"; // group table

    var ttDivId = hb.prefix + "ttDiv";

    var ttData  = [];
    var ttCols  = [];
    var gtData  = [];
    var gtCols  = [];

    var newTT   = false;

    var ttjqd  ="";

    // public methods.

    this.onDraw = function(){
	// for some reason this has to happen after a bunch of other stuff.
	// wierd. but whatever. This works.
	// Actually it doesn't.
	if ( newTT && $('#'+ttId).length > 0 ) {
	    dataTabulate('#'+ttId,ttData,ttCols);
	    //dataTabulate('#'+gtId,gtData,gtCols);
	    newTT=false;
	}
    };

    this.trackAdded = function(t){
	var row = [t.id,t.visible,t.order,t.name,t.type,hb.notecount(t)];
	$('#'+ttId).dataTable().fnAddData(row);
	if ( t.type != "group" ) {
	    //$('#'+gtId).dataTable().fnAddData(row);
	};
    };

    var showTT = function(){
	// show the darn dialog.
	dataTabulate(ttId,ttData,ttCols);
	ttjqd.dialog('open');
	return false;
    };

    var groupLink = function(trackId){
	var t = hb.trackById[trackId];
	if ( t.type == "group" ) {
	    var onclick = "HB.openGroupEditDialog('" + t.id + "'); return false;";
	    return t.type + " (" + t.trackIds.length  + " members )";
	}
	return t.type;
    };

    var dataTabulate = function(tableId,tableData,tableColumns){
	// turn data and html table into a jquery datatable.
	// setup for track table and group table is identical.
	//alert("dataTabulating " + tableId + tableData + tableColumns);
	$(tableId).dataTable({
		"bJQueryUI": true,
		"aaData": tableData,
		"aoColumns": tableColumns,
		"aaSorting": [[ 1, "asc" ]],
		"oLanguage": {"sSearch": "Filter:" },
		"bPaginate": false,
		"bAutoWidth": false
	    });
    };

    var initTT = function(){
	newTT=true;
	for ( var i = 1; i < hb.tracks.length; i++ ) {
	    var t = hb.tracks[i];
	    ttData.push( [ t.id, t.visible, t.order, t.name, t.type, hb.notecount(t) ] );
	}
	ttCols = [
    { "sTitle": "id", "bVisible" : false, "width" : "0px" },
    { "width" : "100px", "sTitle": "Show?", "fnRender": function(cell) { return hb.cb( cell.aData[1], { "id" : "cb"+cell.aData[0] }); } },
    { "width" : "100px", "sTitle": "Order" },
    { "width" : "200px", "sTitle": "Name", "fnRender": function(cell) {  return '' + cell.aData[3] + ''; } },
    { "width" : "200px", "sTitle": "Type", "fnRender": function(cell) { return groupLink(cell.aData[0]);}},
    { "width" : "200px", "sTitle": "Notes" }
		     ];
    };

    var init = function(){
	$("#"+hb.prefix + "showSettingsDialog").click(function(e) { showTT() ; e.preventDefault(); });
	initTT();
	initTTJQD();
	attachListeners();
    };

    var attachListeners = function(){
	var selector = '.' + hb.prefix +'trackTitle';
	$("#"+ttDivId).on("click",selector,function(event){
	    // make clicked title editable.
	    event.preventDefault();
	    var target = event.target;
	    var trackId = target.getAttribute('data-track');
	    if ( ! trackId ) {
		return;
	    }
	    var row = target.getAttribute('data-row');
	    var col = target.getAttribute('data-col');
	    var track = hb.trackById[trackId];
	    if ( ! track.editable ){
		return;
	    }
	    event.target.innerHTML = tag('input',
					 {'type': 'text',
					  'value': track.name,
					  'data-track': trackId,
					  'data-row':row,
					  'data-col':col
					 });
	});
	$("#"+ttDivId).on("blur",selector+" input",function(event){
		updateTrackName(event);
	});
	$("#"+ttDivId).on("keydown",selector+" input",function(event){
	    hb.event=event;
	    if ( event.keyCode === 13 ) {
		updateTrackName(event);
	    }
	});
    };

    var updateTrackName = function(event){
	var target = event.target;
	var trackId = target.getAttribute('data-track');
	var row = parseInt(target.getAttribute('data-row'));
	var col = parseInt(target.getAttribute('data-col'));
	var t = hb.trackById[trackId];
	t.name = target.value;
	$('#'+ttId).dataTable().fnUpdate( t.name, row, col );
	hb.editor.queueSave("update","commentary",t,t);
    };

    var tag = function(name,attributes,text){
	var html='<'+name;
	$.each(attributes, function(key,value) {
		html+= ' ' + key + ' = ' + '"' + value + '"';
	    });
	if ( text !== undefined) {
	    html += text + '</' + name + '>';
	} else {
	    html += ' />';
	}
	return html;
    };

    var initTTJQD = function(){
	// initialized track table jquery dialog widget.
	var html = "";
	html += '
A commentary is a collection of comments or annotations on a text. In Highbrow, each commentary is drawn as a horizontal band plotting annotation density against the referenced text.'
	html += 'Toggle commentaries on and off by ticking the box in the "show" column.
';
	html += '
Commentaries may be grouped. Click on the "member" count for commentary groups to add or remove member commentaries.
';
	html += '
Create new commentaries or groups using the buttons at the bottom of this window.
';
	html += '

';
	ttjqd = $('

')
	.html(html)
	.dialog({
		autoOpen: false,
		title: 'Configure Highbrow Commentaries',
		height: 520,
		width: 650,
		buttons:
		{
		    "New Commentary" : function() {
			hb.createOrdinaryTrack();
			//alert("Created new track " + t.name);
		    },
		    "New Group" : function() {
			var g = hb.initTrack();
			g.name = "New Group";
			g.id = "group"+hb.tracks.length;
			g.type="group";
			g.trackIds=[];
			hb.addTrack(g);
			alert("Created new group " + g.name);
		    },
		    "Apply": function()  {
			var debug="";
			for (var i=1; i < hb.tracks.length; i++ ) {
			    var t = hb.tracks[i];
			    t.visible = $("#cb"+t.id+":checked").val() !== undefined;
			    debug+="t.id: " + t.id + " visible? " + t.visible;
			    debug+="\n";
			}
			//alert("Debug: " + debug);
			hb.filterTracks();
			hb.adjustBounds();
		    }
		}
	    });
    };

    init();

};
<|endoftext|>