<commit_before>"use strict"

const PeerRequest = require("peer-request")
const validate = require("zeronet-common/lib/verify").verifyProtocol
const PeerRequestHandler = require("zeronet-protocol/lib/request/peer-request-handler")

function genHandshakeData(protocol, client, zeronet) {
  let d = {
    crypt: null,
    crypt_supported: protocol.crypto ? protocol.crypto.supported() : [],
    fileserver_port: zeronet.server ? zeronet.server.port : 0,
    protocol: "v2",
    port_opened: false, //TODO: implent
    rev: zeronet.rev,
    version: zeronet.version,
    target_ip: "127.0.0.1", //TODO: add
    own: true //this is later removed
  }
  if (client.isTor) {
    d.onion = 0 //TODO: add tor
  } else {
    d.peer_id = zeronet.peer_id
  }
  return d
}

function Handshake(data) {
  const self = this

  for (var p in data) {
    self[p] = data[p]
  }

  function addCMD(name, fnc, needOwn) {
    self[name] = function () {
      if (!self.linked && needOwn) throw new Error("No handshake linked")
      if (self.linked && needOwn && !self.own) return self.linked[name].apply(self.linked, arguments)
      return fnc.apply(self.linked, arguments)
    }
  }

  self.link = (h2, r) => {
    self.linked = h2
    if (!r) h2.link(self, true)
    delete self.link
  }

  addCMD("commonCrypto", () => self.crypt_supported.filter(c => self.linked.crypt_supported.indexOf(c) != -1)[0], true)

}

const debug = require("debug")

module.exports = function ZeroNetHandshake(client, protocol, zeronet, opt) {

  const log = debug("zeronet:protocol:handshake")

  let waiting = []

  function handshakeComplete(err) {
    //console.log(waiting,opt,new Error("."))
    if (!Array.isArray(waiting)) throw new Error("HandshakeError: Complete called multiple times")
    waiting.forEach(w => w(err, client.handshakeData))
    waiting = err
  }

  function handshakeInit(cb) {
    log("Start handshake", opt)
    const handshake = new Handshake(genHandshakeData(protocol, client, zeronet))

    client.cmd.handshake(handshake, (err, data) => {
      if (err) {
        handshakeComplete(err)
        return cb(err)
      }
      const remoteHandshake = new Handshake(data)

      handshake.link(remoteHandshake)

      client.handshakeData = handshake
      client.remoteHandshake = remoteHandshake

      if (protocol.crypto && handshake.commonCrypto()) {
        client.cork()
        protocol.crypto.wrap(handshake.commonCrypto(), client, {
          isServer: false
        }, err => {
          if (err) return cb(err)
          log("Finished handshake", opt)
          handshakeComplete(err)
          client.isSecure = true
          return cb(null, handshake)
        })
      } else {
        log("Finished crypto-less handshake", opt)
        handshakeComplete(err)
        return cb(null, handshake)
      }

    })
  }

  function handshakeGet(data, cb) {
    log("Got handshake", opt)
    const handshake = new Handshake(genHandshakeData(protocol, client, zeronet))
    const remoteHandshake = new Handshake(data)
    cb(null, handshake)
    handshake.link(remoteHandshake)
    client.handshakeData = handshake
    client.remoteHandshake = remoteHandshake
    if (protocol.crypto && handshake.commonCrypto()) {
      client.cork()
      protocol.crypto.wrap(handshake.commonCrypto(), client, {
        isServer: true
      }, err => {
        waiting.forEach(w => w(err, client.handshakeData))
        waiting = err
        if (err) return log("Handshake error") || log(err)
        log("Finished handshake", opt)
        handshakeComplete(err)
        client.isSecure = true
      })
    } else {
      log("Finished crypto-less handshake", opt)
      handshakeComplete(null)
    }
  }

  client.handlers.handshake = new PeerRequestHandler("handshake", module.exports.req, client, handshakeGet, validate)
  log("use handshake", opt)

  client.handshake = handshakeInit

  client.waitForHandshake = cb => {
    if (Array.isArray(waiting)) waiting.push(cb)
    else cb(waiting, client.handshakeData)
  }

}

module.exports.def = { //Definitions are symmetric
  crypt: a => a === null || typeof a == "string",
  crypt_supported: Array.isArray,
  fileserver_port: "number",
  peer_id: "string",
  port_opened: "boolean",
  protocol: "string",
  rev: "number",
  target_ip: "string",
  version: "string",
}

module.exports.req = new PeerRequest("handshake", module.exports.def, module.exports.def)
<commit_msg>Fix validate function error<commit_after>"use strict"

const PeerRequest = require("peer-request")
const validate = require("zeronet-common/lib/verify").verifyProtocol
const PeerRequestHandler = require("zeronet-protocol/lib/request/peer-request-handler")

function genHandshakeData(protocol, client, zeronet) {
  let d = {
    crypt: null,
    crypt_supported: protocol.crypto ? protocol.crypto.supported() : [],
    fileserver_port: zeronet.server ? zeronet.server.port : 0,
    protocol: "v2",
    port_opened: false, //TODO: implent
    rev: zeronet.rev,
    version: zeronet.version,
    target_ip: "127.0.0.1", //TODO: add
    own: true //this is later removed
  }
  if (client.isTor) {
    d.onion = 0 //TODO: add tor
  } else {
    d.peer_id = zeronet.peer_id
  }
  return d
}

function Handshake(data) {
  const self = this

  for (var p in data) {
    self[p] = data[p]
  }

  function addCMD(name, fnc, needOwn) {
    self[name] = function () {
      if (!self.linked && needOwn) throw new Error("No handshake linked")
      if (self.linked && needOwn && !self.own) return self.linked[name].apply(self.linked, arguments)
      return fnc.apply(self.linked, arguments)
    }
  }

  self.link = (h2, r) => {
    self.linked = h2
    if (!r) h2.link(self, true)
    delete self.link
  }

  addCMD("commonCrypto", () => self.crypt_supported.filter(c => self.linked.crypt_supported.indexOf(c) != -1)[0], true)

}

const debug = require("debug")

