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

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

    this.addAnimation();

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

setSuper: 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();
                }
        }]);
    },

setPlayerTimer: function(){
    this.now = new Date().getTime();
    this.lastHit = this.now;
    this.lastAttack = new Date().getTime(); //Haven't used this
},

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

},

    update: function(delta){
        this.now = new Date() .getTime();
        this.dead = this.checkIfDead();
        this.checkKeyPressesAndMoves();
        this.setAnimation();
        me.collision.check(this, true, this.collideHandler.bind(this), true);
        this.body.update(delta);
        this._super(me.Entity, "update", [delta]);
        return true;
    },

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

    checkKeyPressesAndMoves: 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(){
         //adds the position of my x by the velovity 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);
    },

    moveLeft: function(){
        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;
    },

    setAnimation: function(){
             if(this.attacking){
            if(!this.renderable.isCurrentAnimation("attack")){
                //Sets the current animation to attack 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 wherever we left off when we
                //switched to 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");
    }
    },

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

    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;
            }
            if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer){
                this.lastHit = this.now;
                response.b.loseHealth(game.data.playerAttackTimer);
            }
        }else if(response.b.type==='EnemyCreep'){
            var xdif = this.pos.x - response.b.pos.x;
            var ydif = this.pos.y - response.b.pos.y;

            if(xdif>0){
                //this.pos.x = this.pos.x + 1;
                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(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 leess than our attack, execute code iin if statement
                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);
            }
        }
    }
});

<commit_msg>inbtgftgtyg<commit_after>game.PlayerEntity = me.Entity.extend({
    init: function(x, y){
        this.setSuper(x, y);
        this.setPlayerTimer();
        this.setAttributes();
        this.type = "PlayerEntity";
        this.setFlags();

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

    this.addAnimation();

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

setSuper: function(x, y){
            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();
                }
        }]);
    },

setPlayerTimer: function(){
    this.now = new Date().getTime();
    this.lastHit = this.now;
    this.lastAttack = new Date().getTime(); //Haven't used this
},

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

},

    update: function(delta){
        this.now = new Date() .getTime();
        this.dead = this.checkIfDead();
        this.checkKeyPressesAndMoves();
        this.setAnimation();
        me.collision.check(this, true, this.collideHandler.bind(this), true);
        this.body.update(delta);
        this._super(me.Entity, "update", [delta]);
        return true;
    },

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

    checkKeyPressesAndMoves: 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(){
         //adds the position of my x by the velovity 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);
    },

    moveLeft: function(){
        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;
    },

    setAnimation: function(){
             if(this.attacking){
            if(!this.renderable.isCurrentAnimation("attack")){
                //Sets the current animation to attack 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 wherever we left off when we
                //switched to 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");
    }
    },

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

    collideHandler: function(response){
        if(response.b.type==='EnemyBaseEntity'){
            this.collideWithEnemyBase(response);
        }else if(response.b.type==='EnemyCreep'){
            this.colliideWithEnemyCreeps(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>-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){
                this.lastHit = this.now;
                response.b.loseHealth(game.data.playerAttackTimer);
            }
    },

    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){
                if(this.facing==="left"){
                    this.body.vel.x = 0;
                }
            }else{
                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"))
                    ){
                this.lastHit = this.now;
                ///if the creeps health is less than our attack, execute code iin if statement
                return true;
        }
        return true;
    },

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


<commit_before>var test = require('../test-tools/test')('“keyboardNavigation” plugin');
var keyCodes = require('../../utils/keyCodes');
var mockPlugin = require('../test-tools/mockPlugin');
var mockKeyboardEvent = require('../test-tools/mockKeyboardEvent');

var keyboardNavigation = require('../../plugins/keyboardNavigation');

test(
  'Changes the selected option',
  function(is) {
    is.plan(8);

    // Prepare select state.
    var mock = mockPlugin(keyboardNavigation);
    mock.view.options.emit('update', {
      values: ['1', '2', '3'],
    });
    mock.model.state.emit('value', {attributes: {}});

    // Press [↓].
    mock.model.patch.on('patch', function(patch) {is.equal(
      patch.value,
      '1',
      'selects the first option upon pressing [↓] if nothing has been ' +
      'selected before'
    );});

    mock.view.switchElement.emit('keydown', mockKeyboardEvent(
      keyCodes.DOWN_ARROW,
      {preventDefault: function() {is.pass(
        'calls the `event.preventDefault` method'
      );}}
    ));
    mock.model.patch.off('patch');

    // Press [→].
    mock.model.patch.on('patch', function(patch) {is.equal(
      patch.value,
      '2',
      'selects the next option upon pressing [→]'
    );});

    mock.view.switchElement.emit('keydown', mockKeyboardEvent(
      keyCodes.RIGHT_ARROW
    ));
    mock.model.patch.off('patch');

    // Press [↑].
    mock.model.patch.on('patch', function(patch) {is.equal(
      patch.value,
      '1',
      'selects the previous option upon pressing [↑]'
    );});

    mock.view.switchElement.emit('keydown', mockKeyboardEvent(
      keyCodes.UP_ARROW
    ));
    mock.model.patch.off('patch');

    // Press [←].
    mock.model.patch.on('patch', function(patch) {is.equal(
      patch.value,
      '1',
      'doesn’t change anything upon pressing [←] when the first option is ' +
      'already selected'
    );});

    mock.view.switchElement.emit('keydown', mockKeyboardEvent(
      keyCodes.LEFT_ARROW
    ));
    mock.model.patch.off('patch');

    // Press [END].
    mock.model.patch.on('patch', function(patch) {is.equal(
      patch.value,
      '3',
      'selects the last option upon pressing [END].'
    );});

    mock.view.switchElement.emit('keydown', mockKeyboardEvent(
      keyCodes.END
    ));
    mock.model.patch.off('patch');

    // Press [HOME].
    mock.model.patch.on('patch', function(patch) {is.equal(
      patch.value,
      '1',
      'selects the first option upon pressing [HOME].'
    );});

    mock.view.switchElement.emit('keydown', mockKeyboardEvent(
      keyCodes.HOME
    ));
    mock.model.patch.off('patch');

    // Prepare preselected select state.
    var preselectedMock = mockPlugin(keyboardNavigation);
    preselectedMock.view.options.emit('update', {
      values: ['1', '2', '3', '4'],
    });
    preselectedMock.model.state.emit('value', {attributes: {value: '2'}});

    // Press [↓].
    preselectedMock.model.patch.on('patch', function(patch) {is.equal(
      patch.value,
      '3',
      'selects the next option upon pressing [↓] if there is an initial ' +
      'selection'
    );});

    preselectedMock.view.switchElement.emit('keydown', mockKeyboardEvent(
      keyCodes.DOWN_ARROW
    ));
    preselectedMock.model.patch.off('patch');

    // Finnito.
    is.end();
  }
);

test.skip(  // TODO
  'Slides the dropdown out and back in'
);

test.skip(  // TODO
  'Works only when the select is in focus'
);

