<commit_before>var playerData = {};

game.PlayerEntity = me.Entity.extend({
    init: function(x, y, settings) {
        settings['height'] = 75;
        // call the constructor
        this._super(me.Entity, 'init', [x, y, settings]);

        // set the default horizontal & vertical speed (accel vector)
        this.body.setVelocity(3, 3);

        // set the display to follow our position on both axis
        me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

        // ensure the player is updated even when outside of the viewport
        this.alwaysUpdate = true;

        // define a basic walking animation (using all frames)
        this.renderable.addAnimation("walk",  [0]);
    },

    /* -----

    update the player pos

    ------ */
    update: function(dt) {
        if (me.input.isKeyPressed('left') && me.input.isKeyPressed('up')) {
            this.renderable.angle = Math.PI * 1.75;
            this.body.vel.y -= this.body.accel.y * me.timer.tick;
            this.body.vel.x -= this.body.accel.x * me.timer.tick;
            playerData.orientation = 'northWest';
        }
        else if (me.input.isKeyPressed('left') && me.input.isKeyPressed('down')) {
            this.renderable.angle = Math.PI * -0.75;
            this.body.vel.y += this.body.accel.y * me.timer.tick;
            this.body.vel.x -= this.body.accel.x * me.timer.tick;
            playerData.orientation = 'southWest';
        }
        else if (me.input.isKeyPressed('right') && me.input.isKeyPressed('up')) {
            this.renderable.angle = Math.PI * 0.25;
            this.body.vel.y -= this.body.accel.y * me.timer.tick;
            this.body.vel.x += this.body.accel.x * me.timer.tick;
            playerData.orientation = 'northEast';
        }
        else if (me.input.isKeyPressed('right') && me.input.isKeyPressed('down')) {
            this.renderable.angle = Math.PI * -1.25;
            this.body.vel.y += this.body.accel.y * me.timer.tick;
            this.body.vel.x += this.body.accel.x * me.timer.tick;
            playerData.orientation = 'southEast';
        }
        else if (me.input.isKeyPressed('left')) {
            // flip the sprite on horizontal axis
            // this.renderable.flipX(true);
            // update the entity velocity
            this.renderable.angle = Math.PI * -0.5;
            this.body.vel.x -= this.body.accel.x * me.timer.tick;
            this.body.vel.y = 0;
            playerData.orientation = 'west';
            // change to the walking animation
            // if (!this.renderable.isCurrentAnimation("walk")) {
            //     this.renderable.setCurrentAnimation("walk");
            // }
        } else if (me.input.isKeyPressed('right')) {
            // console.log(this.renderable)
            this.renderable.angle = Math.PI * 0.5;
            this.body.vel.y = 0;
            // unflip the sprite
            // this.renderable.flipX(true);
            // this.renderable.flipY(true);
            // update the entity velocity
            this.body.vel.x += this.body.accel.x * me.timer.tick;
            playerData.orientation = 'east';
        }
        else if (me.input.isKeyPressed('up')) {
            this.body.vel.y -= this.body.accel.y * me.timer.tick;
            this.body.vel.x = 0;
            this.renderable.angle = 0;
            playerData.orientation = 'north';
        }
        else if (me.input.isKeyPressed('down')) {
            this.body.vel.y += this.body.accel.y * me.timer.tick;
            this.body.vel.x = 0;
            this.renderable.angle = Math.PI;
            playerData.orientation = 'south';
        }
        else {
            // this.body.vel.x = 0;
            this.body.vel.y = 0;
            this.body.vel.x = 0;
            this.renderable.setCurrentAnimation("walk");
        }

        if (me.input.isKeyPressed("shoot")) {
            me.game.world.addChild(me.pool.pull("laser", this.pos.x + (this.width / 2 - game.Laser.width / 2), this.pos.y - game.Laser.height))
        }

        // if (me.input.isKeyPressed('jump')) {
        //     // make sure we are not already jumping or falling
        //     if (!this.body.jumping && !this.body.falling) {
        //         // set current vel to the maximum defined value
        //         // gravity will then do the rest
        //         this.body.vel.y = -this.body.maxVel.y * me.timer.tick;
        //         // set the jumping flag
        //         this.body.jumping = true;
        //     }

        // }

        // apply physics to the body (this moves the entity)
        this.body.update(dt);

        // handle collisions against other shapes
        me.collision.check(this);

        // return true if we moved or if the renderable was updated
        return (this._super(me.Entity, 'update', [dt]) || this.body.vel.x !== 0 || this.body.vel.y !== 0);
    },

    /**
     * colision handler
     * (called when colliding with other objects)
     */
    onCollision : function (response, other) {
        // Make all other objects solid
        return true;
    }
});

game.Laser = me.Renderable.extend({
    init: function (x, y) {
        var lazerCords = this.calcLaserOrientation(x, y, playerData.orientation);
        this._super(me.Renderable, "init", [lazerCords.x, lazerCords.y, game.Laser.width, game.Laser.height]);
        this.z = 5;
        var body = this.calcLaserShape();
        this.body = body;

        // this.body = new me.Body(this, ([
        //     new me.Polygon(0, 0, [
        //         new me.Vector2d(0, 0),
        //         new me.Vector2d(this.width, 0),
        //         new me.Vector2d(this.width, this.height),
        //         new me.Vector2d(0, this.height)
        //     ])
        // ]));
        console.log('this.body', this.body.entity)
        console.log('this.body', this.body.entity.body.shapes[0].points)
        this.body.updateBounds();
        this.body.setVelocity(0, 20);
    },

    calcLaserOrientation: function(x, y, playerOrientation) {
      if(playerOrientation === 'south') {
        return {x: x, y: y + 110};
      }
      if(playerOrientation === 'north') {
        return {x: x, y: y - 10};
      }
      if(playerOrientation === 'west') {
        console.log('getting here')
        return {x: x - 60, y: y + 40};
      }
      else {
        return {x: x, y: y}
      }
    },
    calcLaserShape: function() {
      return new me.Body(this, ([
            new me.Polygon(0, 0, [
                new me.Vector2d(-this.height, 0),
                new me.Vector2d(this.height, 0),
                new me.Vector2d(-this.height, this.width),
                new me.Vector2d(this.height, this.width)
            ])
        ]));
    },
    calcLaserDirectionDelta: function(velx, vely, accelX, accelY, playerOrientation, tick) {
      if(playerOrientation === 'south') {
        this.body.setVelocity(0, 20);
        var updatedVelX = 0;
        var updatedVelY = vely + (accelY * tick);
        return {velx: updatedVelX, vely: updatedVelY};
      }
      if(playerOrientation === 'north') {
        this.body.setVelocity(0, 20);
        var updatedVelX = 0;
        var updatedVelY = vely - (accelY * tick);
        return {velx: updatedVelX, vely: updatedVelY};
      }
      if(playerOrientation === 'west') {
        this.body.setVelocity(20, 0);
        var updatedVelX = velx - (accelX * tick);
        var updatedVelY = 0;
        console.log('updatedVelY', updatedVelY)
        return {velx: updatedVelX, vely: updatedVelY};
      }
    },

    draw: function (renderer) {
        var color = renderer.getColor();
        renderer.setColor('#5EFF7E');
        renderer.fillRect(this.pos.x, this.pos.y, this.width, this.height);
        renderer.setColor(color);
    },

    update: function (time) {
        this._super(me.Renderable, "update", [time]);
        var deltas = this.calcLaserDirectionDelta(this.body.vel.x, this.body.vel.y, this.body.accel.x, this.body.accel.y, playerData.orientation, me.timer.tick);
        // this.body.vel.y += this.body.accel.y * me.timer.tick;
        this.body.vel.y = deltas.vely;
        this.body.vel.x = deltas.velx;
        // console.log('this.body.vel.y', this.body.vel.y);
        // this.body.vel.x -= this.body.accel.y * me.timer.tick;

        if (this.pos.y + this.height <= 0) {
            me.game.world.removeChild(this);
        }

        this.body.update();

        return true;
    },
    onCollision: function(response, other) {
        if(response.a.name === 'mainplayer') {
            // console.log('response', response)
            // console.log('other', other)
            return false;
        }
        return true;
    }
});

game.Laser.width = 5;
game.Laser.height = 28;<commit_msg>added more positional data for lasers for various directions<commit_after>var playerData = {orientation: 'north'};