module.exports = function ZeroNetHandshake(client, protocol, zeronet, opt) {

  const log = debug("zeronet:protocol:handshake")

  let waiting = []

  function handshakeComplete(err) {
    //console.log(waiting,opt,new Error("."))
    if (!Array.isArray(waiting)) throw new Error("HandshakeError: Complete called multiple times")
    waiting.forEach(w => w(err, client.handshakeData))
    waiting = err
  }

  function handshakeInit(cb) {
    log("Start handshake", opt)
    const handshake = new Handshake(genHandshakeData(protocol, client, zeronet))

    client.cmd.handshake(handshake, (err, data) => {
      if (err) {
        handshakeComplete(err)
        return cb(err)
      }
      const remoteHandshake = new Handshake(data)

      handshake.link(remoteHandshake)

      client.handshakeData = handshake
      client.remoteHandshake = remoteHandshake

      if (protocol.crypto && handshake.commonCrypto()) {
        client.cork()
        protocol.crypto.wrap(handshake.commonCrypto(), client, {
          isServer: false
        }, err => {
          if (err) return cb(err)
          log("Finished handshake", opt)
          handshakeComplete(err)
          client.isSecure = true
          return cb(null, handshake)
        })
      } else {
        log("Finished crypto-less handshake", opt)
        handshakeComplete(err)
        return cb(null, handshake)
      }

    })
  }

  function handshakeGet(data, cb) {
    log("Got handshake", opt)
    const handshake = new Handshake(genHandshakeData(protocol, client, zeronet))
    const remoteHandshake = new Handshake(data)
    cb(null, handshake)
    handshake.link(remoteHandshake)
    client.handshakeData = handshake
    client.remoteHandshake = remoteHandshake
    if (protocol.crypto && handshake.commonCrypto()) {
      client.cork()
      protocol.crypto.wrap(handshake.commonCrypto(), client, {
        isServer: true
      }, err => {
        waiting.forEach(w => w(err, client.handshakeData))
        waiting = err
        if (err) return log("Handshake error") || log(err)
        log("Finished handshake", opt)
        handshakeComplete(err)
        client.isSecure = true
      })
    } else {
      log("Finished crypto-less handshake", opt)
      handshakeComplete(null)
    }
  }

  client.handlers.handshake = new PeerRequestHandler("handshake", module.exports.req, client, handshakeGet)
  log("use handshake", opt)

  client.handshake = handshakeInit

  client.waitForHandshake = cb => {
    if (Array.isArray(waiting)) waiting.push(cb)
    else cb(waiting, client.handshakeData)
  }

}

module.exports.def = { //Definitions are symmetric
  crypt: a => a === null || typeof a == "string",
  crypt_supported: Array.isArray,
  fileserver_port: "number",
  peer_id: "string",
  port_opened: "boolean",
  protocol: "string",
  rev: "number",
  target_ip: "string",
  version: "string",
}

module.exports.req = new PeerRequest("handshake", module.exports.def, module.exports.def, validate)
<|endoftext|>


<commit_before>// TODO
game.PlayerEntity = me.Entity.extend	//builds the player class
({
	init: function(x,y, settings)	//sets up basic function
	{
		this._super(me.Entity, 'init', [x, y, //._super reaches to the object entity
		{
			image: "player",//uses the image player
			width: 64,	//preserves the height and width for player
			height: 64,
			spritewidth: "64", //uses height and width for player
			spriteheight: "64",
			getShape: function()
			{
				return(new me.Rect(0, 0, 64, 64)) . toPolygon();	//creates a little rectangle for what the player can walk into.
			}
		}]);

		this.body.setVelocity(5, 20); //sets velocity to 5
		this.facing = "right";	//makes the character face right
		this.now= new Date().getTime();	//keeps track of what time it is
		this.lastHit = this.now;	//same as this.now
		this.lastAttack = new Date().getTime();
		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);	//makes camera follow you
		this.renderable.addAnimation("idle", [78]);	//idle animation
		this.renderable.addAnimation("walk", [143, 144, 145, 146, 147, 148, 149, 150, 151], 80);	//walking animation
		this.renderable.setCurrentAnimation("idle");	//sets the idle animation
		this.renderable.addAnimation("attack", [195, 196, 197, 198, 199, 200], 80);	//setting the attack animation
	},

	update: function(delta){
		this.now = new Date().getTime();	//everytime we call update it updates the time
		if(me.input.isKeyPressed("right")){	//checks to see if the right key is pressed
			this.body.vel.x += this.body.accel.x * me.timer.tick; //adds the velocity to the set velocity and mutiplies by the me.timer.tick and makes the movement smooth
			this.facing = "right";	//sets the character to face right
			this.flipX(false);
		}
		else if(me.input.isKeyPressed("left")){		//allows the player to move left
			this.body.vel.x -= this.body.accel.x * me.timer.tick;
			this.facing = "left";
			this.flipX(true);
		}
		else{
			this.body.vel.x = 0;	//stops the movement
		}

		if(me.input.isKeyPressed("jump") && !this.jumping && !this.falling){	//allows the player to jump without double jumping or falling and jumping
			this.body.jumping = true;
			this.body.vel.y -= this.body.accel.y * me.timer.tick;
		}

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

		else if(this.body.vel.x !== 0 && !this.renderable.isCurrentAnimation("attack")){ //changes the animation from attack to walking
		if (!this.renderable.isCurrentAnimation("walk")) {	//sets the current animation for walk
			this.renderable.setCurrentAnimation("walk");
		};
	}
	else if(!this.renderable.isCurrentAnimation("attack")){	//changes the animation from attack to idle
		this.renderable.setCurrentAnimation("idle");	//if the player is not walking it uses idle animation
	}
	// 	if(me.input.isKeyPressed("left")){	//checks to see if the left key is pressed
	// 		this.body.vel.x += this.body.accel.x * me.timer.tick; //adds the velocity to the set velocity and mutiplies by the me.timer.tick and makes the movement smooth
	// 		this.flipX(true);
	// 	}
	// 	else{
	// 		this.body.vel.x = 0;	//stops the movement
	// 	}

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

		me.collision.check(this, true, this.collideHandler.bind(this), true);	//checks for collision
		this.body.update(delta);	//delta is the change in time
		this._super(me.Entity, "update", [delta]);
		return true;
	},
	collideHandler: function(response){
		if(response.b.type==='EnemyBaseEntity'){	//sees if the enemy base entitiy is near a player entity and if so it is solid from left and right and top
		 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;
		}
		 if(xdif>-35 && this.facing==='right' && (xdif<0)){
		 	this.body.vel.x = 0;
		 	this.pos.x = this.pos.x -1;
		 }else if(xdif<70 && this.facing==='left' && (xdif>0)){
		 	this.body.vel.x=0;
		 	this.pos.x = this.pos.x +1;
		 }

		 if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= 1000){	//if the animation is attack it will lose the base health and that it will check when the lasthit was

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

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

	update:function(delta){	//if health reaches zero it changes the image to "broken"
		if(this.health<=0){
			this.broken = true;
			this.renderable.setCurrentAnimation("broken");
		}
		this.body.update(delta);
		this._super(me.Entity,"update",[delta]);
		return true;
	},

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

	}
});