test.skip(  // TODO
  'Fails gracefully'
);
<commit_msg>Specify unfold behavior in “keyboardNavigation” [#6780]<commit_after>var test = require('../test-tools/test')('“keyboardNavigation” plugin');
var keyCodes = require('../../utils/keyCodes');
var mockPlugin = require('../test-tools/mockPlugin');
var mockKeyboardEvent = require('../test-tools/mockKeyboardEvent');

var keyboardNavigation = require('../../plugins/keyboardNavigation');

test(
  'Changes the selected option',
  function(is) {
    is.plan(8);

    // Prepare select state.
    var mock = mockPlugin(keyboardNavigation);
    mock.view.options.emit('update', {
      values: ['1', '2', '3'],
    });

    mock.model.state.emit('value', {attributes: {}});

    // Press [↓].
    mock.model.patch.on('patch', function(patch) {is.equal(
      patch.value,
      '1',
      'selects the first option upon pressing [↓] if nothing has been ' +
      'selected before'
    );});

    mock.view.switchElement.emit('keydown', mockKeyboardEvent(
      keyCodes.DOWN_ARROW,
      {preventDefault: function() {is.pass(
        'calls the `event.preventDefault` method'
      );}}
    ));

    mock.model.patch.off('patch');

    // Press [→].
    mock.model.patch.on('patch', function(patch) {is.equal(
      patch.value,
      '2',
      'selects the next option upon pressing [→]'
    );});

    mock.view.switchElement.emit('keydown', mockKeyboardEvent(
      keyCodes.RIGHT_ARROW
    ));

    mock.model.patch.off('patch');

    // Press [↑].
    mock.model.patch.on('patch', function(patch) {is.equal(
      patch.value,
      '1',
      'selects the previous option upon pressing [↑]'
    );});

    mock.view.switchElement.emit('keydown', mockKeyboardEvent(
      keyCodes.UP_ARROW
    ));

    mock.model.patch.off('patch');

    // Press [←].
    mock.model.patch.on('patch', function(patch) {is.equal(
      patch.value,
      '1',
      'doesn’t change anything upon pressing [←] when the first option is ' +
      'already selected'
    );});

    mock.view.switchElement.emit('keydown', mockKeyboardEvent(
      keyCodes.LEFT_ARROW
    ));

    mock.model.patch.off('patch');

    // Press [END].
    mock.model.patch.on('patch', function(patch) {is.equal(
      patch.value,
      '3',
      'selects the last option upon pressing [END].'
    );});

    mock.view.switchElement.emit('keydown', mockKeyboardEvent(
      keyCodes.END
    ));

    mock.model.patch.off('patch');

    // Press [HOME].
    mock.model.patch.on('patch', function(patch) {is.equal(
      patch.value,
      '1',
      'selects the first option upon pressing [HOME].'
    );});

    mock.view.switchElement.emit('keydown', mockKeyboardEvent(
      keyCodes.HOME
    ));

    mock.model.patch.off('patch');

    // Prepare preselected select state.
    var preselectedMock = mockPlugin(keyboardNavigation);
    preselectedMock.view.options.emit('update', {
      values: ['1', '2', '3', '4'],
    });

    preselectedMock.model.state.emit('value', {attributes: {value: '2'}});

    // Press [↓].
    preselectedMock.model.patch.on('patch', function(patch) {is.equal(
      patch.value,
      '3',
      'selects the next option upon pressing [↓] if there is an initial ' +
      'selection'
    );});

    preselectedMock.view.switchElement.emit('keydown', mockKeyboardEvent(
      keyCodes.DOWN_ARROW
    ));

    preselectedMock.model.patch.off('patch');

    // Finnito.
    is.end();
  }
);

test(
  'Unfolds the dropdown and folds it back up',
  function(is) {
    is.plan(7);

    // Prepare a mock select, folded initially.
    var mock = mockPlugin(keyboardNavigation);
    mock.model.state.emit('unfolded', {attributes: {}});

    // Press [SPACE].
    mock.model.patch.on('patch', function(patch) {is.equal(
      patch.unfolded,
      '',
      'unfolds the dropdown with [SPACE]'
    );});

    mock.view.switchElement.emit('keydown', mockKeyboardEvent(
      keyCodes.SPACE,
      {preventDefault: function() {is.pass(
        'calls the `event.preventDefault` method'
      );}}
    ));

    mock.model.patch.off('patch');

    // Press [SPACE] again.
    mock.model.patch.on('patch', function() {is.fail(
      'doesn’t fold the dropdown back up with [SPACE]'
    );});

    mock.view.switchElement.emit('keydown', mockKeyboardEvent(keyCodes.SPACE));
    mock.model.patch.off('patch');

    // Press [TAB].
    mock.model.patch.on('patch', function(patch) {is.equal(
      patch.unfolded,
      undefined,
      'folds the dropdown back up with [TAB]'
    );});

    mock.view.switchElement.emit('keydown', mockKeyboardEvent(
      keyCodes.TAB,
      {preventDefault: function() {is.pass(
        'calls the method `event.preventDefault` when [TAB] is pressed upon ' +
        'an unfolded dropdown'
      );}}
    ));

    mock.model.patch.off('patch');

    // Press [TAB] again.
    mock.model.patch.on('patch', function() {is.fail(
      'doesn’t unfold the dropdown with [TAB]'
    );});

    mock.view.switchElement.emit('keydown', mockKeyboardEvent(
      keyCodes.TAB,
      {preventDefault: function() {is.fail(
        'doesn’t call the method `event.preventDefault` when [TAB] is ' +
        'pressed upon a folded dropdown'
      );}}
    ));

    mock.model.patch.off('patch');

    // Press [ENTER].
    mock.model.patch.on('patch', function(patch) {is.equal(
      patch.unfolded,
      '',
      'unfolds the dropdown with [ENTER]'
    );});

    mock.view.switchElement.emit('keydown', mockKeyboardEvent(keyCodes.ENTER));
    mock.model.patch.off('patch');

    // Press [ENTER] again.
    mock.model.patch.on('patch', function(patch) {is.equal(
      patch.unfolded,
      undefined,
      'folds the dropdown back up with [ENTER]'
    );});

    mock.view.switchElement.emit('keydown', mockKeyboardEvent(keyCodes.ENTER));
    mock.model.patch.off('patch');

    // Prepare a mock select, initially unfolded.
    var unfoldedMock = mockPlugin(keyboardNavigation);
    unfoldedMock.model.state.emit('unfolded', {attributes: {unfolded: ''}});

    // Press [ESCAPE].
    unfoldedMock.model.patch.on('patch', function(patch) {is.equal(
      patch.unfolded,
      undefined,
      'folds the dropdown up with [ESCAPE]'
    );});

    unfoldedMock.view.switchElement.emit('keydown', mockKeyboardEvent(
      keyCodes.ESCAPE
    ));

    unfoldedMock.model.patch.off('patch');

    // Press [ESCAPE] again.
    unfoldedMock.model.patch.on('patch', function() {is.fail(
      'doesn’t unfold the dropdown with [ESCAPE]'
    );});

    unfoldedMock.view.switchElement.emit('keydown', mockKeyboardEvent(
      keyCodes.ESCAPE
    ));

    unfoldedMock.model.patch.off('patch');

    is.end();
  }
);

test.skip(  // TODO
  'Fails gracefully'
);
<|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.type ="PlayerEntity";
		this.health = 20;
		this.body.setVelocity(5, 20);
		//Keeps track of which direction your charcter is going
		this.facing = "right";
		this.now = new Date().getTime();
		this.lastHit = this.now;
		this.lastAttack = new Date().getTime();
		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) {
		this.now = new Date().getTime();
		if(me.input.isKeyPressed("right")){
			//adds to the position or my x by the velocity defined above in
			//setsVelocity() 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";
			//used when interacting with the enemy base
			this.flipX(true);
		}
		else if (me.input.isKeyPressed("left")){
			this.body.vel.x -= this.body.accel.x * me.timer.tick;
			this.facing = "left";
			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;
		//this will make the player jump.
		me.audio.play("jump");
	}

	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 we start this sequence we bgin
				//form the first animation, not wherever we left off when we
				//switched to another animation
				this.renderable.setAnimationFrame();
			}
		}
		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);
		//used to check for collisions
		this.body.update(delta);

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

	loseHealth: function(damage){
		this.health = this.health - damage;
		console.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;

			if(ydif<-40 && xdif<70 && xdif>-35){
				this.body.falling = false;
				this.body.vel.y = -1;
				//used so we dont fall from the enemy base
				//the -40 is used to block the character
			}

			else if(xdif>-35 && this.facing==='right' && (xdif<0) && (xdif<0) && ydif>-50) {
				this.body.vel.x = 0;
				this.pos.x = this.pos.x -1;
			}else if(xdif<70 && this==='left' && xdif>0) {
				this.body.vel.x = 0;
				this.pos.x = this.pos.x +1;
				//used to block him from the left and the right
			}

			if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= 1000){
				//1000 = equals number of times to end enemy base
				console.log("tower Hit");
				//will show in inspect element to see if the enemy base is actually getting hit
				this.lastHit = this.now;
				response.b.loseHealth();
			}
		}
	}
});
//The game.PlayerBaseEntity
game.PlayerBaseEntity = me.Entity.extend({
	init : function(x, y, settings) {
		this._super(me.Entity, 'init', [x, x, {
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function(){
				return (new me.Rect(0, 0, 100, 100)).toPolygon();
			}
		}]);
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "PlayerBase";

		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;
	},

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

	onCollision: function() {

	}

});
//The game.EnemyBaseEntity will create the enemy base
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, 100)).toPolygon();
			}
		}]);
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "EnemyBaseEntity";

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

	},

	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.health = 10;
			this.alwaysUpdate = true;
			//this.attacking lets us know if the enemy is currently attacking
			this.attacking = false;
			//keeps track of when our creep last attacked anything
			this.lastAttacking = new Date().getTime();
			//keeps trackof the last time our creep hit anything
			this.lastHit = new Date().getTime();
			this.now = new Data().getTime();
			this.body.setVelocity(3, 20);

			this. type = "EnemyCreep";

			this.renderable.addAnimation("walk", [3, 4, 5],  80);
			this.renderable.setCurrentAnimation('walk');
			//this EnemyCreep thing is used so there would be enemies in the game.
		},

		update: function(delta) {
			//so this area of code will make the creep do what we want it to do
		this.now = new Date().getTime();

		this.body.vel.x -= this.body.accel.x * me.timer.tick;
		//so this will the creep move left just like the player
		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 it has been at least 1 second since this creep hit a base
				if((this.now-this.lastHit >=1000)){
					//updates th 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);
				}
			}else if (response.b.type==='PlayerEntity'){
				var xdif = this.pos.x - response.b.pos.x;

				this.attacking=true;
				//this.lastAttacking=this.now;
				this.body.vel.x = 0;
				//keeps moving the creep to the right to maintain its position
				if(xdif>0){
					this.pos.x = this.pos.x + 1;
					this.body.vel.x = 0;
				}
				//checks that it has been at least 1 second since this creep hit a base
				if((this.now-this.lastHit >=1000) && xdif>0){
					//updates th 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();

				if(Math.round(this.now/1000)%10 ===0 && (this.now - this.lastCreep >= 1000)){
					this.lastCreep = this.now;
					var creepe = me.pool.pull("EnemyCreep", 1000, 0, {});
					me.game.world.addChild(creepe, 5);
				}

				return true;
			}
		});<commit_msg>Game Project Video 22 comments.<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.type ="PlayerEntity";
		this.health = 20;
		//this shows how mush health we have
		//the health can be changed
		this.body.setVelocity(5, 20);
		//Keeps track of which direction your charcter is going
		this.facing = "right";
		this.now = new Date().getTime();
		this.lastHit = this.now;
		this.lastAttack = new Date().getTime();
		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) {
		this.now = new Date().getTime();
		if(me.input.isKeyPressed("right")){
			//adds to the position or my x by the velocity defined above in
			//setsVelocity() 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";
			//used when interacting with the enemy base
			this.flipX(true);
		}
		else if (me.input.isKeyPressed("left")){
			this.body.vel.x -= this.body.accel.x * me.timer.tick;
			this.facing = "left";
			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;
		//this will make the player jump.
		me.audio.play("jump");
	}

	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 we start this sequence we bgin
				//form the first animation, not wherever we left off when we
				//switched to another animation
				this.renderable.setAnimationFrame();
			}
		}
		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);
		//used to check for collisions
		this.body.update(delta);

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

	loseHealth: function(damage){
		this.health = this.health - damage;
		console.log(this.health);
		//the console will show in inspect element if the player is being damaged
		//the this.health - damage will make the creep damage the player
	},

	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;
				//used so we dont fall from the enemy base
				//the -40 is used to block the character
			}

			else if(xdif>-35 && this.facing==='right' && (xdif<0) && (xdif<0) && ydif>-50) {
				this.body.vel.x = 0;
				this.pos.x = this.pos.x -1;
			}else if(xdif<70 && this==='left' && xdif>0) {
				this.body.vel.x = 0;
				this.pos.x = this.pos.x +1;
				//used to block him from the left and the right
			}

			if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= 1000){
				//1000 = equals number of times to end enemy base
				console.log("tower Hit");
				//will show in inspect element to see if the enemy base is actually getting hit
				this.lastHit = this.now;
				response.b.loseHealth();
			}
		}
	}
});
//The game.PlayerBaseEntity
game.PlayerBaseEntity = me.Entity.extend({
	init : function(x, y, settings) {
		this._super(me.Entity, 'init', [x, x, {
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function(){
				return (new me.Rect(0, 0, 100, 100)).toPolygon();
			}
		}]);
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "PlayerBase";

		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;
	},

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

	onCollision: function() {

	}

});
//The game.EnemyBaseEntity will create the enemy base
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, 100)).toPolygon();
			}
		}]);
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "EnemyBaseEntity";

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

	},

	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.health = 10;
			this.alwaysUpdate = true;
			//this.attacking lets us know if the enemy is currently attacking
			this.attacking = false;
			//keeps track of when our creep last attacked anything
			this.lastAttacking = new Date().getTime();
			//keeps trackof the last time our creep hit anything
			this.lastHit = new Date().getTime();
			this.now = new Data().getTime();
			this.body.setVelocity(3, 20);

			this. type = "EnemyCreep";

			this.renderable.addAnimation("walk", [3, 4, 5],  80);
			this.renderable.setCurrentAnimation('walk');
			//this EnemyCreep thing is used so there would be enemies in the game.
		},

		update: function(delta) {
			//so this area of code will make the creep do what we want it to do
		this.now = new Date().getTime();

		this.body.vel.x -= this.body.accel.x * me.timer.tick;
		//so this will the creep move left just like the player
		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 it has been at least 1 second since this creep hit a base
				if((this.now-this.lastHit >=1000)){
					//updates th 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);
				}
			}else if (response.b.type==='PlayerEntity'){
				var xdif = this.pos.x - response.b.pos.x;

				this.attacking=true;
				//this.lastAttacking=this.now;
				this.body.vel.x = 0;
				//keeps moving the creep to the right to maintain its position
				if(xdif>0){
					this.pos.x = this.pos.x + 1;
					this.body.vel.x = 0;
				}
				//checks that it has been at least 1 second since this creep hit a base
				if((this.now-this.lastHit >=1000) && xdif>0){
					//updates th 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();

				if(Math.round(this.now/1000)%10 ===0 && (this.now - this.lastCreep >= 1000)){
					this.lastCreep = this.now;
					var creepe = me.pool.pull("EnemyCreep", 1000, 0, {});
					me.game.world.addChild(creepe, 5);
				}

				return true;
			}
		});<|endoftext|>