game.PlayerEntity = me.Entity.extend({
    init: function(x, y, settings) {
        settings['height'] = 75;
        // call the constructor
        this._super(me.Entity, 'init', [x, y, settings]);

        // set the default horizontal & vertical speed (accel vector)
        this.body.setVelocity(3, 3);

        // set the display to follow our position on both axis
        me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

        // ensure the player is updated even when outside of the viewport
        this.alwaysUpdate = true;

        // define a basic walking animation (using all frames)
        this.renderable.addAnimation("walk",  [0]);
    },

    /* -----

    update the player pos

    ------ */
    update: function(dt) {
        if (me.input.isKeyPressed('left') && me.input.isKeyPressed('up')) {
            this.renderable.angle = Math.PI * 1.75;
            this.body.vel.y -= this.body.accel.y * me.timer.tick;
            this.body.vel.x -= this.body.accel.x * me.timer.tick;
            playerData.orientation = 'northWest';
        }
        else if (me.input.isKeyPressed('left') && me.input.isKeyPressed('down')) {
            this.renderable.angle = Math.PI * -0.75;
            this.body.vel.y += this.body.accel.y * me.timer.tick;
            this.body.vel.x -= this.body.accel.x * me.timer.tick;
            playerData.orientation = 'southWest';
        }
        else if (me.input.isKeyPressed('right') && me.input.isKeyPressed('up')) {
            this.renderable.angle = Math.PI * 0.25;
            this.body.vel.y -= this.body.accel.y * me.timer.tick;
            this.body.vel.x += this.body.accel.x * me.timer.tick;
            playerData.orientation = 'northEast';
        }
        else if (me.input.isKeyPressed('right') && me.input.isKeyPressed('down')) {
            this.renderable.angle = Math.PI * -1.25;
            this.body.vel.y += this.body.accel.y * me.timer.tick;
            this.body.vel.x += this.body.accel.x * me.timer.tick;
            playerData.orientation = 'southEast';
        }
        else if (me.input.isKeyPressed('left')) {
            // flip the sprite on horizontal axis
            // this.renderable.flipX(true);
            // update the entity velocity
            this.renderable.angle = Math.PI * -0.5;
            this.body.vel.x -= this.body.accel.x * me.timer.tick;
            this.body.vel.y = 0;
            playerData.orientation = 'west';
            // change to the walking animation
            // if (!this.renderable.isCurrentAnimation("walk")) {
            //     this.renderable.setCurrentAnimation("walk");
            // }
        } else if (me.input.isKeyPressed('right')) {
            this.renderable.angle = Math.PI * 0.5;
            this.body.vel.y = 0;
            // unflip the sprite
            // this.renderable.flipX(true);
            // this.renderable.flipY(true);
            // update the entity velocity
            this.body.vel.x += this.body.accel.x * me.timer.tick;
            playerData.orientation = 'east';
        }
        else if (me.input.isKeyPressed('up')) {
            this.body.vel.y -= this.body.accel.y * me.timer.tick;
            this.body.vel.x = 0;
            this.renderable.angle = 0;
            playerData.orientation = 'north';
        }
        else if (me.input.isKeyPressed('down')) {
            this.body.vel.y += this.body.accel.y * me.timer.tick;
            this.body.vel.x = 0;
            this.renderable.angle = Math.PI;
            playerData.orientation = 'south';
        }
        else {
            // this.body.vel.x = 0;
            this.body.vel.y = 0;
            this.body.vel.x = 0;
            this.renderable.setCurrentAnimation("walk");
        }

        if (me.input.isKeyPressed("shoot")) {
            me.game.world.addChild(me.pool.pull("laser", this.pos.x + (this.width / 2 - game.Laser.width / 2), this.pos.y - game.Laser.height))
        }

        // if (me.input.isKeyPressed('jump')) {
        //     // make sure we are not already jumping or falling
        //     if (!this.body.jumping && !this.body.falling) {
        //         // set current vel to the maximum defined value
        //         // gravity will then do the rest
        //         this.body.vel.y = -this.body.maxVel.y * me.timer.tick;
        //         // set the jumping flag
        //         this.body.jumping = true;
        //     }

        // }

        // apply physics to the body (this moves the entity)
        this.body.update(dt);

        // handle collisions against other shapes
        me.collision.check(this);

        // return true if we moved or if the renderable was updated
        return (this._super(me.Entity, 'update', [dt]) || this.body.vel.x !== 0 || this.body.vel.y !== 0);
    },

    /**
     * colision handler
     * (called when colliding with other objects)
     */
    onCollision : function (response, other) {
        // Make all other objects solid
        return true;
    }
});

game.Laser = me.Renderable.extend({
    init: function (x, y) {
        var lazerCords = this.calcLaserPosition(x, y, playerData.orientation);
        this._super(me.Renderable, "init", [lazerCords.x, lazerCords.y, game.Laser.width, game.Laser.height]);
        this.z = 5;
        var body = this.calcLaserShape();
        this.body = body;

        // this.body = new me.Body(this, ([
        //     new me.Polygon(0, 0, [
        //         new me.Vector2d(0, 0),
        //         new me.Vector2d(this.width, 0),
        //         new me.Vector2d(this.width, this.height),
        //         new me.Vector2d(0, this.height)
        //     ])
        // ]));
        // console.log('this.body', this.body.entity.body.shapes[0].points)
        this.body.updateBounds();
        this.body.setVelocity(0, 20);
    },

    calcLaserPosition: function(x, y, playerOrientation) {
      if(playerOrientation === 'south') {
        return {x: x, y: y + 110};
      }
      if(playerOrientation === 'north') {
        return {x: x, y: y - 10};
      }
      if(playerOrientation === 'west') {
        return {x: x - 70, y: y + 63};
      }
      if(playerOrientation === 'east') {
        return {x: x + 50, y: y + 63};
      }
      if(playerOrientation === 'northWest') {
        return {x: x + 50, y: y + 63};
      }
      else {
        return {x: x, y: y}
      }
    },
    calcLaserShape: function() {
      return new me.Body(this, ([
            new me.Polygon(0, 0, [
                new me.Vector2d(-this.height, 0),
                new me.Vector2d(this.height, 0),
                new me.Vector2d(-this.height, this.width),
                new me.Vector2d(this.height, this.width)
            ])
        ]));
    },
    calcLaserDirectionDelta: function(velx, vely, accelX, accelY, playerOrientation, tick) {
      if(playerOrientation === 'south') {
        this.body.setVelocity(0, 20);
        var updatedVelX = 0;
        var updatedVelY = vely + (accelY * tick);
        return {velx: updatedVelX, vely: updatedVelY};
      }
      else if(playerOrientation === 'north') {
        this.body.setVelocity(0, 20);
        var updatedVelX = 0;
        var updatedVelY = vely - (accelY * tick);
        return {velx: updatedVelX, vely: updatedVelY};
      }
      else if(playerOrientation === 'west') {
        this.body.setVelocity(20, 0);
        var updatedVelX = velx - (accelX * tick);
        var updatedVelY = 0;
        return {velx: updatedVelX, vely: updatedVelY};
      }
      else if(playerOrientation === 'east') {
        this.body.setVelocity(20, 0);
        var updatedVelX = velx + (accelX * tick);
        var updatedVelY = 0;
        return {velx: updatedVelX, vely: updatedVelY};
      }
      else if(playerOrientation === 'northWest') {
        this.body.setVelocity(20, 20);
        var updatedVelX = velx - (accelX * tick);
        var updatedVelY = vely - (accelY * tick);;
        return {velx: updatedVelX, vely: updatedVelY};
      }
    },

    draw: function (renderer) {
        var color = renderer.getColor();
        renderer.setColor('#5EFF7E');
        if(playerData.orientation === 'west') {
            renderer.fillRect(this.pos.x, this.pos.y, this.height, this.width);
        }
        else if(playerData.orientation === 'east') {
            renderer.fillRect(this.pos.x, this.pos.y, this.height, this.width);
        }
        else if(playerData.orientation === 'northWest') {
            renderer.fillRect(this.pos.x, this.pos.y, this.height, this.width);
            // renderer.rotate(Math.PI * 1.50)
            // console.log('renderer', renderer)
        }
        else {
            renderer.fillRect(this.pos.x, this.pos.y, this.width, this.height);
        }
        renderer.setColor(color);
    },

    update: function (time) {
        this._super(me.Renderable, "update", [time]);
        var deltas = this.calcLaserDirectionDelta(this.body.vel.x, this.body.vel.y, this.body.accel.x, this.body.accel.y, playerData.orientation, me.timer.tick);
        // this.body.vel.y += this.body.accel.y * me.timer.tick;
        this.body.vel.y = deltas.vely;
        this.body.vel.x = deltas.velx;
        // console.log('this.body.vel.y', this.body.vel.y);
        // this.body.vel.x -= this.body.accel.y * me.timer.tick;

        if (this.pos.y + this.height <= 0) {
            me.game.world.removeChild(this);
        }

        this.body.update();

        return true;
    },
    onCollision: function(response, other) {
        if(response.a.name === 'mainplayer') {
            return false;
        }
        return true;
    }
});

game.Laser.width = 5;
game.Laser.height = 28;<|endoftext|>