game.EnemyBaseEntity = me.Entity.extend({	//creates the enemy base
	init : function(x, y, settings){
		this._super(me.Entity,'init', [x, y,{
			image: "tower",
			width: 100,
			height: 100,
			spriteheight: "100",
			spritewidth: "100",
			getShape: function(){
				return (new me.Rect(0, 0, 100, 70)) . toPolygon();
			}
		}])
		this.broken = false;	//atributes of the enemy base
		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 health reaches zero image changes to "broken"
		if(this.health<=0){
			this.broken = true;
			this.renderable.setCurrentAnimation("broken");
		}
		this.body.update(delta);
		this._super(me.Entity,"update",[delta]);
		return true;
	},
	onCollision: function(){

	},
	loseHealth: function(){	//makes the health go down
		this.health--;
	}
});

game.EnemyCreep = me.Entity.extend({	//creates the enemy creeps
	init: function(x, y, settings){
		this._super(me.Entity,'init', [x, y, {	//creates the creeps size and image
			image: "creep1",
			width:32,
			height:64,
			spritewidth:"32",
			spriteheight:"64",
			getShape: function(){
				return (new me.Rect(0, 0, 32, 64)).toPolygon();
			}
		}]);
		this.health = 10;	//sets up the attributes
		this.alwaysUpdate = true;
		this.attacking = false;
		this.lastAttacking = new Date().getTime();
		this.lastHit = new Date().getTime();
		this.now = new Date().getTime();
		this.body.setVelocity(3, 20);

		this.type = "EnemyCreep";

		this.renderable.addAnimation("walk", [3, 4, 5], 80);	//sets up the animations for walk
		this.renderable.setCurrentAnimation("walk");
	},

	update: function(delta){
		this.now = new Date() . getTime();
		this.body.vel.x -= this.body.accel.x * me.timer.tick;
		me.collision.check(this, true, this.collideHandler.bind(this), true);
		this.body.update(delta);
		this._super(me.Entity,"update", [delta]);
		return true;
	},

	collideHandler: function(response){
		if(response.b.type==='PlayerBase'){
			this.attacking=true;
			//this.lastAttacking=this.now;
			this.body.vel.x=0;
			this.pos.x = this.pos.x + 1;
			if((this.now-this.lastHit >= 1000)){
				this.lastHit = this.now;
				response.b.loseHealth(1);
			}
		}
	}
});

game.GameManager = Object.extend({	//creates a game manager to manage the timer
	init: function(x, y, settings){
		this.now = new Date().getTime();
		this.lastCreep = new Date().getTime();

		this.alwaysUpdate = true;
	},

	update: function(){	//creates new creeps
		this.now = new Date().getTime();

		if (Math.round(this.now/1000)%10 ===0 && (this.now - this.lastCreep >= 1000)){
			this.lastCreep = this.now;
			var creepe = me.pool.pull("EnemyCreep", 1000, 0, {});
			me.game.world.addChild(creepe, 5);
		}
		return true;
	}
});<commit_msg>Finished video 20-21 comments<commit_after>// TODO
game.PlayerEntity = me.Entity.extend	//builds the player class
({
	init: function(x,y, settings)	//sets up basic function
	{
		this._super(me.Entity, 'init', [x, y, //._super reaches to the object entity
		{
			image: "player",//uses the image player
			width: 64,	//preserves the height and width for player
			height: 64,
			spritewidth: "64", //uses height and width for player
			spriteheight: "64",
			getShape: function()
			{
				return(new me.Rect(0, 0, 64, 64)) . toPolygon();	//creates a little rectangle for what the player can walk into.
			}
		}]);

		this.body.setVelocity(5, 20); //sets velocity to 5
		this.facing = "right";	//makes the character face right
		this.now= new Date().getTime();	//keeps track of what time it is
		this.lastHit = this.now;	//same as this.now
		this.lastAttack = new Date().getTime();
		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);	//makes camera follow you
		this.renderable.addAnimation("idle", [78]);	//idle animation
		this.renderable.addAnimation("walk", [143, 144, 145, 146, 147, 148, 149, 150, 151], 80);	//walking animation
		this.renderable.setCurrentAnimation("idle");	//sets the idle animation
		this.renderable.addAnimation("attack", [195, 196, 197, 198, 199, 200], 80);	//setting the attack animation
	},

	update: function(delta){
		this.now = new Date().getTime();	//everytime we call update it updates the time
		if(me.input.isKeyPressed("right")){	//checks to see if the right key is pressed
			this.body.vel.x += this.body.accel.x * me.timer.tick; //adds the velocity to the set velocity and mutiplies by the me.timer.tick and makes the movement smooth
			this.facing = "right";	//sets the character to face right
			this.flipX(false);
		}
		else if(me.input.isKeyPressed("left")){		//allows the player to move left
			this.body.vel.x -= this.body.accel.x * me.timer.tick;
			this.facing = "left";
			this.flipX(true);
		}
		else{
			this.body.vel.x = 0;	//stops the movement
		}

		if(me.input.isKeyPressed("jump") && !this.jumping && !this.falling){	//allows the player to jump without double jumping or falling and jumping
			this.body.jumping = true;
			this.body.vel.y -= this.body.accel.y * me.timer.tick;
		}

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

		else if(this.body.vel.x !== 0 && !this.renderable.isCurrentAnimation("attack")){ //changes the animation from attack to walking
		if (!this.renderable.isCurrentAnimation("walk")) {	//sets the current animation for walk
			this.renderable.setCurrentAnimation("walk");
		};
	}
	else if(!this.renderable.isCurrentAnimation("attack")){	//changes the animation from attack to idle
		this.renderable.setCurrentAnimation("idle");	//if the player is not walking it uses idle animation
	}
	// 	if(me.input.isKeyPressed("left")){	//checks to see if the left key is pressed
	// 		this.body.vel.x += this.body.accel.x * me.timer.tick; //adds the velocity to the set velocity and mutiplies by the me.timer.tick and makes the movement smooth
	// 		this.flipX(true);
	// 	}
	// 	else{
	// 		this.body.vel.x = 0;	//stops the movement
	// 	}

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

		me.collision.check(this, true, this.collideHandler.bind(this), true);	//checks for collision
		this.body.update(delta);	//delta is the change in time
		this._super(me.Entity, "update", [delta]);
		return true;
	},
	collideHandler: function(response){
		if(response.b.type==='EnemyBaseEntity'){	//sees if the enemy base entitiy is near a player entity and if so it is solid from left and right and top
		 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;
		}
		 if(xdif>-35 && this.facing==='right' && (xdif<0)){
		 	this.body.vel.x = 0;
		 	this.pos.x = this.pos.x -1;
		 }else if(xdif<70 && this.facing==='left' && (xdif>0)){
		 	this.body.vel.x=0;
		 	this.pos.x = this.pos.x +1;
		 }

		 if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= 1000){	//if the animation is attack it will lose the base health and that it will check when the lasthit was

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

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

	update:function(delta){	//if health reaches zero it changes the image to "broken"
		if(this.health<=0){
			this.broken = true;
			this.renderable.setCurrentAnimation("broken");
		}
		this.body.update(delta);
		this._super(me.Entity,"update",[delta]);
		return true;
	},

	loseHealth: function(damage){	// makes the player base lose health by creeps
		this.health = this.health-damage;
	},
	onCollision: function(){

	}
});