<commit_before>//creating basic player class
game.PlayerEntity = me.Entity.extend({
	//init is constructor function with 3 parameters
	init: function(x, y, settings){
		//reaches to the constructor of entity
		//passes settings through []s
		this._super(me.Entity, 'init', [x, y, {
			//all the settings are being set
			image: "player",
			width: 64,
			height: 64,
			spritewidth: "64",
			spriteheight: "64",
			//returns shape of player in box
			getShape: function(){
				//.toPolygon turns shape into a polygon
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
			}
		}]);

		//sets velocity or movement speed for player
		//changed y movement
		this.body.setVelocity(5, 20);

		//screen follows wherever player goes on x and y axis
		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

		//adding "idle animation"
		this.renderable.addAnimation("idle", [78]);
		//adding "walk" animation and setting images to use
		this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
		//adding "attack" animation
		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);

		//sets an animation to start with (default)
		this.renderable.setCurrentAnimation("idle");
	},
	//what happens on the fly
	update: function(delta){
		//checks if right key was pressed
		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 movement look smooth
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			//flips animation position 180 degrees
			this.flipX(true);
		}
		//if right is not clicked, dont move
		else{
			this.body.vel.x = 0;
		}

		//if attack key is pressed...
		if(me.input.isKeyPressed("attack")){
			//if current animation isnt attack then sets current animation to attack then idle
			if(!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");

				this.renderable.setAnimationFrame();
			}
		}

		//walk animation only if character is moving
		else if(this.body.vel.x !== 0){
			//doesnt start walk animation if it is already walking
			if(!this.renderable.isCurrentAnimation("walk")){
			this.renderable.setCurrentAnimation("walk");
			}
		}
		//if velocity is 0 set to idle
		else{
			this.renderable.setCurrentAnimation("idle");
		}

		//if attack key is pressed...
		if(me.input.isKeyPressed("attack")){
			//if current animation isnt attack then sets current animation to attack then idle
			if(!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();
			}
		}

		//tells all the code to actually work
		//delta is change in time that happened
		//must always update for screen to run
		this.body.update(delta);

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

//creates PlayerBase class
//pretty much the same as creating the player class but with a few minor changes
game.PlayerBaseEntity = me.Entity.extend({
	init: function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			//settings being set (100 instead of 64 for the tower)
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",
			//returns shape of tower
			getShape: function(){
				//makes sure tower is a polygon
				return (new me.Rect(0, 0, 100, 100)).toPolygon();
			}
		}]);
		//says tower has not been destroyed
		this.broken = false;
		//sets health
		this.health = 10;
		//even if tower is not on screen, the tower will still update
		this.alwaysUpdate = true;
		//if player runs into tower it will be able to collide
		this.body.onCollision = this.onCollision.bind(this);
		//can check and see what you are running into
		this.type = "PlayerBaseEntity";

		//renderable helps with animation
		//adds not burning animation
		this.renderable.addAnimation("idle", [0]);
		//adds burning animation
		this.renderable.addAnimation("broken", [1]);
		//sets not burning animation
		this.renderable.setCurrentAnimation("idle");
	},

	//updates what happens on the fly
	update:function(delta){
		//if health is 0, then player is dead
		if(this.health<=0){
			this.broken = true;
			//sets burning animation
			this.renderable.setCurrentAnimation("broken");
		}
		//delta represents time since last update
		this.body.update(delta);

		//updates animation on the fly
		this._super(me.Entity, "update", [delta]);
		//must always return
		return true;
	},

	//must have collision function
	onCollision: function(){

	}
});