<commit_before>//this is for the player. a basic setup
/**/game.PlayerEntity = me.Entity.extend ({
	init:function(x , y, settings){
       this._super(me.Entity, 'init', [x, y, {
       	image: "player",
       	width: 64,
       	height: 64,
       	spritewidth: "64",
       	spriteheight: "64",
       	getShape: function(){
       		return(new me.Rect(0, 0, 64, 64)).toPolygon();
       	}
       }]);

       this.body.setVelocity(3,20);
//screen will now follow the player
       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){
	// to make sure if the sure is pressing on the key//adds to the position of my x by adding the velocity defined in setVelocity() and multiplying it by me.timer.tick makes the movement smooth
      if(me.input.isKeyPressed("right")) {
        this.body.vel.x += this.body.accel.x * me.timer.tick;
        this.flipX(true);
       }
       else if (me.input.isKeyPressed("left")){
           this.body.vel.x -= this.body.accel.x * me.timer.tick;
           this.flipX (false);
      }else{
      	this.body.vel.x = 0;
      }

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

            if (me.input.isKeyPressed("attack")) {
       	if (!this.renderable.isCurrentAnimation("attack")) {
       		console.log(!this.renderable.isCurrentAnimation("attack"))
// sets animation to attack then once it  over it goes back to idle
       	this.renderable.setCurrentAnimation("attack", "idle");
//once the animation is over the sequence continues from the first animation idle no the one where we last left off from.
       	this.renderable.setAnimationFrame();

       	}

       }

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

           if (me.input.isKeyPressed("attack")) {
       	if (!this.renderable.isCurrentAnimation("attack")) {
       		console.log(!this.renderable.isCurrentAnimation("attack"))
// sets animation to attack then once it  over it goes back to idle
       	this.renderable.setCurrentAnimation("attack", "idle");
//once the animation is over the sequence continues from the first animation idle no the one where we last left off from.
       	this.renderable.setAnimationFrame();

       	}

       }

       this.body.update(delta);

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

});
/**/
game.PlayerBaseEntity = me.Entity.extend({
    init : function(x, y, settings){
       this._super(me.Entity, 'init', [x, y, {
       image:"tower",
    	width:100,
    	height:100,
    	spritewidth:"100",
    	spriteheight:"100",
        getShape:function(){
        return (new me.Rect(0, 0, 100, 100)).toPolygon();

       }

    }]);

    this.broken = false;
    this.health = 10;
    this.alwaysUpdate = true;
    this.body.onCollision = this.onCollision.bind(this);

    this.type = "PlayerBaseEntity";

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

    },

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

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

    onCollision: function(){

    }

});
/**/
game.EnemyBaseEntity = me.Entity.extend({
    init : function(x, y, settings){
       this._super(me.Entity, 'init', [x, y, {
       image:"tower",
    	width:100,
    	height:100,
    	spritewidth:"100",
    	spriteheight:"100",
        getShape:function(){
        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(){

    }

});
<commit_msg>commit 14<commit_after>//this is for the player. a basic setup
/**/game.PlayerEntity = me.Entity.extend ({
	init:function(x , y, settings){
       this._super(me.Entity, 'init', [x, y, {
       	image: "player",
       	width: 64,
       	height: 64,
       	spritewidth: "64",
       	spriteheight: "64",
       	getShape: function(){
       		return(new me.Rect(0, 0, 64, 64)).toPolygon();
       	}
       }]);

       this.body.setVelocity(3,20);
//screen will now follow the player
       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){
	// to make sure if the sure is pressing on the key//adds to the position of my x by adding the velocity defined in setVelocity() and multiplying it by me.timer.tick makes the movement smooth
      if(me.input.isKeyPressed("right")) {
        this.body.vel.x += this.body.accel.x * me.timer.tick;
        this.flipX(true);
       }
// to help my player left ad right
       else if (me.input.isKeyPressed("left")){
           this.body.vel.x -= this.body.accel.x * me.timer.tick;
           this.flipX (false);
      }else{
      	this.body.vel.x = 0;
      }
// so my player will now jump but theres a problem, he only jumps once.
      if (me.input.isKeyPressed("jump") && !this.jumping && !this.falling) {
      	this.jumping = true;
      	this.body.vel.y -= this.body.accel.y * me.timer.tick;
      }
//to make my player attack so he can damage the towers
            if (me.input.isKeyPressed("attack")) {
       	if (!this.renderable.isCurrentAnimation("attack")) {
       		console.log(!this.renderable.isCurrentAnimation("attack"))
// sets animation to attack then once it  over it goes back to idle
       	this.renderable.setCurrentAnimation("attack", "idle");
//once the animation is over the sequence continues from the first animation idle no the one where we last left off from.
       	this.renderable.setAnimationFrame();
       	}
       }

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

           if (me.input.isKeyPressed("attack")) {
       	if (!this.renderable.isCurrentAnimation("attack")) {
       		console.log(!this.renderable.isCurrentAnimation("attack"))
// sets animation to attack then once it  over it goes back to idle
       	this.renderable.setCurrentAnimation("attack", "idle");
//once the animation is over the sequence continues from the first animation idle no the one where we last left off from.
       	this.renderable.setAnimationFrame();

       	}

       }

       this.body.update(delta);

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

});
/**/
game.PlayerBaseEntity = me.Entity.extend({
    init : function(x, y, settings){
       this._super(me.Entity, 'init', [x, y, {
       image:"tower",
    	width:100,
    	height:100,
    	spritewidth:"100",
    	spriteheight:"100",
        getShape:function(){
        return (new me.Rect(0, 0, 100, 100)).toPolygon();

       }

    }]);

    this.broken = false;
    this.health = 10;
    this.alwaysUpdate = true;
    this.body.onCollision = this.onCollision.bind(this);

    this.type = "PlayerBaseEntity";

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

    },

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

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

    onCollision: function(){

    }

});
/**/
game.EnemyBaseEntity = me.Entity.extend({
    init : function(x, y, settings){
       this._super(me.Entity, 'init', [x, y, {
       image:"tower",
    	width:100,
    	height:100,
    	spritewidth:"100",
    	spriteheight:"100",
        getShape:function(){
        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(){

    }

});
<|endoftext|>


<commit_before>game.PlayerEntity = me.Entity.extend({
	// init function is creating my character and holding
	//all of his properties
	init: function(x, y, settings){
		this.setSuper();
		this.setPlayerTimer();
		this.setAttributes();

		this.type = 'PlayerEntity';

	  		//keeps track
	  		this.facing = "right";

	  		this.dead = false;
	  		this.attack = game.data.playerAttack;

	  		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 is my attack animation
	  		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);
	  		this.renderable.setCurrentAnimation("idle");

	},

		setSuper: function() {
			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 yet
		},

		setAttributes: function() {
			this.health = game.data.playerHealth;
             // this.body.setVelocity allows us to set were
			//our player standes
	  		this.body.setVelocity(game.data.playerMoveSpeed, 20);
		},

		// update function works with my PlayerEntity above
		// update function constently updates my PlayerEntity
	update: function(delta){
		this.now = new Date().getTime();

		if(this.health <=0){
			this.dead = true;

		}

		if(me.input.isKeyPressed("right")){
			//sets the position of my X by adding the volocity 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);
			//this else is statement is creating my left key movement
		}else if(me.input.isKeyPressed("left")){
			this.facing = "left";
			this.body.vel.x -=this.body.accel.x * me.timer.tick;
			this.flipX(false);
		}else{
			this.body.vel.x = 0;
		}

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

				//this is my if statement for my attack animation
		if(me.input.isKeyPressed("attack")){
			if(!this.renderable.isCurrentAnimation("attack")){
				//sets current animation to attack and then back to idle
				this.renderable.setCurrentAnimation("attack", "idle");
				//setAnimationFrame is used to start our attack animtion
				//from the beginning
				this.renderable.setAnimationFrame();
			}
		}
		    //these if statements are checking the animation of the character
		else if (this.body.vel.x !== 0 && !this.renderable.isCurrentAnimation("attack")){
			if(!this.renderable.isCurrentAnimation("walk")){
				this.renderable.setCurrentAnimation("walk");
			}

		}else if(!this.renderable.isCurrentAnimation("attack")){
			this.renderable.setCurrentAnimation("idle");
		}

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

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

			//allows my player to lose health
		loseHealth: function(damage){
			this.health = this.health - damage;

		},

		//collideHandler is responsable for make my player
		//collide with the bases
	collideHandler: function(response){
		if(response.b.type==="EnemyBase"){
			var ydif = this.pos.y - response.b.pos.y;
			var xdif = this.pos.x - response.b.pos.x;

		    if(ydif<-40 && xdif< 70 && xdif>-35){
				this.body.falling = false;
				// this.body.vel.y = -1;
			}
			else if(xdif>-35 && this.facing=== "right" && (xdif<0) && ydif>-50){
				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
				     &&(Math.abs(ydif) <=40) &&
				    ( ( (xdif>0) && this.facing==='left') || ( (xdif<0) && this.facing==='right'))
				     ){

				this.lastHit = this.now;
				response.b.loseHealth(game.data.playerAttack);
			}
		}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{
				if(this.faceing==='right'){
					this.body.vel.x = 0;
				}
				// this.pos.x = this.pos.x -1;
			}

			//This if statement is created to make the
			//enemy creep lose health
			if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >=game.data.playerAttackTimer){
				this.lastHit = this.now;
					//if creeps health is less than our attack, execute if statement
				if(response.b.health <= game.data.playerAttack){
					//adds one gold for player
					game.data.gold += 1;

				}

				response.b.losehealth(game.data.playerAttack);
			}
		}
	}
});<commit_msg>finished vid 30<commit_after>game.PlayerEntity = me.Entity.extend({
	// init function is creating my character and holding
	//all of his properties
	init: function(x, y, settings){
		this.setSuper();
		this.setPlayerTimer();
		this.setAttributes();
		this.type = 'PlayerEntity';
		this.setFlags();
		this.addAnimation();

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

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

		setSuper: function() {
			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 yet
		},
		setAttributes: function() {
			this.health = game.data.playerHealth;
             // this.body.setVelocity allows us to set were
			//our player standes
	  		this.body.setVelocity(game.data.playerMoveSpeed, 20);
	  		this.attack = game.data.playerAttack;
		},
		setFlags: function(){
			//keeps track
	  		this.facing = "right";
	  		this.dead = false;
		},
		addAnimation: function(){
			this.renderable.addAnimation("idle", [78]);
	  		this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122,
	  			123, 124, 125], 80);
	  		//this is my attack animation
	  		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);
		},

		// update function works with my PlayerEntity above
		// update function constently updates my PlayerEntity
	update: function(delta){
		this.now = new Date().getTime();

		if(this.health <=0){
			this.dead = true;

		}

		if(me.input.isKeyPressed("right")){
			//sets the position of my X by adding the volocity 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);
			//this else is statement is creating my left key movement
		}else if(me.input.isKeyPressed("left")){
			this.facing = "left";
			this.body.vel.x -=this.body.accel.x * me.timer.tick;
			this.flipX(false);
		}else{
			this.body.vel.x = 0;
		}

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

				//this is my if statement for my attack animation
		if(me.input.isKeyPressed("attack")){
			if(!this.renderable.isCurrentAnimation("attack")){
				//sets current animation to attack and then back to idle
				this.renderable.setCurrentAnimation("attack", "idle");
				//setAnimationFrame is used to start our attack animtion
				//from the beginning
				this.renderable.setAnimationFrame();
			}
		}
		    //these if statements are checking the animation of the character
		else if (this.body.vel.x !== 0 && !this.renderable.isCurrentAnimation("attack")){
			if(!this.renderable.isCurrentAnimation("walk")){
				this.renderable.setCurrentAnimation("walk");
			}

		}else if(!this.renderable.isCurrentAnimation("attack")){
			this.renderable.setCurrentAnimation("idle");
		}

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

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

			//allows my player to lose health
		loseHealth: function(damage){
			this.health = this.health - damage;

		},

		//collideHandler is responsable for make my player
		//collide with the bases
	collideHandler: function(response){
		if(response.b.type==="EnemyBase"){
			var ydif = this.pos.y - response.b.pos.y;
			var xdif = this.pos.x - response.b.pos.x;

		    if(ydif<-40 && xdif< 70 && xdif>-35){
				this.body.falling = false;
				// this.body.vel.y = -1;
			}
			else if(xdif>-35 && this.facing=== "right" && (xdif<0) && ydif>-50){
				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
				     &&(Math.abs(ydif) <=40) &&
				    ( ( (xdif>0) && this.facing==='left') || ( (xdif<0) && this.facing==='right'))
				     ){

				this.lastHit = this.now;
				response.b.loseHealth(game.data.playerAttack);
			}
		}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{
				if(this.faceing==='right'){
					this.body.vel.x = 0;
				}
				// this.pos.x = this.pos.x -1;
			}

			//This if statement is created to make the
			//enemy creep lose health
			if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >=game.data.playerAttackTimer){
				this.lastHit = this.now;
					//if creeps health is less than our attack, execute if statement
				if(response.b.health <= game.data.playerAttack){
					//adds one gold for player
					game.data.gold += 1;

				}

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


<commit_before>game.PlayerEntity = me.Entity.extend({
	init: function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			image: "player",
			width: 64,
			height: 64,
			spritewidth: "64",
			spriteheight: "64",
			getShape: function(){
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
			}
		}]);

		this.body.setVelocity(5, 20);
		//sets movement speed
		//the "20" allows the y-location to change
		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.setCurrentAnimation("idle");
	},

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

		if(this.body.vel.x !== 0){
			if(!this.renderable.isCurrentAnimation("walk")){
				this.renderable.setCurrentAnimation("walk");
			}
		}
		//allows the character to walk
		else{
			this.renderable.setCurrentAnimation("idle");
		}
		//makes the character return to idle when not moving

		this.body.update(delta);

		this._super(me.Entity, "update", [delta]);
		return true;
	}
});
//classes have both entities capitalized, while methods have only the second entity in caps
game.PlayerBaseEntity = me.Entity.extend({
	init : function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function(){
				return (new me.Rect(0, 0, 100, 100)).toPolygon();
			}

		}]);

		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "PlayerBaseEntity";

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

	update:function(delta){
		if(this.health<=0){
			this.broken = true;
			this.renderable.setCurrentAnimation("broken");
		}
		//kills the game if the health reaches or goes below zero
		this.body.update(delta);

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

	onCollision: function(){

	}
});

game.EnemyBaseEntity = me.Entity.extend({
	init : function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function(){
				return (new me.Rect(0, 0, 100, 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;
		//delta represents time
	},

	onCollision: function(){

	}
});
//this second "base" entity is for the enemy tower<commit_msg>Comments added to video 12<commit_after>game.PlayerEntity = me.Entity.extend({
	init: function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			image: "player",
			width: 64,
			height: 64,
			spritewidth: "64",
			spriteheight: "64",
			getShape: function(){
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
			}
		}]);

		this.body.setVelocity(5, 20);
		//sets movement speed
		//the "20" allows the y-location to change
		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.setCurrentAnimation("idle");
	},

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

		if(this.body.vel.x !== 0){
			if(!this.renderable.isCurrentAnimation("walk")){
				this.renderable.setCurrentAnimation("walk");
			}
		}
		//allows the character to walk
		else{
			this.renderable.setCurrentAnimation("idle");
		}
		//makes the character return to idle when not moving

		this.body.update(delta);

		this._super(me.Entity, "update", [delta]);
		return true;
	}
});
//classes have both entities capitalized, while methods have only the second entity in caps
game.PlayerBaseEntity = me.Entity.extend({
	init : function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function(){
				return (new me.Rect(0, 0, 100, 100)).toPolygon();
			}

		}]);

		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "PlayerBaseEntity";

		this.renderable.addAnimation("idle", [0]);
		this.renderable.addAnimation("broken", [1]);
		this.renderable.setCurrentAnimation("idle");
		//adds the animation of the player base to the game screen
	},

	update:function(delta){
		if(this.health<=0){
			this.broken = true;
			this.renderable.setCurrentAnimation("broken");
		}
		//kills the game if the health reaches or goes below zero
		this.body.update(delta);

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

	onCollision: function(){

	}
});