game.EnemyBaseEntity = me.Entity.extend({	//creates the enemy base
	init : function(x, y, settings){
		this._super(me.Entity,'init', [x, y,{
			image: "tower",
			width: 100,
			height: 100,
			spriteheight: "100",
			spritewidth: "100",
			getShape: function(){
				return (new me.Rect(0, 0, 100, 70)) . toPolygon();
			}
		}])
		this.broken = false;	//atributes of the enemy base
		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 health reaches zero image changes to "broken"
		if(this.health<=0){
			this.broken = true;
			this.renderable.setCurrentAnimation("broken");
		}
		this.body.update(delta);
		this._super(me.Entity,"update",[delta]);
		return true;
	},
	onCollision: function(){

	},
	loseHealth: function(){	//makes the health go down
		this.health--;
	}
});

game.EnemyCreep = me.Entity.extend({	//creates the enemy creeps
	init: function(x, y, settings){
		this._super(me.Entity,'init', [x, y, {	//creates the creeps size and image
			image: "creep1",
			width:32,
			height:64,
			spritewidth:"32",
			spriteheight:"64",
			getShape: function(){
				return (new me.Rect(0, 0, 32, 64)).toPolygon();
			}
		}]);
		this.health = 10;	//sets up the attributes
		this.alwaysUpdate = true;
		this.attacking = false;	//lets us know when the enemy is attacking
		this.lastAttacking = new Date().getTime();	//lets us know when the enemy last attacked
		this.lastHit = new Date().getTime();	//keeps track on the last time the enemy hit anything
		this.now = new Date().getTime();	//creates a timer
		this.body.setVelocity(3, 20);

		this.type = "EnemyCreep";

		this.renderable.addAnimation("walk", [3, 4, 5], 80);	//sets up the animations for walk
		this.renderable.setCurrentAnimation("walk");
	},

	update: function(delta){
		this.now = new Date() . getTime();	//creates a timer
		this.body.vel.x -= this.body.accel.x * me.timer.tick;	//causes creeps to move
		me.collision.check(this, true, this.collideHandler.bind(this), true);	//checks for collisions
		this.body.update(delta);	//causes the creep to fall to the ground
		this._super(me.Entity,"update", [delta]);
		return true;
	},

	collideHandler: function(response){
		if(response.b.type==='PlayerBase'){	//checks if there is a player base
			this.attacking=true;
			//this.lastAttacking=this.now;
			this.body.vel.x=0;
			this.pos.x = this.pos.x + 1;	//makes the creep keep moving
			if((this.now-this.lastHit >= 1000)){	//attacks the base every second
				this.lastHit = this.now;	//updates the last hit timer
				response.b.loseHealth(1);	//calls the lose health function which loses the health with a damage of 1
			}
		}
	}
});