//just like PlayerBaseEntity class, but the name is EnemyBaseEntity
//everything is the same
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, 100)).toPolygon();
			}
		}]);
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "EnemyBaseEntity";

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

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

	onCollision: function(){

	}
});<commit_msg>vid 13 comments<commit_after>//creating basic player class
game.PlayerEntity = me.Entity.extend({
	//init is constructor function with 3 parameters
	init: function(x, y, settings){
		//reaches to the constructor of entity
		//passes settings through []s
		this._super(me.Entity, 'init', [x, y, {
			//all the settings are being set
			image: "player",
			width: 64,
			height: 64,
			spritewidth: "64",
			spriteheight: "64",
			//returns shape of player in box
			getShape: function(){
				//.toPolygon turns shape into a polygon
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
			}
		}]);

		//sets velocity or movement speed for player
		//changed y movement
		this.body.setVelocity(5, 20);

		//screen follows wherever player goes on x and y axis
		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

		//adding "idle animation"
		this.renderable.addAnimation("idle", [78]);
		//adding "walk" animation and setting images to use
		this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
		//adding "attack" animation
		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);

		//sets an animation to start with (default)
		this.renderable.setCurrentAnimation("idle");
	},
	//what happens on the fly
	update: function(delta){
		//checks if right key was pressed
		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 movement look smooth
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			//flips animation position 180 degrees
			this.flipX(true);
		}
		//if right is not clicked, dont move
		else{
			this.body.vel.x = 0;
		}

		//if attack key is pressed...
		if(me.input.isKeyPressed("attack")){
			//if current animation isnt attack then sets current animation to attack then idle
			if(!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();
			}
		}

		//walk animation only if character is moving
		else if(this.body.vel.x !== 0){
			//doesnt start walk animation if it is already walking
			if(!this.renderable.isCurrentAnimation("walk")){
			this.renderable.setCurrentAnimation("walk");
			}
		}
		//if velocity is 0 set to idle
		else{
			this.renderable.setCurrentAnimation("idle");
		}

		//if attack key is pressed...
		if(me.input.isKeyPressed("attack")){
			//if current animation isnt attack then sets current animation to attack then idle
			if(!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();
			}
		}

		//tells all the code to actually work
		//delta is change in time that happened
		//must always update for screen to run
		this.body.update(delta);

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

//creates PlayerBase class
//pretty much the same as creating the player class but with a few minor changes
game.PlayerBaseEntity = me.Entity.extend({
	init: function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			//settings being set (100 instead of 64 for the tower)
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",
			//returns shape of tower
			getShape: function(){
				//makes sure tower is a polygon
				return (new me.Rect(0, 0, 100, 100)).toPolygon();
			}
		}]);
		//says tower has not been destroyed
		this.broken = false;
		//sets health
		this.health = 10;
		//even if tower is not on screen, the tower will still update
		this.alwaysUpdate = true;
		//if player runs into tower it will be able to collide
		this.body.onCollision = this.onCollision.bind(this);
		//can check and see what you are running into
		this.type = "PlayerBaseEntity";

		//renderable helps with animation
		//adds not burning animation
		this.renderable.addAnimation("idle", [0]);
		//adds burning animation
		this.renderable.addAnimation("broken", [1]);
		//sets not burning animation
		this.renderable.setCurrentAnimation("idle");
	},

	//updates what happens on the fly
	update:function(delta){
		//if health is 0, then player is dead
		if(this.health<=0){
			this.broken = true;
			//sets burning animation
			this.renderable.setCurrentAnimation("broken");
		}
		//delta represents time since last update
		this.body.update(delta);

		//updates animation on the fly
		this._super(me.Entity, "update", [delta]);
		//must always return
		return true;
	},

	//must have collision function
	onCollision: function(){

	}
});

//just like PlayerBaseEntity class, but the name is EnemyBaseEntity
//everything is the same
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, 100)).toPolygon();
			}
		}]);
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "EnemyBaseEntity";

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

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

	onCollision: function(){

	}
});<|endoftext|>