game.EnemyBaseEntity = me.Entity.extend({
	init : function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function(){
				return (new me.Rect(0, 0, 100, 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");
		//adds the animation of the enemy base to the game screen
	},

	update:function(delta){
		if(this.health<=0){
			this.broken = true;
			this.renderable.setCurrentAnimation("broken");
		}
		//renders the base obsolite should it reach zero
		this.body.update(delta);

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

	onCollision: function(){

	}
});
//this second "base" entity is for the enemy tower<|endoftext|>


<commit_before>/*
	GEIESPICTURES - The picture language from chapter 2 of SICP
	Author: Marco Faustinelli (contacts@faustinelli.net)
	Web: http://faustinelli.net/
	     http://faustinelli.wordpress.com/
	Version: 0.1 - Requires Geieslists 1.1 and Geiesvectors 0.1

	The MIT License - Copyright (c) 2016 Geiespictures Project
*/
var P = function(L, V) {
  var make_frame = (origin, edge1, edge2) => L.ArrayToList([origin, edge1, edge2]);
  var origin_frame = frame => L.first(frame);
  var edge1_frame = frame => L.second(frame);
  var edge2_frame = frame => L.third(frame);

  var frame_coord_map = frame => vector =>
    V.add_vect(origin_frame(frame),
               V.add_vect(V.scale_vect(edge1_frame(frame),
                                       V.xcor_vect(vector)),
                          V.scale_vect(edge2_frame(frame),
                                       V.ycor_vect(vector))));

  var make_segment = (start, end) => L.ArrayToList([start, end]);
  var start_segment = segment => L.first(segment);
  var end_segment = segment => L.second(segment);

  // painter(what)(where)(canvasContext)
  var segments_painter = segments => (frame, paintFrame) => (ctx, color) => {
    color = color || '#000000';
    if (paintFrame) frame_painter(frame, ctx, color);
    var canvasWidth = ctx.canvas.clientWidth;
    var canvasHeight = ctx.canvas.clientHeight;
    var newCanvasOriginX = canvasWidth/2;
    var newCanvasOriginY = canvasHeight/2;
    var X = x => x + newCanvasOriginX;
    var Y = y => -(y + newCanvasOriginY) + canvasHeight;
    var draw_segment = segment => {
      ctx.resetTransform();
      ctx.translate(newCanvasOriginX, newCanvasOriginY);
      var coordinateMapper = frame_coord_map(frame);
      var startPoint = coordinateMapper(start_segment(segment));
      var endPoint = coordinateMapper(end_segment(segment));
      ctx.beginPath();
      //ctx.moveTo(X(V.xcor_vect(startPoint)), Y(V.ycor_vect(startPoint)));
      //ctx.lineTo(X(V.xcor_vect(endPoint)), Y(V.ycor_vect(endPoint)));
      ctx.moveTo(V.xcor_vect(startPoint), V.ycor_vect(startPoint));
      ctx.lineTo(V.xcor_vect(endPoint), V.ycor_vect(endPoint));
      ctx.strokeStyle = color;
      ctx.stroke();
      ctx.resetTransform();
    }
    segments.forEach(draw_segment);
  }

  var transform_painter = (painter, origin, xAxe, yAxe) => (frame, paintFrame) => {
    var mapper = frame_coord_map(frame);
    var newFrame = P.make_frame(mapper(origin),
                                V.sub_vect(mapper(xAxe),mapper(origin)),
                                V.sub_vect(mapper(yAxe),mapper(origin)))
    return painter(newFrame, paintFrame);
  }

  var flip_vert = painter => transform_painter(painter,
                                               V.make_vect(0,1), // new origin
                                               V.make_vect(1,1), // new END of xAxe
                                               V.make_vect(0,0));// new END of yAxe

  var flip_horiz = painter => transform_painter(painter,
                                               V.make_vect(1,0), // new origin
                                               V.make_vect(0,0), // new END of xAxe
                                               V.make_vect(1,1));// new END of yAxe

  var shrink_to_upper_right_naive = painter => (frame, paintFrame) => {
    var mapper = frame_coord_map(frame);
    var newOrigin = V.make_vect(.5,.5); // new origin
    var newXAxis = V.make_vect(.5,0);  // new xAxe
    var newYAxis = V.make_vect(0,.5); // new yAxe
    var newFrame = make_frame(V.add_vect(origin_frame(frame),mapper(newOrigin)),
                              mapper(newXAxis),
                              mapper(newYAxis));
    return painter(newFrame, paintFrame);
  }

  var flip_vert_naive = painter => (frame, paintFrame) => {
    var mapper = frame_coord_map(frame);
    var newOrigin = V.make_vect(0,1); // new origin
    var newXAxis = V.make_vect(1,0);  // new xAxe
    var newYAxis = V.make_vect(0,-1); // new yAxe
    var newFrame = make_frame(V.add_vect(origin_frame(frame),mapper(newOrigin)),
                              mapper(newXAxis),
                              mapper(newYAxis));
    return painter(newFrame, paintFrame);
  }

  var flip_horiz_naive = painter => (frame, paintFrame) => {
    var newOrigin = V.make_vect(1,0);
    var newXSide = V.make_vect(-1,0);
    var newYSide = V.make_vect(0,1);
    var mapper = frame_coord_map(frame);
    var newFrame = make_frame(V.add_vect(origin_frame(frame),mapper(newOrigin)),
                              mapper(newXSide),
                              mapper(newYSide));
    return painter(newFrame,paintFrame);
  }

  // paints also rotated/skewed frames
  var frame_painter = (frame, ctx, color) => {
    var frameAxes =
      [
        make_segment(V.make_vect(0,0),V.make_vect(1,0)),        // x-axis
        make_segment(V.make_vect(1,0),V.make_vect(.95,.05)),    // x-arrow
        make_segment(V.make_vect(1,0),V.make_vect(.95,-.05)),   // x-arrow
        make_segment(V.make_vect(.95,.1),V.make_vect(.98,.16)), // x
        make_segment(V.make_vect(.95,.16),V.make_vect(.98,.1)), // x
        make_segment(V.make_vect(0,0),V.make_vect(0,1)),        // y-axis
        make_segment(V.make_vect(0,1),V.make_vect(-.05,.95)),   // y-arrow
        make_segment(V.make_vect(0,1),V.make_vect(.05,.95)),    // y-arrow
        make_segment(V.make_vect(.08,.92),V.make_vect(.13,.98)),// y
        make_segment(V.make_vect(.08,.98),V.make_vect(.1,.95))  // y
      ];
    segments_painter(frameAxes)(frame)(ctx, color);
  }

  var diamond_painter = (frame, paintFrame) => (ctx, color) => {
    var diamondPieces =
      [
        make_segment(V.make_vect(.14,.50),V.make_vect(.50,.86)),
        make_segment(V.make_vect(.50,.86),V.make_vect(.86,.50)),
        make_segment(V.make_vect(.86,.50),V.make_vect(.50,.14)),
        make_segment(V.make_vect(.50,.14),V.make_vect(.14,.50)),

        make_segment(V.make_vect(.28,.50),V.make_vect(.50,.72)),
        make_segment(V.make_vect(.50,.72),V.make_vect(.72,.50)),
        make_segment(V.make_vect(.72,.50),V.make_vect(.50,.28)),
        make_segment(V.make_vect(.50,.28),V.make_vect(.28,.50)),

        make_segment(V.make_vect(.42,.50),V.make_vect(.50,.58)),
        make_segment(V.make_vect(.50,.58),V.make_vect(.58,.50)),
        make_segment(V.make_vect(.58,.50),V.make_vect(.50,.42)),
        make_segment(V.make_vect(.50,.42),V.make_vect(.42,.50)),
        make_segment(V.make_vect(.5,.5),V.make_vect(1,1))
      ];
    segments_painter(diamondPieces)(frame, paintFrame)(ctx, color);
  }

  var picture_painter = img => (frame, paintFrame) => (ctx) => {
    ctx.resetTransform();

    var imgWidth = img.width;
    var imgHeight = img.height;
    var canvasWidth = ctx.canvas.clientWidth;
    var canvasHeight = ctx.canvas.clientHeight;
    var frameWidth = V.length_vect(edge1_frame(frame));
    var frameHeight = V.length_vect(edge2_frame(frame));

    var newCanvasOriginX = canvasWidth/2;
    var newCanvasOriginY = canvasHeight/2;
    ctx.translate(newCanvasOriginX, newCanvasOriginY);

    var mapper = frame_coord_map(frame);
    var frameOriginX = V.xcor_vect(origin_frame(frame));
    var frameOriginY = V.ycor_vect(origin_frame(frame));
    //ctx.translate(frameOriginX, -frameOriginY);
    ctx.translate(frameOriginX, frameOriginY);

    // currently ignoring skewed y-axes
    var frameRotation = V.angle_vect(edge1_frame(frame));
    ctx.rotate(frameRotation);

    var imgWidthScale = frameWidth/imgWidth;
    var imgHeightScale = frameHeight/imgHeight;
    ctx.scale(imgWidthScale, imgHeightScale);

    // transform(a,b,c,d,e,f) = (hor.scal., hor.skew., vertskew., vert.scal., hor.mov., vert.mov.)
    ctx.drawImage(img,0,0);
    ctx.resetTransform();
    if (paintFrame) frame_painter(frame, ctx);
  }

  return {
    make_frame: make_frame,
    origin_frame: origin_frame,
    edge1_frame: edge1_frame,
    edge2_frame: edge2_frame,
    frame_coord_map: frame_coord_map,
    make_segment: make_segment,
    segments_painter: segments_painter,
    picture_painter: picture_painter,
    diamond_painter: diamond_painter,
    flip_vert: flip_vert,
    flip_vert_naive: flip_vert_naive,
    flip_horiz_naive: flip_horiz_naive,
    shrink_to_upper_right_naive: shrink_to_upper_right_naive
  }
}(L, V);
<commit_msg>relative mapper implemented<commit_after>/*
	GEIESPICTURES - The picture language from chapter 2 of SICP
	Author: Marco Faustinelli (contacts@faustinelli.net)
	Web: http://faustinelli.net/
	     http://faustinelli.wordpress.com/
	Version: 0.1 - Requires Geieslists 1.1 and Geiesvectors 0.1

	The MIT License - Copyright (c) 2016 Geiespictures Project
*/
var P = function(L, V) {
  var make_frame = (origin, edge1, edge2) => L.ArrayToList([origin, edge1, edge2]);
  var origin_frame = frame => L.first(frame);
  var edge1_frame = frame => L.second(frame);
  var edge2_frame = frame => L.third(frame);

  // canvas pixels relative to center of canvas
  var frame_coord_map = frame => vector =>
    V.add_vect(origin_frame(frame),
               V.add_vect(V.scale_vect(edge1_frame(frame),
                                       V.xcor_vect(vector)),
                          V.scale_vect(edge2_frame(frame),
                                       V.ycor_vect(vector))));
  // canvas pixels relative to center of frame
  var rel_frame_coord_map = frame => vector =>
    V.add_vect(V.scale_vect(edge1_frame(frame),
                           V.xcor_vect(vector)),
              V.scale_vect(edge2_frame(frame),
                           V.ycor_vect(vector)));

  var make_segment = (start, end) => L.ArrayToList([start, end]);
  var start_segment = segment => L.first(segment);
  var end_segment = segment => L.second(segment);

  // painter(what)(where)(canvasContext)
  var segments_painter = segments => (frame, paintFrame) => (ctx, color) => {
    color = color || '#000000';
    if (paintFrame) frame_painter(frame, ctx, color);
    var canvasWidth = ctx.canvas.clientWidth;
    var canvasHeight = ctx.canvas.clientHeight;
    var newCanvasOriginX = canvasWidth/2;
    var newCanvasOriginY = canvasHeight/2;
    var X = x => x + newCanvasOriginX;
    var Y = y => -(y + newCanvasOriginY) + canvasHeight;
    var draw_segment = segment => {
      ctx.resetTransform();
      ctx.translate(newCanvasOriginX, newCanvasOriginY);
      var coordinateMapper = frame_coord_map(frame);
      var startPoint = coordinateMapper(start_segment(segment));
      var endPoint = coordinateMapper(end_segment(segment));
      ctx.beginPath();
      //ctx.moveTo(X(V.xcor_vect(startPoint)), Y(V.ycor_vect(startPoint)));
      //ctx.lineTo(X(V.xcor_vect(endPoint)), Y(V.ycor_vect(endPoint)));
      ctx.moveTo(V.xcor_vect(startPoint), V.ycor_vect(startPoint));
      ctx.lineTo(V.xcor_vect(endPoint), V.ycor_vect(endPoint));
      ctx.strokeStyle = color;
      ctx.stroke();
      ctx.resetTransform();
    }
    segments.forEach(draw_segment);
  }

  var transform_painter = (painter, origin, xAxe, yAxe) => (frame, paintFrame) => {
    var mapper = frame_coord_map(frame);
    var newFrame = P.make_frame(mapper(origin),
                                V.sub_vect(mapper(xAxe),mapper(origin)),
                                V.sub_vect(mapper(yAxe),mapper(origin)))
    return painter(newFrame, paintFrame);
  }

  var flip_vert = painter => transform_painter(painter,
                                               V.make_vect(0,1), // new origin
                                               V.make_vect(1,1), // new END of xAxe
                                               V.make_vect(0,0));// new END of yAxe

  var flip_horiz = painter => transform_painter(painter,
                                               V.make_vect(1,0), // new origin
                                               V.make_vect(0,0), // new END of xAxe
                                               V.make_vect(1,1));// new END of yAxe

  var shrink_to_upper_right_naive = painter => (frame, paintFrame) => {
    var mapper = frame_coord_map(frame);
    var newOrigin = V.make_vect(.5,.5); // new origin
    var newXAxis = V.make_vect(.5,0);  // new xAxe
    var newYAxis = V.make_vect(0,.5); // new yAxe
    var newFrame = make_frame(V.add_vect(origin_frame(frame),mapper(newOrigin)),
                              mapper(newXAxis),
                              mapper(newYAxis));
    return painter(newFrame, paintFrame);
  }

  var flip_vert_naive = painter => (frame, paintFrame) => {
    var mapper = frame_coord_map(frame);
    var newOrigin = V.make_vect(0,1); // new origin
    var newXAxis = V.make_vect(1,0);  // new xAxe
    var newYAxis = V.make_vect(0,-1); // new yAxe
    var newFrame = make_frame(V.add_vect(origin_frame(frame),mapper(newOrigin)),
                              mapper(newXAxis),
                              mapper(newYAxis));
    return painter(newFrame, paintFrame);
  }

  var flip_horiz_naive = painter => (frame, paintFrame) => {
    var newOrigin = V.make_vect(1,0);
    var newXSide = V.make_vect(-1,0);
    var newYSide = V.make_vect(0,1);
    var mapper = frame_coord_map(frame);
    var newFrame = make_frame(V.add_vect(origin_frame(frame),mapper(newOrigin)),
                              mapper(newXSide),
                              mapper(newYSide));
    return painter(newFrame,paintFrame);
  }

  // paints also rotated/skewed frames
  var frame_painter = (frame, ctx, color) => {
    var frameAxes =
      [
        make_segment(V.make_vect(0,0),V.make_vect(1,0)),        // x-axis
        make_segment(V.make_vect(1,0),V.make_vect(.95,.05)),    // x-arrow
        make_segment(V.make_vect(1,0),V.make_vect(.95,-.05)),   // x-arrow
        make_segment(V.make_vect(.95,.1),V.make_vect(.98,.16)), // x
        make_segment(V.make_vect(.95,.16),V.make_vect(.98,.1)), // x
        make_segment(V.make_vect(0,0),V.make_vect(0,1)),        // y-axis
        make_segment(V.make_vect(0,1),V.make_vect(-.05,.95)),   // y-arrow
        make_segment(V.make_vect(0,1),V.make_vect(.05,.95)),    // y-arrow
        make_segment(V.make_vect(.08,.92),V.make_vect(.13,.98)),// y
        make_segment(V.make_vect(.08,.98),V.make_vect(.1,.95))  // y
      ];
    segments_painter(frameAxes)(frame)(ctx, color);
  }

  var diamond_painter = (frame, paintFrame) => (ctx, color) => {
    var diamondPieces =
      [
        make_segment(V.make_vect(.14,.50),V.make_vect(.50,.86)),
        make_segment(V.make_vect(.50,.86),V.make_vect(.86,.50)),
        make_segment(V.make_vect(.86,.50),V.make_vect(.50,.14)),
        make_segment(V.make_vect(.50,.14),V.make_vect(.14,.50)),

        make_segment(V.make_vect(.28,.50),V.make_vect(.50,.72)),
        make_segment(V.make_vect(.50,.72),V.make_vect(.72,.50)),
        make_segment(V.make_vect(.72,.50),V.make_vect(.50,.28)),
        make_segment(V.make_vect(.50,.28),V.make_vect(.28,.50)),

        make_segment(V.make_vect(.42,.50),V.make_vect(.50,.58)),
        make_segment(V.make_vect(.50,.58),V.make_vect(.58,.50)),
        make_segment(V.make_vect(.58,.50),V.make_vect(.50,.42)),
        make_segment(V.make_vect(.50,.42),V.make_vect(.42,.50)),
        make_segment(V.make_vect(.5,.5),V.make_vect(1,1))
      ];
    segments_painter(diamondPieces)(frame, paintFrame)(ctx, color);
  }

  var picture_painter = img => (frame, paintFrame) => (ctx) => {
    ctx.resetTransform();

    var imgWidth = img.width;
    var imgHeight = img.height;
    var canvasWidth = ctx.canvas.clientWidth;
    var canvasHeight = ctx.canvas.clientHeight;
    var frameWidth = V.length_vect(edge1_frame(frame));
    var frameHeight = V.length_vect(edge2_frame(frame));

    var newCanvasOriginX = canvasWidth/2;
    var newCanvasOriginY = canvasHeight/2;
    ctx.translate(newCanvasOriginX, newCanvasOriginY);

    var mapper = frame_coord_map(frame);
    var frameOriginX = V.xcor_vect(origin_frame(frame));
    var frameOriginY = V.ycor_vect(origin_frame(frame));
    //ctx.translate(frameOriginX, -frameOriginY);
    ctx.translate(frameOriginX, frameOriginY);

    // currently ignoring skewed y-axes
    var frameRotation = V.angle_vect(edge1_frame(frame));
    ctx.rotate(frameRotation);

    var imgWidthScale = frameWidth/imgWidth;
    var imgHeightScale = frameHeight/imgHeight;
    ctx.scale(imgWidthScale, imgHeightScale);

    // transform(a,b,c,d,e,f) = (hor.scal., hor.skew., vertskew., vert.scal., hor.mov., vert.mov.)
    ctx.drawImage(img,0,0);
    ctx.resetTransform();
    if (paintFrame) frame_painter(frame, ctx);
  }

  return {
    make_frame: make_frame,
    origin_frame: origin_frame,
    edge1_frame: edge1_frame,
    edge2_frame: edge2_frame,
    frame_coord_map: frame_coord_map,
    make_segment: make_segment,
    segments_painter: segments_painter,
    picture_painter: picture_painter,
    diamond_painter: diamond_painter,
    flip_vert: flip_vert,
    flip_vert_naive: flip_vert_naive,
    flip_horiz_naive: flip_horiz_naive,
    shrink_to_upper_right_naive: shrink_to_upper_right_naive
  }
}(L, V);
<|endoftext|>


<commit_before>var gameModule = angular.module('app', []).
	controller("gameTheoryControl", function gameTheoryControl($scope){

	    	function number(num){
	    		this.name = num;
	    		this.selected = false;
	    		return this;
	    	}

	    	$scope.numbers=[];
	    	$scope.solutions=[];

	    	$scope.getStarter = function(){
	    		var isEven = ($scope.solutions.length % 2) == 0;

	    		if(isEven){
	    			return "Alice";
	    		}
	    		else{
	    			return "Bob";
	    		}
	    	}

	    	function solution(x, parts){
	    		this.number = x;
	    		this.parts = parts;
	    	}

	    	$scope.amount = 5;

	    	$scope.newNumbers = function(){
			$scope.numbers = [];

			intAmount = parseInt($scope.amount);

			for(var i = 1; i < intAmount + 1; i++){
				$scope.numbers.push(new number(i));
			}
		}

		$scope.deleteSelected = function(){
			for(var num in $scope.numbers){
				if($scope.numbers[num].selected){
					$scope.numbers.splice(num, 1);
					num--;
				}
			}
		}

		function sumNumbers(numbers){
			var num = 0;
			for(var i = 0; i < numbers.length; i++){
				num += parseInt(numbers[i].name);
			}
			return num;
		}

		function sumOf(parts){
			var num = 0;
			for(var i = 0; i < parts.length; i++){
				num += parts[i];
			}
			return num;
		}

		function getSmallerNumbers(number){
			var newArray = [];
			for(var i = 0; i < $scope.numbers.length; i++){
				if($scope.numbers[i].name <= number){
					newArray.push($scope.numbers[i].name);
				}
				else{
					break;
				}
			}
			return newArray;
		}

		/*var getCombinations = function(startArray, arrayOfNumbers){
			var results = [];
			for(var i = 0; i < arrayOfNumbers.length; i++){
				results.push(startArray.concat(arrayOfNumbers[i]));

				var tempArray = [];
				for(var j = i + 1; j < arrayOfNumbers.length; j++){
					tempArray.push(arrayOfNumbers[j]);
				}

				results = results.concat(getCombinations(startArray.concat(arrayOfNumbers[i]), tempArray));
			}
			return results;
		}*/

		var getResult = function(startArray, arrayOfNumbers, expected){
			var results = [];
			for(var i = arrayOfNumbers.length - 1; i > -1; i--){
				results.push(startArray.concat(arrayOfNumbers[i]));
				if(sumOf(startArray.concat(arrayOfNumbers[i]))==expected){
					return {result: true, values: startArray.concat(arrayOfNumbers[i])};
				}

				var tempArray = [];
				for(var j = 0; j < i; j++){
					tempArray.push(arrayOfNumbers[j]);
				}

				var newCombinations = getResult(startArray.concat(arrayOfNumbers[i]), tempArray, expected);
				if(newCombinations.result == true){return newCombinations;}
				else{
					results = results.concat(newCombinations);
				}
			}
			return results;
		}

		$scope.getSolutions = function(){
			$scope.solutions = [];
			var calculable = true;
			var currentNumber = 1;

			while(calculable && currentNumber <= sumNumbers($scope.numbers)){
				parts = [];

				var solved = false;

				var smallerNums = getSmallerNumbers(currentNumber);

				if(smallerNums.length == 0){
					calculable = false; break;
				}

				for(var i = 0; i < $scope.numbers.length; i++){
					if($scope.numbers[i].name == currentNumber)
					{
						solved = true;
						$scope.solutions.push(new solution(currentNumber, [$scope.numbers[i].name]));
					}
				}

				if(!solved){
					var returnses = getResult([], smallerNums, currentNumber);
					if(returnses.result == true){
						$scope.solutions.push(new solution(currentNumber, returnses.values));
						solved = true;
					}
					else{
						calculable = false; break;
					}
				}

				/*if(!solved){
					var combinations = getCombinations([], smallerNums);

						for(var i = 0; i < combinations.length; i++){
							if(sumOf(combinations[i]) == currentNumber){
								$scope.solutions.push(new solution(currentNumber, combinations[i]));
								solved = true;
								break;
							}
							if(solved){break;}
						}

					if(!solved){
						calculable = false; break;
					}
				}*/

				currentNumber++;
			}
		}

		$scope.newNumbers();

	});
<commit_msg>Update gameTheoryController.js<commit_after>var gameModule = angular.module('app', []).
	controller("gameTheoryControl", function gameTheoryControl($scope){

	    	function number(num){
	    		this.name = num;
	    		this.selected = false;
	    		return this;
	    	}

	    	$scope.numbers=[];
	    	$scope.solutions=[];

	    	$scope.getStarter = function(){
	    		var isEven = ($scope.solutions.length % 2) == 0;

	    		if(isEven){
	    			return "Alice";
	    		}
	    		else{
	    			return "Bob";
	    		}
	    	}

	    	function solution(x, parts){
	    		this.number = x;
	    		this.parts = parts;
	    	}

	    	$scope.amount = 5;

	    	$scope.newNumbers = function(){
			$scope.numbers = [];

			intAmount = parseInt($scope.amount);

			for(var i = 1; i < intAmount + 1; i++){
				$scope.numbers.push(new number(i));
			}
		}

		$scope.deleteSelected = function(){
			for(var num in $scope.numbers){
				if($scope.numbers[num].selected){
					$scope.numbers.splice(num, 1);
					num--;
				}
			}
		}

		function sumNumbers(numbers){
			var num = 0;
			for(var i = 0; i < numbers.length; i++){
				num += parseInt(numbers[i].name);
			}
			return num;
		}

		function sumOf(parts){
			var num = 0;
			for(var i = 0; i < parts.length; i++){
				num += parts[i];
			}
			return num;
		}

		function getSmallerNumbers(number){
			var newArray = [];
			for(var i = 0; i < $scope.numbers.length; i++){
				if($scope.numbers[i].name <= number){
					newArray.push($scope.numbers[i].name);
				}
				else{
					break;
				}
			}
			return newArray;
		}

		/*var getCombinations = function(startArray, arrayOfNumbers){
			var results = [];
			for(var i = 0; i < arrayOfNumbers.length; i++){
				results.push(startArray.concat(arrayOfNumbers[i]));

				var tempArray = [];
				for(var j = i + 1; j < arrayOfNumbers.length; j++){
					tempArray.push(arrayOfNumbers[j]);
				}

				results = results.concat(getCombinations(startArray.concat(arrayOfNumbers[i]), tempArray));
			}
			return results;
		}*/

		var getResult = function(startArray, arrayOfNumbers, expected){
			var results = [];
			for(var i = arrayOfNumbers.length - 1; i > -1; i--){
				results.push(startArray.concat(arrayOfNumbers[i]));
				if(sumOf(startArray.concat(arrayOfNumbers[i]))==expected){
					return {result: true, values: startArray.concat(arrayOfNumbers[i])};
				}

				var tempArray = [];
				for(var j = 0; j < i; j++){
					tempArray.push(arrayOfNumbers[j]);
				}

				var newCombinations = getResult(startArray.concat(arrayOfNumbers[i]), tempArray, expected);
				if(newCombinations.result == true){return newCombinations;}
				else{
					results = results.concat(newCombinations);
				}
			}
			return results;
		}

		$scope.getSolutions = function(){
			$scope.solutions = [];
			var calculable = true;
			var currentNumber = 1;

			var maxNumber = sumNumbers($scope.numbers);

			while(calculable && currentNumber <= maxNumber){
				parts = [];

				var solved = false;

				var smallerNums = getSmallerNumbers(currentNumber);

				if(smallerNums.length == 0){
					calculable = false; break;
				}

				for(var i = 0; i < $scope.numbers.length; i++){
					if($scope.numbers[i].name == currentNumber)
					{
						solved = true;
						$scope.solutions.push(new solution(currentNumber, [$scope.numbers[i].name]));
					}
				}

				if(!solved){
					var returnses = getResult([], smallerNums, currentNumber);
					if(returnses.result == true){
						$scope.solutions.push(new solution(currentNumber, returnses.values));
						solved = true;
					}
					else{
						calculable = false; break;
					}
				}

				/*if(!solved){
					var combinations = getCombinations([], smallerNums);

						for(var i = 0; i < combinations.length; i++){
							if(sumOf(combinations[i]) == currentNumber){
								$scope.solutions.push(new solution(currentNumber, combinations[i]));
								solved = true;
								break;
							}
							if(solved){break;}
						}

					if(!solved){
						calculable = false; break;
					}
				}*/

				currentNumber++;
			}
		}

		$scope.newNumbers();

	});
<|endoftext|>


<commit_before>/**
 * Knob - jQuery Plugin
 * Nice, configurable, backward compatible knob UI component
 *
 * Copyright (c) 2011 - 2013 Anthony Terrien

 * Version: 1.0.0 (23/11/2011)
 * Requires: jQuery v1.7+
 *
 * Under MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */
$(function() {

    $.fn.knob = function( gopt ) {

        return this.each(

                    function() {

                        var $this = $(this);

                        if( $this.data('knobed') ) return $this;
                        $this.data('knobed',true);

                        var opt = $.extend(
                                        {
                                            'min' : $this.data('min') || 0
                                            ,'max' : $this.data('max') || 100
                                            ,'cursor' : $this.data('cursor')
                                            ,'thickness' : $this.data('thickness') || .3
                                            ,'width' : $this.data('width') || 200
                                            ,'displayInput' : $this.data('displayinput')==null || $this.data('displayinput')
                                            ,'fgColor' : $this.data('fgcolor') || '#87CEEB' //#222222'
                                            ,'bgColor' : $this.data('bgcolor') || '#EEEEEE'
                                            ,'readOnly' : $this.data('readonly')
                                            ,'draw' :
                                                    /**
                                                     * @param int a angle
                                                     * @param int v current value
                                                     * @param array opt plugin options
                                                     * @param context ctx Canvas context 2d
                                                     */
                                                    function( a, v, opt, ctx ) {
                                                            var sa = 1.5*Math.PI
                                                                ,ea = sa+a
                                                                ,r = opt.width/2
                                                                ,lw = r*opt.thickness;

                                                            ctx.clearRect(0, 0, opt.width, opt.width);
                                                            ctx.lineWidth = lw;

                                                            opt.cursor
                                                                && ( sa = ea-0.3 )
                                                                && ( ea = ea+0.3 );

                                                            ctx.beginPath();
                                                            ctx.strokeStyle = opt.fgColor;
                                                            ctx.arc( r, r, r-lw, sa, ea, false);
                                                            ctx.stroke();

                                                            ctx.beginPath();
                                                            ctx.strokeStyle = opt.bgColor;
                                                            ctx.arc(
                                                                        r, r, r-lw ,sa
                                                                        ,(v==opt.min && !opt.cursor)
                                                                            ? sa+0.0001
                                                                            : ea
                                                                        , true
                                                                    );
                                                            ctx.stroke();
                                                        }
                                            ,'change' :
                                                    /**
                                                     * @param int v Current value
                                                     */
                                                    function(v) {}
                                            ,'release' :
                                                    /**
                                                     * @param int v Current value
                                                     */
                                                    function(v) {}
                                        }
                                        ,gopt
                                    );

                        var c = $('<canvas width="'+opt.width+'" height="'+opt.width+'"></canvas>')
                            ,wd = $('

')
                            ,k;

                        $this.wrap( wd ).before( c );

                        opt.displayInput
                        && $this.css(
                                    {
                                    'width' : opt.width/2+'px'
                                    ,'position' : 'absolute'
                                    ,'margin-top' : (opt.width*5/13)+'px'
                                    ,'margin-left' : '-'+3*opt.width/4+'px'
                                    ,'font-size' : opt.width/5+'px'
                                    ,'border' : 'none'
                                    ,'background' : 'none'
                                    ,'font-family' : 'Arial'
                                    ,'font-weight' : 'bold'
                                    ,'text-align' : 'center'
                                    ,'color' : 'lightgrey'
                                    ,'padding' : '0px'
                                    ,'-webkit-appearance': 'none'
                                    }
                                )
                        || $this.css(
                                    {
                                    'width' : '0px'
                                    , 'visibility' : 'hidden'
                                    }
                                );

                        k = new Knob( c, opt );
                        k.onRelease = opt.release;
                        k.val( parseInt($this.val()) || 0 );
                        k.onChange = function(v) {
                                                    $this.val(v);
                                                    opt.change(v);
                                                 };

                        if( !opt.readOnly ){
                            c.bind(
                                "mousedown touchstart"
                                ,function( e ) {
                                    e.preventDefault();
                                    k.startDrag( e );
                                }
                            );
                        }else{
                            $this.attr('readonly','readonly');
                        }

                        var keys={37: -1, 38:1, 39:1, 40: -1}

                        $this.keydown(function(event){
                            setVal( keys[event.keyCode])
                        });

                        $this.bind('mousewheel DOMMouseScroll', function(event){
                            var deltaX = event.originalEvent.wheelDeltaX;
                            var deltaY = event.originalEvent.wheelDeltaY;
                            event.preventDefault();
                            setVal( deltaX > 0 ||  deltaY > 0 ? 1 : deltaX < 0 ||  deltaY < 0 ? -1 : 0)
                        });

                        function setVal(dir){
                            if(dir){
                                k.val( parseInt($this.val()) + dir )
                            }
                        }
                    }
                ).parent();
    }

    Knob = function( c, opt ) {

        var v = null
            ,ctx = c[0].getContext("2d")
            ,a = Math.PI*0.0001
            ,PI2 = 2*Math.PI
            ,mx ,my ,x ,y
            ,_self = this;

        this.onChange = function() {}
        this.onRelease = function() {}

        this.val = function(_v) {
            if(null!=_v){
                if( v==_v ) return;
                v=_v;
                this.onChange(_v);
                a = (_v-opt.min)*PI2/(opt.max-opt.min);
                opt.draw( a, _v, opt, ctx );
            }else{
                var b = a = Math.atan2( mx-x, -(my-y-opt.width/2) );
                (a<0) && (b=a+PI2);
                 _v = Math.round( b*(opt.max-opt.min)/PI2 ) + opt.min;
                return ( _v>opt.max ) ? opt.max : _v;
            }
        }

        this.capture = function(e) {
            switch( e.type ){
                case 'mousemove' :
                case 'mousedown' :
                    mx = e.pageX;
                    my = e.pageY;
                    break;
                case 'touchmove' :
                case 'touchstart' :
                    mx = e.originalEvent.touches[0].pageX;
                    my = e.originalEvent.touches[0].pageY;
                    break;
            }
            this.val( this.val() );
        }

        this.startDrag = function(e) {

            var p = c.position();
            x = p.left+(opt.width/2);
            y = p.top;

            this.capture(e);

            $(document).bind(
                            "mousemove.knob touchmove.knob"
                            ,function(e) {
                                _self.capture(e);
                            }
                        )
                        .bind(
                            "mouseup.knob touchend.knob"
                            ,function() {
                                $(document).unbind('mousemove.knob touchmove.knob mouseup.knob touchend.knob');
                                _self.onRelease(v);
                            }
                        );
        }
    }
});<commit_msg>add support for old event.detail property<commit_after>/**
 * Knob - jQuery Plugin
 * Nice, configurable, backward compatible knob UI component
 *
 * Copyright (c) 2011 - 2013 Anthony Terrien

 * Version: 1.0.0 (23/11/2011)
 * Requires: jQuery v1.7+
 *
 * Under MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */
$(function() {

    $.fn.knob = function( gopt ) {

        return this.each(

                    function() {

                        var $this = $(this);

                        if( $this.data('knobed') ) return $this;
                        $this.data('knobed',true);

                        var opt = $.extend(
                                        {
                                            'min' : $this.data('min') || 0
                                            ,'max' : $this.data('max') || 100
                                            ,'cursor' : $this.data('cursor')
                                            ,'thickness' : $this.data('thickness') || .3
                                            ,'width' : $this.data('width') || 200
                                            ,'displayInput' : $this.data('displayinput')==null || $this.data('displayinput')
                                            ,'fgColor' : $this.data('fgcolor') || '#87CEEB' //#222222'
                                            ,'bgColor' : $this.data('bgcolor') || '#EEEEEE'
                                            ,'readOnly' : $this.data('readonly')
                                            ,'draw' :
                                                    /**
                                                     * @param int a angle
                                                     * @param int v current value
                                                     * @param array opt plugin options
                                                     * @param context ctx Canvas context 2d
                                                     */
                                                    function( a, v, opt, ctx ) {
                                                            var sa = 1.5*Math.PI
                                                                ,ea = sa+a
                                                                ,r = opt.width/2
                                                                ,lw = r*opt.thickness;

                                                            ctx.clearRect(0, 0, opt.width, opt.width);
                                                            ctx.lineWidth = lw;

                                                            opt.cursor
                                                                && ( sa = ea-0.3 )
                                                                && ( ea = ea+0.3 );

                                                            ctx.beginPath();
                                                            ctx.strokeStyle = opt.fgColor;
                                                            ctx.arc( r, r, r-lw, sa, ea, false);
                                                            ctx.stroke();

                                                            ctx.beginPath();
                                                            ctx.strokeStyle = opt.bgColor;
                                                            ctx.arc(
                                                                        r, r, r-lw ,sa
                                                                        ,(v==opt.min && !opt.cursor)
                                                                            ? sa+0.0001
                                                                            : ea
                                                                        , true
                                                                    );
                                                            ctx.stroke();
                                                        }
                                            ,'change' :
                                                    /**
                                                     * @param int v Current value
                                                     */
                                                    function(v) {}
                                            ,'release' :
                                                    /**
                                                     * @param int v Current value
                                                     */
                                                    function(v) {}
                                        }
                                        ,gopt
                                    );

                        var c = $('<canvas width="'+opt.width+'" height="'+opt.width+'"></canvas>')
                            ,wd = $('

')
                            ,k;

                        $this.wrap( wd ).before( c );

                        opt.displayInput
                        && $this.css(
                                    {
                                    'width' : opt.width/2+'px'
                                    ,'position' : 'absolute'
                                    ,'margin-top' : (opt.width*5/13)+'px'
                                    ,'margin-left' : '-'+3*opt.width/4+'px'
                                    ,'font-size' : opt.width/5+'px'
                                    ,'border' : 'none'
                                    ,'background' : 'none'
                                    ,'font-family' : 'Arial'
                                    ,'font-weight' : 'bold'
                                    ,'text-align' : 'center'
                                    ,'color' : 'lightgrey'
                                    ,'padding' : '0px'
                                    ,'-webkit-appearance': 'none'
                                    }
                                )
                        || $this.css(
                                    {
                                    'width' : '0px'
                                    , 'visibility' : 'hidden'
                                    }
                                );

                        k = new Knob( c, opt );
                        k.onRelease = opt.release;
                        k.val( parseInt($this.val()) || 0 );
                        k.onChange = function(v) {
                                                    $this.val(v);
                                                    opt.change(v);
                                                 };

                        if( !opt.readOnly ){
                            c.bind(
                                "mousedown touchstart"
                                ,function( e ) {
                                    e.preventDefault();
                                    k.startDrag( e );
                                }
                            );
                        }else{
                            $this.attr('readonly','readonly');
                        }

                        var keys={37: -1, 38:1, 39:1, 40: -1}

                        $this.keydown(function(event){
                            setVal( keys[event.keyCode]);
                            event.preventDefault();
                        });

                        $this.bind('mousewheel DOMMouseScroll', function(event){
                            var originalEvent = event.originalEvent;
                            var deltaX = originalEvent.detail || originalEvent.wheelDeltaX;
                            var deltaY = originalEvent.detail || originalEvent.wheelDeltaY;
                            setVal( deltaX > 0 ||  deltaY > 0 ? 1 : deltaX < 0 ||  deltaY < 0 ? -1 : 0);
                            event.preventDefault();
                        });

                        function setVal(dir){
                            if(dir){
                                k.val( parseInt($this.val()) + dir );
                            }
                        }
                    }
                ).parent();
    }

    Knob = function( c, opt ) {

        var v = null
            ,ctx = c[0].getContext("2d")
            ,a = Math.PI*0.0001
            ,PI2 = 2*Math.PI
            ,mx ,my ,x ,y
            ,_self = this;

        this.onChange = function() {}
        this.onRelease = function() {}

        this.val = function(_v) {
            if(null!=_v){
                if( v==_v ) return;
                v=_v;
                this.onChange(_v);
                a = (_v-opt.min)*PI2/(opt.max-opt.min);
                opt.draw( a, _v, opt, ctx );
            }else{
                var b = a = Math.atan2( mx-x, -(my-y-opt.width/2) );
                (a<0) && (b=a+PI2);
                 _v = Math.round( b*(opt.max-opt.min)/PI2 ) + opt.min;
                return ( _v>opt.max ) ? opt.max : _v;
            }
        }

        this.capture = function(e) {
            switch( e.type ){
                case 'mousemove' :
                case 'mousedown' :
                    mx = e.pageX;
                    my = e.pageY;
                    break;
                case 'touchmove' :
                case 'touchstart' :
                    mx = e.originalEvent.touches[0].pageX;
                    my = e.originalEvent.touches[0].pageY;
                    break;
            }
            this.val( this.val() );
        }

        this.startDrag = function(e) {

            var p = c.position();
            x = p.left+(opt.width/2);
            y = p.top;

            this.capture(e);

            $(document).bind(
                            "mousemove.knob touchmove.knob"
                            ,function(e) {
                                _self.capture(e);
                            }
                        )
                        .bind(
                            "mouseup.knob touchend.knob"
                            ,function() {
                                $(document).unbind('mousemove.knob touchmove.knob mouseup.knob touchend.knob');
                                _self.onRelease(v);
                            }
                        );
        }
    }
});<|endoftext|>