game.GameManager = Object.extend({	//creates a game manager to manage the timer
	init: function(x, y, settings){
		this.now = new Date().getTime();
		this.lastCreep = new Date().getTime();

		this.alwaysUpdate = true;
	},

	update: function(){	//creates new creeps
		this.now = new Date().getTime();

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


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

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

       this.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");
    },

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

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

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

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

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

        if(me.input.isKeyPressed("right")){
            //adds the position of my x by the velocity defined above in
            //setVelocity and multiplying it by me.timer.tick
            //me.timer.tick makes movement look smooth
            this.body.vel.x += this.body.accel.x * me.timer.tick;
            this.facing = "right";
            this.flipX(true);
        }else if(me.input.isKeyPressed("left")){
            this.facing = "left";
            this.body.vel.x -=this.body.accel.x * me.timer.tick;
            this.flipX(false);
        }else{
            this.body.vel.x = 0;
        }
        //i made the character go left when the left key is pressed
        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;
        }
        //i am making the character jump when i press the space button
        if(me.input.isKeyPressed("attack")){
            if(!this.renderable.isCurrentAnimation("attack")){
                //sets the current animation to attack and once that is over
                //goes back to the idle animation
                this.renderable.setCurrentAnimation("attack", "idle");
                //makes it so the next time we start this sequence we begin
                //from the first animation, not from wherever we left off when we
                //switched to another animation
                this.renderable.setAnimationFrame();
            }
        }

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

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

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

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

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

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

            if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer){

                this.lastHit = this.now;
                response.b.loseHealth();
            }
        }else if(response.b.type==='EnemyCreep'){
            var xdif = this.pos.x - response.b.pos.x;
            var ydif = this.pos.y - response.b.pos.y;

            if (xdif>0){
                //this.pos.x = this.pos.x + 1;
                if(this.facing==="left"){
                    this.body.vel.x = 0;
                }
            }else{
                //this.pos.x = this.pos.x - 1;
                if(this.facing==="right"){
                    this.body.vel.x = 0;
                }
            }
            if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer
                    && (Math.abs(ydif) <=40) &&
                    (((xdif>0) && this.facing==="left") || ((xdif<0) && this.facing==="right"))
                    ){
                this.lastHit = this.now;
                //if the creeps health is less than our attack, execute code in if statement
                if(response.b.health <= game.data.playerAttack){
                    //adds one gold for each creep kill
                    game.data.gold += 1;
                    console.log("Current gold: " + game.data.gold);
                }

                response.b.loseHealth(game.data.playerAttack);
            }
        }
    }
});
<commit_msg>done with video 30 created refactor int<commit_after>game.PlayerEntity = me.Entity.extend({
    init: function(x, y, settings){
       this.setSuper();
       this.setPlayerTimers();
       this.setAttributes();
       this.type = "PlayerEntity";
       this.setFlags();

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

       this.addAnimation();

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

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

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

    setFlags: function(){
       //keeps track of which direction your character is going
       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.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);

    },

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

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

        if(me.input.isKeyPressed("right")){
            //adds the position of my x by the velocity defined above in
            //setVelocity and multiplying it by me.timer.tick
            //me.timer.tick makes movement look smooth
            this.body.vel.x += this.body.accel.x * me.timer.tick;
            this.facing = "right";
            this.flipX(true);
        }else if(me.input.isKeyPressed("left")){
            this.facing = "left";
            this.body.vel.x -=this.body.accel.x * me.timer.tick;
            this.flipX(false);
        }else{
            this.body.vel.x = 0;
        }
        //i made the character go left when the left key is pressed
        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;
        }
        //i am making the character jump when i press the space button
        if(me.input.isKeyPressed("attack")){
            if(!this.renderable.isCurrentAnimation("attack")){
                //sets the current animation to attack and once that is over
                //goes back to the idle animation
                this.renderable.setCurrentAnimation("attack", "idle");
                //makes it so the next time we start this sequence we begin
                //from the first animation, not from wherever we left off when we
                //switched to another animation
                this.renderable.setAnimationFrame();
            }
        }

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

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

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

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

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

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

            if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer){

                this.lastHit = this.now;
                response.b.loseHealth();
            }
        }else if(response.b.type==='EnemyCreep'){
            var xdif = this.pos.x - response.b.pos.x;
            var ydif = this.pos.y - response.b.pos.y;

            if (xdif>0){
                //this.pos.x = this.pos.x + 1;
                if(this.facing==="left"){
                    this.body.vel.x = 0;
                }
            }else{
                //this.pos.x = this.pos.x - 1;
                if(this.facing==="right"){
                    this.body.vel.x = 0;
                }
            }
            if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer
                    && (Math.abs(ydif) <=40) &&
                    (((xdif>0) && this.facing==="left") || ((xdif<0) && this.facing==="right"))
                    ){
                this.lastHit = this.now;
                //if the creeps health is less than our attack, execute code in if statement
                if(response.b.health <= game.data.playerAttack){
                    //adds one gold for each creep kill
                    game.data.gold += 1;
                    console.log("Current gold: " + game.data.gold);
                }

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


<commit_before>'use strict';
// Global vars
var pymChild = null;
var isMobile = false;
var KEY_NESTED_DATA;
var FLAT_DATA = [];

var lineKeys = d3.set(d3.map(DATA[0]).keys());

/* Initialize the graphic.
----------------------------------------------------*/
var onWindowLoaded = function () {
    if (Modernizr.svg) {
        formatData();

        pymChild = new pym.Child({
            renderCallback: render,
        });
    } else {
        pymChild = new pym.Child({});
    }
};

/*
 * Re-format graphic data for processing by D3.
 */
var formatData = function () {

    // Map through data and convert to numbers
    DATA = DATA.map(function (obj) {
        return d3.entries(obj).reduce(function (memo, val) {
            var key = val.key;
            var value = val.value;
            var formattedValue;

            if (value) formattedValue = +value; // turn string into number

            memo[key] = formattedValue;
            return memo;
        }, {});
    });

    /*
     * Restructure tabular data for easier charting.
     */
    lineKeys.forEach(function (d) {
        FLAT_DATA = FLAT_DATA.concat(DATA.map(function (v) {
            return {
                amt: v[d],
                key: d,
            };
        }));
    });

    // Remove undefined amounts in data
    FLAT_DATA = FLAT_DATA.filter(function(element) {
        return element.amt !== undefined;
    })

    // Nest data under data keys
    KEY_NESTED_DATA = d3.nest()
        .key(function (d) { return d.key; })
        .entries(FLAT_DATA);
};

/*
 * Render the graphic(s). Called by pym with the container width.
 */
var render = function (containerWidth) {
    containerWidth = containerWidth || DEFAULT_WIDTH;
    isMobile = (containerWidth <= MOBILE_THRESHOLD);

    // Render the chart
    renderSparklineChart();

    // Update iframe
    if (pymChild) {
        pymChild.sendHeight();
    }
};

/*
 * Render a Sparkline chart.
 */
var renderSparklineChart = function () {
    /*
     * Setup
     */
    var labelWidth = parseInt(LABELS.labelWidth || 55);
    var labelMargin = parseInt(LABELS.labelMargin || 4);

    var dataLabelWidth = parseInt(LABELS.dataLabelWidth || 90);
    var dataLabelMargin = parseInt(LABELS.dataLabelMargin || 4);

    var sparklineHeight = parseInt(LABELS.chartHeight || 50);
    var circleRadius = parseFloat(LABELS.circleRadius || 1.5);
    var endCircleRadius = parseFloat(LABELS.endCircleRadius || 2);

    var margins = {
        top: parseInt(LABELS.marginTop || 0),
        right: parseInt(LABELS.marginRight || dataLabelWidth + dataLabelMargin),
        bottom: parseInt(LABELS.marginBottom || 0),
        left: parseInt(LABELS.marginLeft || labelWidth + labelMargin),
    };

    // if (isMobile) {
    //     margins.right = margins.right * 0.9;
    //     margins.left = margins.left * 0.9;
    // }

    // Clear existing graphic (for redraw)
    var containerElement = d3.select('#sparkline-chart')
    containerElement.html('');

    // Set up colors
    var colorList = colorArray(LABELS, MONOCHROMECOLORS);

    function drawSparklines(chartData) {
        /*
        * Create the root SVG element
        */
        var chartWrapper = containerElement.append('div')
            .attr('class', 'graphics-wrapper')

        // Calculate actual chart dimensions
        var innerWidth = chartWrapper.node().getBoundingClientRect().width;
        var chartWidth = (innerWidth - margins.left - margins.right);
        var chartHeight = sparklineHeight - margins.top - margins.bottom;

        var xScale = d3.scale.linear().range([0 + endCircleRadius, chartWidth - endCircleRadius]);
        var yScale = d3.scale.linear().range([chartHeight - endCircleRadius, 0 + endCircleRadius]);

        xScale.domain([0, chartData.values.length - 1] );
        yScale.domain(d3.extent(chartData.values, function(d) { return d.amt; }));

        var minAmt;
        var maxAmt;
        var endAmt = chartData.values[chartData.values.length - 1].amt;

        // Left side label key
        chartWrapper.append('div')
            .classed('sparkline-key', true)
            .style({
                'position': 'absolute',
                'height': chartHeight + 'px',
            })
            .append('ul')
                .classed('labels', true)
                .append('li')
                    .style('line-height', chartHeight + 'px')
                    .append('span')
                        .style('min-width', labelWidth + 'px')
                        .text(chartData.key);

        // Min and Max values
        var minMaxValueLabel = chartWrapper.append('div')
            .classed('sparkline-values', true)
            .style({
                'position': 'absolute',
                'left': chartWidth + labelWidth + labelMargin + dataLabelMargin + 'px',
                'height': chartHeight + 'px',
            })
            .append('ul')
                .classed('labels', true)
                .classed('end-data', true)
                .append('li')
                    .classed('min-max', true)
                    .style({
                        'display': 'flex',
                        'justify-content': 'center',
                        'flex-direction': 'column',
                        'min-height': chartHeight + 'px'
                    })
                    .append('span')
                        .style('min-width', dataLabelWidth / 2 + 'px')
                        .style('text-align', 'left');

        // End value
        var endValueLabel = chartWrapper.append('div')
            .classed('sparkline-values', true)
            .style({
                'position': 'absolute',
                'right': dataLabelWidth / 2 - dataLabelMargin + 'px',
                'height': chartHeight + 'px'
            })
            .append('ul')
                .classed('labels', true)
                .append('li')
                    .classed('end-value', true)
                    .style({
                        'display': 'flex',
                        'justify-content': 'center',
                        'flex-direction': 'column',
                        'min-height': chartHeight + 'px'
                    })
                    .append('span')
                        .style('min-width', dataLabelWidth / 2 + 'px')
                        .style('text-align', 'left')
                        .style('color', colorList[0]);

        // Sparkline chart
        var chartSvg = chartWrapper.append('svg')
            .attr({
                width: chartWidth + margins.left + margins.right,
                height: chartHeight + margins.top + margins.bottom,
            });

        var chartElement = chartSvg.append('g')
                .attr('transform', makeTranslate(margins.left, margins.top));

        var overlay = chartElement.append('rect')
            .attr({
                width: chartWidth,
                height: chartHeight,
                fill: 'transparent'
            });

        // Draw a sparkline
        var line = d3.svg.line()
            .interpolate(LABELS.interpolate || 'linear')
            .x(function(d, i) {
                return xScale(i);
            })
            .y(function(d) {
                return yScale(d.amt);
            });

        chartElement.append('path')
            .datum(chartData.values)
            .classed('sparkline', true)
            .attr('d', line);

        // Set minimum and maximup variables
        var yMin = d3.min(chartData.values, function(d) { return d.amt; });
        var yMax = d3.max(chartData.values, function(d) { return d.amt; });

        chartData.values.forEach(function(d, i) {
            // Find and mark minimum point
            if (d.amt === yMin) {
                minAmt = d.amt;

                chartElement.append('circle')
                    .attr('class', 'sparkcircle min-circle')
                    .attr('cx', xScale(i))
                    .attr('cy', yScale(minAmt))
                    .attr('r', circleRadius);
            }

            // Find and mark maximum point
            if (d.amt === yMax) {
                maxAmt = d.amt;

                chartElement.append('circle')
                    .attr('class', 'sparkcircle max-circle')
                    .attr('cx', xScale(i))
                    .attr('cy', yScale(maxAmt))
                    .attr('r', circleRadius);
            }
        });

        chartElement.append('circle')
            .attr('class', 'sparkcircle end-circle')
            .attr('cx', xScale(chartData.values.length - 1))
            .attr('cy', yScale(endAmt))
            .attr('r', endCircleRadius)
            .style('fill', colorList[0]);

        // Render data values
        if (LABELS.decimalPlaces) {
            minMaxValueLabel.html(
                LABELS.valuePrefix +
                Number(maxAmt).toFixed(LABELS.decimalPlaces) +
                LABELS.valueSuffix +
                '
' +
                LABELS.valuePrefix +
                Number(minAmt).toFixed(LABELS.decimalPlaces) +
                LABELS.valueSuffix);
            endValueLabel.html(
                LABELS.valuePrefix +
                Number(endAmt).toFixed(LABELS.decimalPlaces) +
                LABELS.valueSuffix
                );
        } else {
            minMaxValueLabel.html(
                LABELS.valuePrefix +
                maxAmt +
                LABELS.valueSuffix +
                '
' +
                LABELS.valuePrefix +
                minAmt +
                LABELS.valueSuffix
                );
            endValueLabel.html(
                LABELS.valuePrefix +
                endAmt +
                LABELS.valueSuffix
                );
        }
    };

    // For each data column render a chart
    KEY_NESTED_DATA.forEach(function(d, i) {
            drawSparklines(d);
        });
};

/*
 * Initially load the graphic
 * (NB: Use window.load to ensure all images have loaded)
 */
window.onload = onWindowLoaded;<commit_msg>Line up the divs side by side<commit_after>'use strict';
// Global vars
var pymChild = null;
var isMobile = false;
var KEY_NESTED_DATA;
var FLAT_DATA = [];

var lineKeys = d3.set(d3.map(DATA[0]).keys());

/* Initialize the graphic.
----------------------------------------------------*/
var onWindowLoaded = function () {
    if (Modernizr.svg) {
        formatData();

        pymChild = new pym.Child({
            renderCallback: render,
        });
    } else {
        pymChild = new pym.Child({});
    }
};

/*
 * Re-format graphic data for processing by D3.
 */
var formatData = function () {

    // Map through data and convert to numbers
    DATA = DATA.map(function (obj) {
        return d3.entries(obj).reduce(function (memo, val) {
            var key = val.key;
            var value = val.value;
            var formattedValue;

            if (value) formattedValue = +value; // turn string into number

            memo[key] = formattedValue;
            return memo;
        }, {});
    });

    /*
     * Restructure tabular data for easier charting.
     */
    lineKeys.forEach(function (d) {
        FLAT_DATA = FLAT_DATA.concat(DATA.map(function (v) {
            return {
                amt: v[d],
                key: d,
            };
        }));
    });

    // Remove undefined amounts in data
    FLAT_DATA = FLAT_DATA.filter(function(element) {
        return element.amt !== undefined;
    })

    // Nest data under data keys
    KEY_NESTED_DATA = d3.nest()
        .key(function (d) { return d.key; })
        .entries(FLAT_DATA);
};

/*
 * Render the graphic(s). Called by pym with the container width.
 */
var render = function (containerWidth) {
    containerWidth = containerWidth || DEFAULT_WIDTH;
    isMobile = (containerWidth <= MOBILE_THRESHOLD);

    // Render the chart
    renderSparklineChart();

    // Update iframe
    if (pymChild) {
        pymChild.sendHeight();
    }
};

/*
 * Render a Sparkline chart.
 */
var renderSparklineChart = function () {
    /*
     * Setup
     */
    var labelWidth = parseInt(LABELS.labelWidth || 55);
    var labelMargin = parseInt(LABELS.labelMargin || 4);

    var dataLabelWidth = parseInt(LABELS.dataLabelWidth || 80);
    var dataLabelMargin = parseInt(LABELS.dataLabelMargin || 4);

    var sparklineHeight = parseInt(LABELS.chartHeight || 50);
    var circleRadius = parseFloat(LABELS.circleRadius || 1.6);
    var endCircleRadius = parseFloat(LABELS.endCircleRadius || 2.2);

    var margins = {
        top: parseInt(LABELS.marginTop || 0),
        right: parseInt(LABELS.marginRight || dataLabelWidth + dataLabelMargin),
        bottom: parseInt(LABELS.marginBottom || 0),
        left: parseInt(LABELS.marginLeft || labelWidth + labelMargin),
    };

    // if (isMobile) {
    //     margins.right = margins.right * 0.9;
    //     margins.left = margins.left * 0.9;
    // }

    // Clear existing graphic (for redraw)
    var containerElement = d3.select('#sparkline-chart')
    containerElement.html('');

    // Set up colors
    var colorList = colorArray(LABELS, MONOCHROMECOLORS);
    var colorScale = d3.scale.ordinal()
        .range(colorList);

    function drawSparklines(chartData) {
        /*
        * Create the root SVG element
        */
        var chartWrapper = containerElement.append('div')
            .attr('class', 'graphics-wrapper')

        // Calculate actual chart dimensions

        //
        if (isMobile && !LABELS.fullWidth) {
            var innerWidth = chartWrapper.node().getBoundingClientRect().width;
        } else {
            var innerWidth = chartWrapper.node().getBoundingClientRect().width / 2;
            chartWrapper.style('display', 'inline-block');
        }

        var chartWidth = (innerWidth - margins.left - margins.right);
        var chartHeight = sparklineHeight - margins.top - margins.bottom;

        var xScale = d3.scale.linear().range([0 + endCircleRadius, chartWidth - endCircleRadius]);
        var yScale = d3.scale.linear().range([chartHeight - endCircleRadius, 0 + endCircleRadius]);

        xScale.domain([0, chartData.values.length - 1] );
        yScale.domain(d3.extent(chartData.values, function(d) { return d.amt; }));

        var minAmt;
        var maxAmt;
        var endAmt = chartData.values[chartData.values.length - 1].amt;

        // Left side label key
        chartWrapper.append('div')
            .classed('sparkline-key', true)
            .style({
                'position': 'absolute',
                'height': chartHeight + 'px',
            })
            .append('ul')
                .classed('labels', true)
                .append('li')
                    .style('line-height', chartHeight + 'px')
                    .append('span')
                        .style('min-width', labelWidth + 'px')
                        .text(chartData.key);

        // Min and Max values
        var minMaxValueLabel = chartWrapper.append('div')
            .classed('sparkline-values', true)
            .style({
                'position': 'relative',
                'display': 'inline-block',
                'left': chartWidth + labelWidth + labelMargin + dataLabelMargin + 'px',
                'height': chartHeight + 'px',
            })
            .append('ul')
                .classed('labels', true)
                .classed('end-data', true)
                .append('li')
                    .classed('min-max', true)
                    .style({
                        'display': 'flex',
                        'justify-content': 'center',
                        'flex-direction': 'column',
                        'min-height': chartHeight + 'px'
                    })
                    .append('span')
                        .style('min-width', dataLabelWidth / 2 + 'px')
                        .style('text-align', 'left');

        // End value
        var endValueLabel = chartWrapper.append('div')
            .classed('sparkline-values', true)
            .style({
                'position': 'relative',
                'display': 'inline-block',
                'left': chartWidth +
                        labelWidth +
                        labelMargin +
                        dataLabelMargin +
                        (dataLabelWidth / 2) +
                        dataLabelMargin +
                        'px',
                'height': chartHeight + 'px'
            })
            .append('ul')
                .classed('labels', true)
                .append('li')
                    .classed('end-value', true)
                    .style({
                        'display': 'flex',
                        'justify-content': 'center',
                        'flex-direction': 'column',
                        'min-height': chartHeight + 'px'
                    })
                    .append('span')
                        .style('min-width', dataLabelWidth / 2 + 'px')
                        .style('text-align', 'left')
                        .style('color', colorList[0]);

        // Sparkline chart
        var chartSvg = chartWrapper.append('svg')
            .attr({
                width: chartWidth + margins.left + margins.right,
                height: chartHeight + margins.top + margins.bottom,
            });

        var chartElement = chartSvg.append('g')
                .attr('transform', makeTranslate(margins.left, margins.top));

        var overlay = chartElement.append('rect')
            .attr({
                width: chartWidth,
                height: chartHeight,
                fill: 'transparent'
            });

        // Draw a sparkline
        var line = d3.svg.line()
            .interpolate(LABELS.interpolate || 'linear')
            .x(function(d, i) {
                return xScale(i);
            })
            .y(function(d) {
                return yScale(d.amt);
            });

        chartElement.append('path')
            .datum(chartData.values)
            .classed('sparkline', true)
            .attr('d', line);

        // Set minimum and maximup variables
        var yMin = d3.min(chartData.values, function(d) { return d.amt; });
        var yMax = d3.max(chartData.values, function(d) { return d.amt; });

        chartData.values.forEach(function(d, i) {
            // Find and mark minimum point
            if (d.amt === yMin) {
                minAmt = d.amt;

                chartElement.append('circle')
                    .attr('class', 'sparkcircle min-circle')
                    .attr('cx', xScale(i))
                    .attr('cy', yScale(minAmt))
                    .attr('r', circleRadius);
            }

            // Find and mark maximum point
            if (d.amt === yMax) {
                maxAmt = d.amt;

                chartElement.append('circle')
                    .attr('class', 'sparkcircle max-circle')
                    .attr('cx', xScale(i))
                    .attr('cy', yScale(maxAmt))
                    .attr('r', circleRadius);
            }
        });

        chartElement.append('circle')
            .attr('class', 'sparkcircle end-circle')
            .attr('cx', xScale(chartData.values.length - 1))
            .attr('cy', yScale(endAmt))
            .attr('r', endCircleRadius)
            .style('fill', colorList[0]);

        // Render data values
        if (LABELS.decimalPlaces) {
            minMaxValueLabel.html(
                LABELS.valuePrefix +
                Number(maxAmt).toFixed(LABELS.decimalPlaces) +
                LABELS.valueSuffix +
                '
' +
                LABELS.valuePrefix +
                Number(minAmt).toFixed(LABELS.decimalPlaces) +
                LABELS.valueSuffix);
            endValueLabel.html(
                LABELS.valuePrefix +
                Number(endAmt).toFixed(LABELS.decimalPlaces) +
                LABELS.valueSuffix
                );
        } else {
            minMaxValueLabel.html(
                LABELS.valuePrefix +
                maxAmt +
                LABELS.valueSuffix +
                '
' +
                LABELS.valuePrefix +
                minAmt +
                LABELS.valueSuffix
                );
            endValueLabel.html(
                LABELS.valuePrefix +
                endAmt +
                LABELS.valueSuffix
                );
        }
    };

    // For each data column render a chart
    KEY_NESTED_DATA.forEach(function(d, i) {
            drawSparklines(d);
        });
};

/*
 * Initially load the graphic
 * (NB: Use window.load to ensure all images have loaded)
 */
window.onload = onWindowLoaded;<|endoftext|>


<commit_before>game.PlayerEntity = me.Entity.extend({
    init: function(x, y, settings) {
        this._super(me.Entity, 'init', [x, y, {
                image: "player",
                width: 64,
                height: 64,
                spritewidth: "64",
                spriteheight: "64",
                getShape: function() {
                    return(new me.Rect(0, 0, 64, 64)).toPolygon();
                }
            }]);
        this.type = "PlayerEntity";
        this.health = 20;
        this.body.setVelocity(5, 20);
        this.facing = "right";
        this.new = new Date().getTime();
        this.lastHit = this.now;
        this.lastAttack = new Date().getTime();
        me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

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

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

    update: function(delta) {
        this.now = new Date().getTime();
        if (me.input.isKeyPressed("right")) {
            this.facing = "right";
            this.body.vel.x += this.body.accel.x * me.timer.tick;
            this.flipX(true);
        } else if(me.input.isKeyPressed("left")){
            this.facing = "left";
            this.body.vel.x -=this.body.accel.x * me.timer.tick;
            this.flipX(false);
        }else{
            this.body.vel.x = 0;
        }

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

        if (me.input.isKeyPressed("attack")) {
            if(!this.renderable.isCurrentAnimation("attack")) {

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

                this.renderable.setAnimationFrame();
            }
        }

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

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

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

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

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

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

            if (ydif<-40 && xdif< 70 && xdif>-35){
                this.body.falling = false;
                this.body.vel.y = -1;
            }else if(xdif>-35 && this.facing==='right' && (xdif<0)) {
                this.body.vel.x = 0;
            }else if(xdif<60 && this.facing==='left' && xdif>0){
                this.body.vel.x = 0;
            }

            if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= 400){
                console.log("Hit");
            this.lastHit = this.now;
            response.b.loseHealth();
            }
        }
    }
});

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

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

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

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

    onCollision: function() {

    }

});

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

    this.type = "enemyBaseEntity";

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

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

    },

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

});

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

    this.health = 10;
    this.alwaysUpdate = true;
    this.attacking = false;
    this.lastHit = new Date().getTime();
    this.lastAttacking = new Date().getTime();
    this.now = new Date().getTime();
    this.body.setVelocity(3,20);

    this.type = "EnemyCreep";

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

    },

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

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

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

        this.body.update(delta);

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

    collideHandler: function(response){
        if(response.b.type==='playerBase'){
            this.attacking=true;
            this.lastAttacking=this.now;
            this.body.vel.x = 0;
            this.pos.x = this.pos.x + 1;
            if((this.now-this.lastHit >= 1000)){
                this.lastHit = this.now;
                response.b.loseHealth(1);
            }
        }else if(response.b.type==='PlayerEntity'){
            var xdif = this.pos.x - response.b.pos.x;
            this.attacking=true;
            if(xdif>0){
            this.pos.x = this.pos.x + 1;
            this.body.vel.x = 0;
        }
            if((this.now-this.lastHit >= 1000) && xdif>0){
                this.lastHit = this.now;
                response.b.loseHealth(1);
            }
        }
    }

});

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

        this.alwaysUpdate = true;
    },

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

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

        return true;
    }
});<commit_msg>error correcting<commit_after>game.PlayerEntity = me.Entity.extend({
    init: function(x, y, settings) {
        this._super(me.Entity, 'init', [x, y, {
                image: "player",
                width: 64,
                height: 64,
                spritewidth: "64",
                spriteheight: "64",
                getShape: function() {
                    return(new me.Rect(0, 0, 64, 64)).toPolygon();
                }
            }]);
        this.type = "PlayerEntity";
        this.health = 500;
        this.body.setVelocity(5, 20);
        this.facing = "right";
        this.new = new Date().getTime();
        this.lastHit = this.now;
        this.lastAttack = new Date().getTime();
        me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

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

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

    update: function(delta) {
        this.now = new Date().getTime();
        if (me.input.isKeyPressed("right")) {
            this.facing = "right";
            this.body.vel.x += this.body.accel.x * me.timer.tick;
            this.flipX(true);
        } else if(me.input.isKeyPressed("left")){
            this.facing = "left";
            this.body.vel.x -=this.body.accel.x * me.timer.tick;
            this.flipX(false);
        }else{
            this.body.vel.x = 0;
        }

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

        if (me.input.isKeyPressed("attack")) {
            if(!this.renderable.isCurrentAnimation("attack")) {

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

                this.renderable.setAnimationFrame();
            }
        }

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

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

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

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

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

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

            if (ydif<-40 && xdif< 70 && xdif>-35){
                this.body.falling = false;
                this.body.vel.y = -1;
            }else if(xdif>-35 && this.facing==='right' && (xdif<0)) {
                this.body.vel.x = 0;
                this.pos.x = this.pos.x -1;
            }else if(xdif<60 && 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 >= 400){
            this.lastHit = this.now;
            response.b.loseHealth();
            }
        }
    }
});

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

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

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

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

    onCollision: function() {

    }

});

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

    this.type = "EnemyBaseEntity";

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

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

    },

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

});

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

    this.health = 10;
    this.alwaysUpdate = true;
    this.attacking = false;
    this.lastHit = new Date().getTime();
    this.lastAttacking = new Date().getTime();
    this.now = new Date().getTime();
    this.body.setVelocity(3,20);

    this.type = "EnemyCreep";

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

    },

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

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

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

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

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

        this.body.update(delta);

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

    collideHandler: function(response){
        if(response.b.type==='playerBase'){
            this.attacking=true;
            this.lastAttacking=this.now;
            this.body.vel.x = 0;
            this.pos.x = this.pos.x + 1;
            if((this.now-this.lastHit >= 1000)){
                this.lastHit = this.now;
                response.b.loseHealth(1);
            }
        }else if(response.b.type==='PlayerEntity'){
            var xdif = this.pos.x - response.b.pos.x;
            this.attacking=true;
            if(xdif>0){
            this.pos.x = this.pos.x + 1;
            this.body.vel.x = 0;
        }
            if((this.now-this.lastHit >= 1000) && xdif>0){
                this.lastHit = this.now;
                response.b.loseHealth(1);
            }
        }
    }

});

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

        this.alwaysUpdate = true;
    },

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

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

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