<commit_before>	//creating basic player class
	game.PlayerEntity = me.Entity.extend({
		init: function(x, y, settings){
			//constructer function
			this.setSuper();
			this.setPlayerTimers();
			this.setAttributes();
			this.type = "PlayerEntity";
			this.setFlags();

			me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);
			//follows the player on the x axis on the screen

			this.addAnimation();

			this.renderable.setCurrentAnimation("idle");
			//rendering the idle position
		},

		setSuper: function(){
			//
			this._super(me.Entity, 'init', [x, y, {
				//all settings
				image: "player",
				//player image
				width: 64,
				//64 width
				height: 64,
				//64 height
				//height and width are the same almost all the time
				spritewidth: "64",
				//64 spritewidth
				spriteheight: "64",
				//64 spriteheight
				getShape: function(){
					return(new me.Rect(0, 0, 64, 64)).toPolygon();
					//rectangle of what character can walk in to
				}
			}]);
		},

		setPlayerTimers: function(){
			this.now = new Date().getTime();
			this.lastHit = this.now;
			this.lastAttack = new Date().getTime(); //Haven't used this

		},

		setAttributes: function(){
			this.health = game.data.playerHealth;
			this.body.setVelocity(game.data.playerMoveSpeed, 20);
			//movement speed
			//changing the x and y location
			this.attack = game.data.playerAttack;
		},

		setFlags: function(){
			this.facing = "right";
			//keeps track of which direction your character is going
			this.dead = false;
			this.attacking = false;
			},
		addAnimation: function(){
			this.renderable.addAnimation("idle", [78]);
			//telling the game what the idle position does
			this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
			//telling the game which animations to use for walking
			this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);
		},

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

			this.dead = checkIfDead();

			this.checkKeyPressesAndMove();

		this.setAnimation();

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

			this._super(me.Entity, "update", [delta]);
			//updating the super function "delta"
			return true;
			//returning true
		},

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

		checkKeyPressesAndMove: function(){
			if(me.input.isKeyPressed("right")){
				this.moveRight();
			}else if(me.input.isKeyPressed("left")){

			}else{
				this.body.vel.x = 0;
				//checking if velocity is 0
			}
			if(me.input.isKeyPressed("jump") && !this.body.jumping && !this.body.falling){
				//if not jumping or falling. jump ^
				//this is on Y axis so dont want this in the if else
				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;

				this.flipX(true);
				//flips animation
				this.facing = "right";
		},

		moveLeft: function(){
			this.facing = "left";
			//facing left when
			this.body.vel.x -= this.body.accel.x = me.timer.tick;
			//making player accelerate to the left
			this.flipX(false);
			//dont want player to look like hes walking right
			//when walking left
		},

		jump: function(){
			this.body.jumping = true;
			this.body.vel.y -= this.body.accel.y * me.timer.tick;
			},

		setAnimation: function(){
			if(this.attacking){
	if(!this.renderable.isCurrentAnimation("attack")){
		//Sets the current animation to attack and once that is over
		//goes back to the idle animation
		this.renderable.set.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.setCurrentAnimationFrame();
	}
}
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")''
}
		}

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

		collideHandler: function(response) {
			if (response.b.type==='EnemyBaseEntity') {
				//see if it is a enemy base entity
				var ydif = this.pos.y - response.b.pos.y;
				//difference between players y position
				//and bases y
				var xdif = this.pos.x - response.b.pos.x;
				//difference between players x position
				//and bases x
				console.log(ydif);

				if(ydif<-50 && xdif< 70 && xdif>-35) {
					//if ydif is beyond 30
					this.body.falling = false;
					//and falling is false
					this.body.vel.y = -1;
				}

				else if (xdif>-35 && this.facing==='right' && (xdif<0)){
					//go beyond 35 stop moving
					//making sure if youre on the right side even if
					//they're coliding they wont both trigger

					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;
					//when your not moving
					//this.pos.x = this.pos.x +1;
				}

				if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer){
					//if attacking
					//checking if it has been 400 ms since base was hit
					//going to update last hit variable so that this will work repeatedly
					this.lastHit = this.now;
					response.b.loseHealth(game.data.playerAttack);
					//responce is for b to lose 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;

				if (xdif>0) {
					this.pos.x = this.pos.x + 1;
					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(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 player is to the right of the creep and Im facing to the left
						//then i am allowed to attack it otherwize it wont work
						){
					this.lastHit = this.now;
					if(response.b.health <= game.data.playerAttack){
						//if the creeps health is less than our attack execute code in if statement
						game.data.gold += 1;
						//adds one gold for a creep kill
						console.log("Current gold: " + game.data.gold);
					}

					response.b.loseHealth(game.data.playerAttack);
				//only loses health if attacking
				}
			}
		}
});
<commit_msg>finished video 33 coded and commented. refactoring pretty much done<commit_after>	//creating basic player class
	game.PlayerEntity = me.Entity.extend({
		init: function(x, y, settings){
			//constructer function
			this.setSuper();
			this.setPlayerTimers();
			this.setAttributes();
			this.type = "PlayerEntity";
			this.setFlags();

			me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);
			//follows the player on the x axis on the screen

			this.addAnimation();

			this.renderable.setCurrentAnimation("idle");
			//rendering the idle position
		},

		setSuper: function(){
			//
			this._super(me.Entity, 'init', [x, y, {
				//all settings
				image: "player",
				//player image
				width: 64,
				//64 width
				height: 64,
				//64 height
				//height and width are the same almost all the time
				spritewidth: "64",
				//64 spritewidth
				spriteheight: "64",
				//64 spriteheight
				getShape: function(){
					return(new me.Rect(0, 0, 64, 64)).toPolygon();
					//rectangle of what character can walk in to
				}
			}]);
		},

		setPlayerTimers: function(){
			this.now = new Date().getTime();
			this.lastHit = this.now;
			this.lastAttack = new Date().getTime(); //Haven't used this

		},

		setAttributes: function(){
			this.health = game.data.playerHealth;
			this.body.setVelocity(game.data.playerMoveSpeed, 20);
			//movement speed
			//changing the x and y location
			this.attack = game.data.playerAttack;
		},

		setFlags: function(){
			this.facing = "right";
			//keeps track of which direction your character is going
			this.dead = false;
			this.attacking = false;
			},
		addAnimation: function(){
			this.renderable.addAnimation("idle", [78]);
			//telling the game what the idle position does
			this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
			//telling the game which animations to use for walking
			this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);
		},

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

			this.dead = checkIfDead();

			this.checkKeyPressesAndMove();

		this.setAnimation();

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

			this._super(me.Entity, "update", [delta]);
			//updating the super function "delta"
			return true;
			//returning true
		},

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

		checkKeyPressesAndMove: function(){
			if(me.input.isKeyPressed("right")){
				this.moveRight();
			}else if(me.input.isKeyPressed("left")){

			}else{
				this.body.vel.x = 0;
				//checking if velocity is 0
			}
			if(me.input.isKeyPressed("jump") && !this.body.jumping && !this.body.falling){
				//if not jumping or falling. jump ^
				//this is on Y axis so dont want this in the if else
				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;

				this.flipX(true);
				//flips animation
				this.facing = "right";
		},

		moveLeft: function(){
			this.facing = "left";
			//facing left when
			this.body.vel.x -= this.body.accel.x = me.timer.tick;
			//making player accelerate to the left
			this.flipX(false);
			//dont want player to look like hes walking right
			//when walking left
		},

		jump: function(){
			this.body.jumping = true;
			this.body.vel.y -= this.body.accel.y * me.timer.tick;
			},

		setAnimation: function(){
			if(this.attacking){
	if(!this.renderable.isCurrentAnimation("attack")){
		//Sets the current animation to attack and once that is over
		//goes back to the idle animation
		this.renderable.set.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.setCurrentAnimationFrame();
	}
}
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")''
}
		}

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

		collideHandler: function(response) {
			if (response.b.type==='EnemyBaseEntity') {
				//see if it is a enemy base entity
				this.collideWithEnemyBase(resonse);
			}else if(response.b.type==='EnemyCreep'){

				this.collideWithEnemyCreep(response);
	}
		},

		collideWithEnemyBase: function(resonse){
			var ydif = this.pos.y - response.b.pos.y;
				//difference between players y position
				//and bases y
				var xdif = this.pos.x - response.b.pos.x;
				//difference between players x position
				//and bases x
				console.log(ydif);

				if(ydif<-50 && xdif< 70 && xdif>-35) {
					//if ydif is beyond 30
					this.body.falling = false;
					//and falling is false
					this.body.vel.y = -1;
				}
			},
			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;
					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;
					}
				}
			},
			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 player is to the right of the creep and Im facing to the left
						//then i am allowed to attack it otherwize it wont work
						){
					this.lastHit = this.now;
					return true;

				}
				return false;
			},
			hitCreep: function(response){
				if(response.b.health <= game.data.playerAttack){
						//if the creeps health is less than our attack execute code in if statement
						game.data.gold += 1;
						//adds one gold for a creep kill
						console.log("Current gold: " + game.data.gold);
					}

					response.b.loseHealth(game.data.playerAttack);
				//only loses health if attacking

			}
});

<|endoftext|>


<commit_before>// Copyright 2015, University of Colorado Boulder

/**
 * Full PhET-iO build including phet version, phet-io version and accompanying material.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */

// modules
var assert = require( 'assert' );
var copyDirectory = require( '../../../chipper/js/grunt/copyDirectory' );
var child_process = require( 'child_process' );
var ChipperStringUtils = require( '../../../chipper/js/common/ChipperStringUtils' );

/**
 * @param grunt the grunt instance
 * @param {Object} buildConfig
 */