<commit_before>game.PlayerEntity = me.Entity.extend({
	init: function(x, y, settings) {
		this._super(me.Entity, 'init', [x, y, {
			image:"player",
			/*telling the screen how much space to preserve*/
			width: 64,
			height: 64,
			/*spritewidth and height are passing us information. telling us the size of image*/
			spritewidth: "64",
			spriteheight: "64",
			getShpape: function(){
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
			}
		}]);
		//velocity represents current position
	this.body.setVelocity(5, 0);
	},

	update: function() {
		if(me.input.isKeyPressed("right")){
			this.body,vel.x += this.body.accel.x = me.timer.tick;
		}else{
			this.body.vel.x = 0;
		}
		this.body.update(delta);
		return true;
	}

});
			<commit_msg>video 7 with comments<commit_after>game.PlayerEntity = me.Entity.extend({
	init: function(x, y, settings) {
		this._super(me.Entity, 'init', [x, y, {
			image:"player",
			/*telling the screen how much space to preserve*/
			width: 64,
			height: 64,
			/*spritewidth and height are passing us information. telling us the size of image*/
			spritewidth: "64",
			spriteheight: "64",
			getShpape: function(){
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
			}
		}]);
		//velocity represents current position
	this.body.setVelocity(5, 0);
	},

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

});
			<|endoftext|>