module.exports = function( grunt, buildConfig ) {
  'use strict';

  // TODO: chipper#101 eek, this is scary! we are importing from the repository dir. ideally we should just have uglify-js installed once in chipper?
  var uglify = require( '../../../' + buildConfig.name + '/node_modules/uglify-js' );

  // Read a JS file and uglify
  var readUgly = function( filename ) {
    var text = grunt.file.read( filename );
    return uglify.minify( text, {
      mangle: true,
      fromString: true,
      output: {
        inline_script: true, // escape </script
        beautify: false
      },
      compress: {
        global_defs: {}
      }
    } ).code;
  };

  var skipBuild = grunt.option( 'skipBuild' );
  var packageJSON = grunt.file.readJSON( 'package.json' );

  var cwd = process.cwd();

  var phetioBuildDir = cwd + '/build-phet-io';
  var buildDir = cwd + '/build';

  // Clean
  if ( grunt.file.exists( phetioBuildDir ) ) {
    grunt.file.delete( phetioBuildDir );
  }
  grunt.file.mkdir( phetioBuildDir );

  var createOtherPhETIOFiles = function() {

    // create devguide/
    grunt.file.mkdir( 'build/phet-io/devguide' );
    copyDirectory( grunt, '../sherpa/lib/highlight.js-9.1.0', 'build/phet-io/devguide/lib/highlight.js-9.1.0' );
    copyDirectory( grunt, '../phet-io/doc/devguide', 'build/phet-io/devguide', function( abspath, contents ) {
      if ( abspath.indexOf( '.html' ) >= 0 ) {
        return ChipperStringUtils.replaceAll( contents, '../../../sherpa/lib/highlight.js-9.1.0', 'lib/highlight.js-9.1.0' );
      }
    } );

    // output the SimIFrameClient.js and SimWrapperUtils.js to the top level lib (not protected), see https://github.com/phetsims/phet-io/issues/353
    grunt.file.mkdir( 'build/phet-io/lib' );

    // create protected/
    grunt.file.mkdir( 'build/phet-io/protected' );

    // Load the template for instance-proxies.html
    var templateText = grunt.file.read( '../phet-io/html/templates/load-state.html' );
    var lines = templateText.split( '\n' );
    var templateString = '[';
    lines.forEach( function( line ) {
      templateString = templateString + '\'' + line + '\',\n';
    } );
    // "<script>" does not parse in an HTML file (even if in JS), so we split it apart into separate substrings.
    templateString = ChipperStringUtils.replaceAll( templateString, '<script>', '<scr\'+\'ipt>' );
    templateString = ChipperStringUtils.replaceAll( templateString, '</script>', '</scr\'+\'ipt>' );
    templateString = templateString + '\'\'].join(\'\\n\')';

    var filterWrapper = function( abspath, contents ) {
      var originalContents = contents + '';
      if ( abspath.indexOf( '.js' ) >= 0 || abspath.indexOf( '.html' ) >= 0 ) {
        contents = ChipperStringUtils.replaceAll( contents, '$SIMULATION_NAME$', buildConfig.name );
        contents = ChipperStringUtils.replaceAll( contents, '$SIMULATION_VERSION$', buildConfig.version );
      }
      if ( abspath.indexOf( '.html' ) >= 0 ) {

        // RULES FOR INSTANCE_PROXIES
        contents = ChipperStringUtils.replaceAll( contents,
          '"../../../sherpa/lib/lodash-2.4.1.min.js"',
          '"https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.11.2/lodash.min.js"'
        );
        contents = ChipperStringUtils.replaceAll( contents,
          '"../../../sherpa/lib/font-awesome-4.5.0/css/font-awesome.min.css"',
          '"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css"'
        );
        contents = ChipperStringUtils.replaceAll( contents,
          '"../../../sherpa/lib/jquery-2.1.0.min.js"',
          '"https://code.jquery.com/jquery-2.2.3.min.js"'
        );
        contents = ChipperStringUtils.replaceAll( contents,
          '"../../../sherpa/lib/d3-4.2.2.min.js"',
          '"https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"'
        );
        contents = ChipperStringUtils.replaceAll( contents,
          '<script type="text/javascript" src="../../../assert/js/assert.js"></script>',
          '<script>' + grunt.file.read( '../assert/js/assert.js' ) + '</script>'
        );
        contents = ChipperStringUtils.replaceAll( contents,
          'var isBuiltMode = false;',
          'var isBuiltMode = true;' );
        contents = ChipperStringUtils.replaceAll( contents,
          'var templateText = null;',
          'var templateText = ' + templateString + ';'
        ); //template uses exclusively "
        // END RULES FOR INSTANCE_PROXIES

        contents = ChipperStringUtils.replaceAll( contents, '../../js/', '../../lib/' );
      }
      if ( contents !== originalContents ) {
        return contents;
      }
      else {
        return null; // signify no change (helps for images)
      }
    };
    copyDirectory( grunt, '../phet-io/apps', 'build/phet-io/protected/apps', filterWrapper );

    // TODO: what if something overwrites? These directories are being merged.
    var simSpecificPath = '../phet-io/html/' + buildConfig.name;
    if ( grunt.file.exists( simSpecificPath ) ) {
      var failOnExistingFiles = true;
      if ( skipBuild ) {
        failOnExistingFiles = false;
      }
      copyDirectory( grunt, simSpecificPath, 'build/phet-io/protected/wrappers', filterWrapper, { failOnExistingFiles: failOnExistingFiles } );
    }

    // The .htaccess file
    grunt.file.copy( '../phet-io/templates/.htaccess', 'build/phet-io/protected/.htaccess' );

    var wrapperHTML = grunt.file.read( '../phet-io/templates/wrappers.html' );
    wrapperHTML = ChipperStringUtils.replaceAll( wrapperHTML, '$SIM$', buildConfig.name );
    wrapperHTML = ChipperStringUtils.replaceAll( wrapperHTML, '$VERSION$', buildConfig.version );
    wrapperHTML = ChipperStringUtils.replaceAll( wrapperHTML, '$PHET_IO_HTML_SIM_FILENAME$', buildConfig.name + '_en-phetio.html' );
    wrapperHTML = ChipperStringUtils.replaceAll( wrapperHTML, '$SIM_NAME$', buildConfig.name );
    grunt.file.write( 'build/phet-io/protected/wrappers.html', wrapperHTML );

    var destinationPath = 'build/phet-io/lib';

    var minifyAndWrite = function( filename, precode ) {
      var minified = uglify.minify( [ '../phet-io/apps/common/js/' + filename ], {
        mangle: true,
        output: {
          inline_script: true, // escape </script
          beautify: false
        },
        compress: {
          global_defs: {}
        }
      } ).code;

      var copyrightHeader = '// Copyright 2002-2016, University of Colorado Boulder\n' +
                            '// This PhET-iO file requires a license\n' +
                            '// USE WITHOUT A LICENSE AGREEMENT IS STRICTLY PROHIBITED.\n' +
                            '// For licensing, please contact phethelp@colorado.edu';
      grunt.file.write( destinationPath + '/' + filename, copyrightHeader + '\n\n' + precode + minified );
    };

    minifyAndWrite( 'SimIFrameClient.js', '' );

    // Determine which sim versions will be pointed to by SimWrapperUtils
    minifyAndWrite( 'SimWrapperUtils.js', 'window.useRelativeSimPath=true;' );
  };

  if ( skipBuild ) {
    grunt.file.mkdir( 'build/phet-io' );
    createOtherPhETIOFiles();
  }
  else {
    var done = grunt.task.current.async();
    var command1 = 'grunt --brand=phet-io';
    var command2 = 'grunt --brand=phet';
    grunt.log.writeln( 'Starting command: ' + command1 + '...' );
    child_process.exec( command1, { cwd: cwd }, function( error1, stdout1, stderr1 ) {
      assert( !error1, 'error in ' + command1 + '\n' + error1 );
      grunt.log.writeln( stdout1 );
      grunt.log.writeln( stderr1 );
      grunt.log.writeln( 'Finished command: ' + command1 );
      copyDirectory( grunt, buildDir, phetioBuildDir );

      grunt.log.writeln( 'Starting command: ' + command2 + '...' );
      child_process.exec( command2, { cwd: cwd }, function( error2, stdout2, stderr2 ) {
        assert( !error2, 'error in ' + command2 + '\n' + error2 );
        grunt.log.writeln( stdout2 );
        grunt.log.writeln( stderr2 );
        grunt.log.writeln( 'Finished command: ' + command2 );
        copyDirectory( grunt, phetioBuildDir, buildDir + '/phet-io' );

        createOtherPhETIOFiles();
        done();
      } );
    } );
  }
};<commit_msg>Simplified clean, see https://github.com/phetsims/phet-io/issues/588<commit_after>// Copyright 2015, University of Colorado Boulder

/**
 * Full PhET-iO build including phet version, phet-io version and accompanying material.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */

// modules
var assert = require( 'assert' );
var copyDirectory = require( '../../../chipper/js/grunt/copyDirectory' );
var child_process = require( 'child_process' );
var ChipperStringUtils = require( '../../../chipper/js/common/ChipperStringUtils' );

/**
 * @param grunt the grunt instance
 * @param {Object} buildConfig
 */
module.exports = function( grunt, buildConfig ) {
  'use strict';

  // TODO: chipper#101 eek, this is scary! we are importing from the repository dir. ideally we should just have uglify-js installed once in chipper?
  var uglify = require( '../../../' + buildConfig.name + '/node_modules/uglify-js' );

  var skipBuild = grunt.option( 'skipBuild' );

  var cwd = process.cwd();

  var phetioBuildDir = cwd + '/build-phet-io';
  var buildDir = cwd + '/build';

  // Clean
  grunt.file.exists( phetioBuildDir ) && grunt.file.delete( phetioBuildDir );
  grunt.file.mkdir( phetioBuildDir );

  var createOtherPhETIOFiles = function() {

    // create devguide/
    grunt.file.mkdir( 'build/phet-io/devguide' );
    copyDirectory( grunt, '../sherpa/lib/highlight.js-9.1.0', 'build/phet-io/devguide/lib/highlight.js-9.1.0' );
    copyDirectory( grunt, '../phet-io/doc/devguide', 'build/phet-io/devguide', function( abspath, contents ) {
      if ( abspath.indexOf( '.html' ) >= 0 ) {
        return ChipperStringUtils.replaceAll( contents, '../../../sherpa/lib/highlight.js-9.1.0', 'lib/highlight.js-9.1.0' );
      }
    } );

    // output the SimIFrameClient.js and SimWrapperUtils.js to the top level lib (not protected), see https://github.com/phetsims/phet-io/issues/353
    grunt.file.mkdir( 'build/phet-io/lib' );

    // create protected/
    grunt.file.mkdir( 'build/phet-io/protected' );

    // Load the template for instance-proxies.html
    var templateText = grunt.file.read( '../phet-io/html/templates/load-state.html' );
    var lines = templateText.split( '\n' );
    var templateString = '[';
    lines.forEach( function( line ) {
      templateString = templateString + '\'' + line + '\',\n';
    } );
    // "<script>" does not parse in an HTML file (even if in JS), so we split it apart into separate substrings.
    templateString = ChipperStringUtils.replaceAll( templateString, '<script>', '<scr\'+\'ipt>' );
    templateString = ChipperStringUtils.replaceAll( templateString, '</script>', '</scr\'+\'ipt>' );
    templateString = templateString + '\'\'].join(\'\\n\')';

    var filterWrapper = function( abspath, contents ) {
      var originalContents = contents + '';
      if ( abspath.indexOf( '.js' ) >= 0 || abspath.indexOf( '.html' ) >= 0 ) {
        contents = ChipperStringUtils.replaceAll( contents, '$SIMULATION_NAME$', buildConfig.name );
        contents = ChipperStringUtils.replaceAll( contents, '$SIMULATION_VERSION$', buildConfig.version );
      }
      if ( abspath.indexOf( '.html' ) >= 0 ) {

        // RULES FOR INSTANCE_PROXIES
        contents = ChipperStringUtils.replaceAll( contents,
          '"../../../sherpa/lib/lodash-2.4.1.min.js"',
          '"https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.11.2/lodash.min.js"'
        );
        contents = ChipperStringUtils.replaceAll( contents,
          '"../../../sherpa/lib/font-awesome-4.5.0/css/font-awesome.min.css"',
          '"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css"'
        );
        contents = ChipperStringUtils.replaceAll( contents,
          '"../../../sherpa/lib/jquery-2.1.0.min.js"',
          '"https://code.jquery.com/jquery-2.2.3.min.js"'
        );
        contents = ChipperStringUtils.replaceAll( contents,
          '"../../../sherpa/lib/d3-4.2.2.min.js"',
          '"https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"'
        );
        contents = ChipperStringUtils.replaceAll( contents,
          '<script type="text/javascript" src="../../../assert/js/assert.js"></script>',
          '<script>' + grunt.file.read( '../assert/js/assert.js' ) + '</script>'
        );
        contents = ChipperStringUtils.replaceAll( contents,
          'var isBuiltMode = false;',
          'var isBuiltMode = true;' );
        contents = ChipperStringUtils.replaceAll( contents,
          'var templateText = null;',
          'var templateText = ' + templateString + ';'
        ); //template uses exclusively "
        // END RULES FOR INSTANCE_PROXIES

        contents = ChipperStringUtils.replaceAll( contents, '../../js/', '../../lib/' );
      }
      if ( contents !== originalContents ) {
        return contents;
      }
      else {
        return null; // signify no change (helps for images)
      }
    };
    copyDirectory( grunt, '../phet-io/apps', 'build/phet-io/protected/apps', filterWrapper );

    // TODO: what if something overwrites? These directories are being merged.
    var simSpecificPath = '../phet-io/html/' + buildConfig.name;
    if ( grunt.file.exists( simSpecificPath ) ) {
      var failOnExistingFiles = true;
      if ( skipBuild ) {
        failOnExistingFiles = false;
      }
      copyDirectory( grunt, simSpecificPath, 'build/phet-io/protected/wrappers', filterWrapper, { failOnExistingFiles: failOnExistingFiles } );
    }

    // The .htaccess file
    grunt.file.copy( '../phet-io/templates/.htaccess', 'build/phet-io/protected/.htaccess' );

    var wrapperHTML = grunt.file.read( '../phet-io/templates/wrappers.html' );
    wrapperHTML = ChipperStringUtils.replaceAll( wrapperHTML, '$SIM$', buildConfig.name );
    wrapperHTML = ChipperStringUtils.replaceAll( wrapperHTML, '$VERSION$', buildConfig.version );
    wrapperHTML = ChipperStringUtils.replaceAll( wrapperHTML, '$PHET_IO_HTML_SIM_FILENAME$', buildConfig.name + '_en-phetio.html' );
    wrapperHTML = ChipperStringUtils.replaceAll( wrapperHTML, '$SIM_NAME$', buildConfig.name );
    grunt.file.write( 'build/phet-io/protected/wrappers.html', wrapperHTML );

    var destinationPath = 'build/phet-io/lib';

    var minifyAndWrite = function( filename, precode ) {
      var minified = uglify.minify( [ '../phet-io/apps/common/js/' + filename ], {
        mangle: true,
        output: {
          inline_script: true, // escape </script
          beautify: false
        },
        compress: {
          global_defs: {}
        }
      } ).code;

      var copyrightHeader = '// Copyright 2002-2016, University of Colorado Boulder\n' +
                            '// This PhET-iO file requires a license\n' +
                            '// USE WITHOUT A LICENSE AGREEMENT IS STRICTLY PROHIBITED.\n' +
                            '// For licensing, please contact phethelp@colorado.edu';
      grunt.file.write( destinationPath + '/' + filename, copyrightHeader + '\n\n' + precode + minified );
    };

    minifyAndWrite( 'SimIFrameClient.js', '' );

    // Determine which sim versions will be pointed to by SimWrapperUtils
    minifyAndWrite( 'SimWrapperUtils.js', 'window.useRelativeSimPath=true;' );
  };

  if ( skipBuild ) {
    grunt.file.mkdir( 'build/phet-io' );
    createOtherPhETIOFiles();
  }
  else {
    var done = grunt.task.current.async();
    var command1 = 'grunt --brand=phet-io';
    var command2 = 'grunt --brand=phet';
    grunt.log.writeln( 'Starting command: ' + command1 + '...' );
    child_process.exec( command1, { cwd: cwd }, function( error1, stdout1, stderr1 ) {
      assert( !error1, 'error in ' + command1 + '\n' + error1 );
      grunt.log.writeln( stdout1 );
      grunt.log.writeln( stderr1 );
      grunt.log.writeln( 'Finished command: ' + command1 );
      copyDirectory( grunt, buildDir, phetioBuildDir );

      grunt.log.writeln( 'Starting command: ' + command2 + '...' );
      child_process.exec( command2, { cwd: cwd }, function( error2, stdout2, stderr2 ) {
        assert( !error2, 'error in ' + command2 + '\n' + error2 );
        grunt.log.writeln( stdout2 );
        grunt.log.writeln( stderr2 );
        grunt.log.writeln( 'Finished command: ' + command2 );
        copyDirectory( grunt, phetioBuildDir, buildDir + '/phet-io' );

        createOtherPhETIOFiles();
        done();
      } );
    } );
  }
};<|endoftext|>


<commit_before>(function($) {
	$.fn.enemyBoxes = function() {
		var selector = this.selector;

		return this.each(function() {

			$(this).on("click", function() {
				var element = this;

				if($(this).is(":checked")) {
					$(selector).not(element).attr("checked", false);
				}

			});

		});
	};
})(jQuery);<commit_msg>Changed the listener to listen to "change" instead of "click".<commit_after>(function($) {
	$.fn.enemyBoxes = function() {
		var selector = this.selector; //Get the selector used

		return this.each(function() {

			$(this).on('change', function() { //Creates a change listener on every element that matches the selector
				var element = this;

				//If a matching element changes, then it unchecks all its enemy boxes
				if($(this).is(':checked')) {
					$(selector).not(element).attr('checked', false);
				}

			});

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


<commit_before>(function( $ ) {
  $.fn.multiAdder = function(options) {

    // Plugin settings
    // No options yet
    var settings = $.extend( {
      placeholder         : 'value'
    }, options);

    function addMultiAdderRow(thisMultiAdder)
    {
      var row = thisMultiAdder.find('.multi-adder-row-holder:hidden').html();
      console.log(row);

      // If there are no rows yet
      if (thisMultiAdder.children('.multi-adder-row').length === 0) {
        thisMultiAdder.find('>:first-child').after(row);
        thisMultiAdder
          .find('.multi-adder-row:first')
          .find('input, textarea, select')
          .filter(':visible:first')
          .focus();
      } else {
        // If there are rows add row after the last one
        thisMultiAdder
          .children('.multi-adder-row:last').after(row);

        var lastRow = thisMultiAdder.find('> .multi-adder-row:last');

        lastRow
          .find('input, textarea, select')
          .filter(':visible:first')
          .focus();
      }
    }

    function removeMultiAdderRow(thisMultiAdderRow)
    {
      thisMultiAdderRow.remove();
    }

    // Add a row to multi adder
    $('.multi-adder').on('click', '.multi-add', function(e){
      e.preventDefault();

      // Set up our variables
      var thisMultiAdder = $(this).parents('.multi-adder');

      // Only set up our maxRows var if the attribute exists
      var maxRows = thisMultiAdder.attr('data-maxrows') || 0;

      // Stop adding rows if max rows value is reached
      if (maxRows) {
        if (thisMultiAdder.find('.multi-adder-row').length < maxRows) {
          addMultiAdderRow(thisMultiAdder);
        } else {
          alert('Maximum reached.');
        }
      } else {
        // Else just add the row
        addMultiAdderRow(thisMultiAdder);
      }
    });

    // Delete a row from multi adder
    $('.multi-adder').on('click', '.multi-adder-delete', function(e){
      e.preventDefault();
      var thisMultiAdderRow = $(this).parents('.multi-adder-row');
      removeMultiAdderRow(thisMultiAdderRow);
    });

  };
})(jQuery);
<commit_msg>Remove console log<commit_after>(function( $ ) {
  $.fn.multiAdder = function(options) {

    // Plugin settings
    // No options yet
    var settings = $.extend( {
      placeholder         : 'value'
    }, options);

    function addMultiAdderRow(thisMultiAdder)
    {
      var row = thisMultiAdder.find('.multi-adder-row-holder:hidden').html();

      // If there are no rows yet
      if (thisMultiAdder.children('.multi-adder-row').length === 0) {
        thisMultiAdder.find('>:first-child').after(row);
        thisMultiAdder
          .find('.multi-adder-row:first')
          .find('input, textarea, select')
          .filter(':visible:first')
          .focus();
      } else {
        // If there are rows add row after the last one
        thisMultiAdder
          .children('.multi-adder-row:last').after(row);

        var lastRow = thisMultiAdder.find('> .multi-adder-row:last');

        lastRow
          .find('input, textarea, select')
          .filter(':visible:first')
          .focus();
      }
    }

    function removeMultiAdderRow(thisMultiAdderRow)
    {
      thisMultiAdderRow.remove();
    }

    // Add a row to multi adder
    $('.multi-adder').on('click', '.multi-add', function(e){
      e.preventDefault();

      // Set up our variables
      var thisMultiAdder = $(this).parents('.multi-adder');

      // Only set up our maxRows var if the attribute exists
      var maxRows = thisMultiAdder.attr('data-maxrows') || 0;

      // Stop adding rows if max rows value is reached
      if (maxRows) {
        if (thisMultiAdder.find('.multi-adder-row').length < maxRows) {
          addMultiAdderRow(thisMultiAdder);
        } else {
          alert('Maximum reached.');
        }
      } else {
        // Else just add the row
        addMultiAdderRow(thisMultiAdder);
      }
    });

    // Delete a row from multi adder
    $('.multi-adder').on('click', '.multi-adder-delete', function(e){
      e.preventDefault();
      var thisMultiAdderRow = $(this).parents('.multi-adder-row');
      removeMultiAdderRow(thisMultiAdderRow);
    });

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


<commit_before>var chai = require("chai");
var sinon = require("sinon");
var rewire = require("rewire");
var expect = chai.expect;
require('../../../tests-config')(chai);

describe('TelemetryData', function () {
  var TelemetryData = rewire('../../../app/models/TelemetryData');
  var PacketParser = {};

  beforeEach(function () {
    PacketParser.parseData = sinon.stub();
    TelemetryData.__set__({
      'PacketParser': PacketParser
    });
  });

  afterEach(function () {
    TelemetryData.clearHeaders();
    TelemetryData.setCurrentState({});
    TelemetryData.removeAllListeners();
  });

  describe('settersAndGetters', function () {
    it('setHeaders should set headers', function () {
      TelemetryData.setHeaders(['header1', 'header2']);
      expect(TelemetryData.getHeaders()).to.be.eql(['header1', 'header2']);
    });

    it('setHeaders should set headers', function () {
      var packet = {
        packet_name: {
          header: 'value'
        }
      };
      TelemetryData.setCurrentState(packet);
      expect(TelemetryData.getCurrentState()).to.be.eql(packet);
    });
  });

  describe('setCurrentStateFromString', function () {
    it('should set the current state based on the results for packet parser', function () {
      var headers = ['header'];
      var state_string = 'value';
      var current_state = {
        packet_name: {
          header: 'value'
        }
      };

      TelemetryData.setHeaders(headers);
      PacketParser.parseData.returns(current_state);

      TelemetryData.setCurrentStateFromString(state_string);
      expect(PacketParser.parseData).to.have.been.calledWith(state_string);
      expect(TelemetryData.getCurrentState()).to.be.eql(current_state);
    });
  });

  describe('setHeadersFromString', function () {
    it('given a valid string of headers should set the headers array correctly', function () {
      var string = 'header1,header2,header3,header4';
      TelemetryData.setHeadersFromString(string);
      var expected_array = ['header1', 'header2', 'header3', 'header4'];
      expect(TelemetryData.getHeaders()).to.eql(expected_array);
    });

    it('given a string with spaces should set the headers array correctly', function () {
      var string = '   header1 , header2 ,         header3 , header4';
      TelemetryData.setHeadersFromString(string);
      var expected_array = ['header1', 'header2', 'header3', 'header4'];
      expect(TelemetryData.getHeaders()).to.eql(expected_array);
    });

    it('given a string with a single header should set the headers array correctly', function () {
      var string = 'header1';
      TelemetryData.setHeadersFromString(string);
      var expected_array = ['header1'];
      expect(TelemetryData.getHeaders()).to.eql(expected_array);
    });

    it('given an empty string should set the headers array as an empty array', function () {
      TelemetryData.setHeadersFromString('');
      var expected_array = [];
      expect(TelemetryData.getHeaders()).to.eql(expected_array);
    });

    it('given null should set the headers array as an empty array', function () {
      TelemetryData.setHeadersFromString(null);
      var expected_array = [];
      expect(TelemetryData.getHeaders()).to.eql(expected_array);
    });

    it('given undefined should set the headers array as an empty array', function () {
      var result = TelemetryData.setHeadersFromString(undefined);
      var expected_array = [];
      expect(TelemetryData.getHeaders()).to.eql(expected_array);
    });
  });

  describe('emitPackets', function () {
    it('given a valid packets object should emit the events with the correct payload', function () {
      var packet_object = {
        packet_name1: {
          packet_header1: 'packet_value1',
          packet_header2: 'packet_value2'
        },
        packet_name2: {
          packet_header3: 'packet_value3',
          packet_header4: 'packet_value4'
        }
      };

      var callbacks = {
        packet_name1: sinon.spy(),
        packet_name2: sinon.spy()
      };

      TelemetryData.setCurrentState(packet_object);
      TelemetryData.on('packet_name1', callbacks.packet_name1);
      TelemetryData.on('packet_name2', callbacks.packet_name2);

      TelemetryData.emitPackets();

      expect(callbacks.packet_name1).to.have.been.calledWithExactly(packet_object['packet_name1']);
      expect(callbacks.packet_name2).to.have.been.calledWithExactly(packet_object['packet_name2']);
    });

    it('given a packet object with a single packet should emit the event with the correct payload', function () {
      var packet_object = {
        packet_name1: {
          packet_header1: 'packet_value1',
          packet_header2: 'packet_value2'
        }
      };

      var callback = sinon.spy();
      TelemetryData.setCurrentState(packet_object);
      TelemetryData.on('packet_name1', callback);
      TelemetryData.emitPackets();

      expect(callback).to.have.been.calledWithExactly(packet_object['packet_name1']);
    });

    it('given an empty object should not emit any events', function () {
      var original_emitter = TelemetryData.emit;
      TelemetryData.emit = sinon.spy();
      TelemetryData.setCurrentState({});
      TelemetryData.emitPackets();
      expect(TelemetryData.emit).to.have.callCount(0);
      TelemetryData.emit = original_emitter;
    });
  });
});<commit_msg>Renamed test file for telemetry data<commit_after><|endoftext|>