<commit_before>/**
 * @author Mat Groves http://matgroves.com/ @Doormat23
 */

/**
 * The Matrix class is now an object, which makes it a lot faster,
 * here is a representation of it :
 * | a | b | tx|
 * | c | d | ty|
 * | 0 | 0 | 1 |
 *
 * @class Matrix
 * @constructor
 */
Phaser.Matrix = function()
{
    /**
     * @property a
     * @type Number
     * @default 1
     */
    this.a = 1;

    /**
     * @property b
     * @type Number
     * @default 0
     */
    this.b = 0;

    /**
     * @property c
     * @type Number
     * @default 0
     */
    this.c = 0;

    /**
     * @property d
     * @type Number
     * @default 1
     */
    this.d = 1;

    /**
     * @property tx
     * @type Number
     * @default 0
     */
    this.tx = 0;

    /**
     * @property ty
     * @type Number
     * @default 0
     */
    this.ty = 0;

    /**
    * @property {number} type - The const type of this object.
    * @readonly
    */
    this.type = Phaser.MATRIX;

};

/**
 * Creates a Matrix object based on the given array. The Element to Matrix mapping order is as follows:
 *
 * a = array[0]
 * b = array[1]
 * c = array[3]
 * d = array[4]
 * tx = array[2]
 * ty = array[5]
 *
 * @method fromArray
 * @param array {Array} The array that the matrix will be populated from.
 */
Phaser.Matrix.prototype.fromArray = function(array)
{
    this.a = array[0];
    this.b = array[1];
    this.c = array[3];
    this.d = array[4];
    this.tx = array[2];
    this.ty = array[5];
};

/**
 * Creates an array from the current Matrix object.
 *
 * @method toArray
 * @param transpose {Boolean} Whether we need to transpose the matrix or not
 * @return {Array} the newly created array which contains the matrix
 */
Phaser.Matrix.prototype.toArray = function(transpose)
{
    if(!this.array) this.array = new PIXI.Float32Array(9);
    var array = this.array;

    if(transpose)
    {
        array[0] = this.a;
        array[1] = this.b;
        array[2] = 0;
        array[3] = this.c;
        array[4] = this.d;
        array[5] = 0;
        array[6] = this.tx;
        array[7] = this.ty;
        array[8] = 1;
    }
    else
    {
        array[0] = this.a;
        array[1] = this.c;
        array[2] = this.tx;
        array[3] = this.b;
        array[4] = this.d;
        array[5] = this.ty;
        array[6] = 0;
        array[7] = 0;
        array[8] = 1;
    }

    return array;
};

/**
 * Get a new position with the current transformation applied.
 * Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering)
 *
 * @method apply
 * @param pos {Point} The origin
 * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input)
 * @return {Point} The new point, transformed through this matrix
 */
Phaser.Matrix.prototype.apply = function(pos, newPos)
{
    newPos = newPos || new Phaser.Point();

    newPos.x = this.a * pos.x + this.c * pos.y + this.tx;
    newPos.y = this.b * pos.x + this.d * pos.y + this.ty;

    return newPos;
};

/**
 * Get a new position with the inverse of the current transformation applied.
 * Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input)
 *
 * @method applyInverse
 * @param pos {Point} The origin
 * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input)
 * @return {Point} The new point, inverse-transformed through this matrix
 */
Phaser.Matrix.prototype.applyInverse = function(pos, newPos)
{
    newPos = newPos || new Phaser.Point();

    var id = 1 / (this.a * this.d + this.c * -this.b);
    var x = pos.x;
    var y = pos.y;

    newPos.x = this.d * id * x + -this.c * id * y + (this.ty * this.c - this.tx * this.d) * id;
    newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id;

    return newPos;
};

/**
 * Translates the matrix on the x and y.
 *
 * @method translate
 * @param {Number} x
 * @param {Number} y
 * @return {Matrix} This matrix. Good for chaining method calls.
 **/
Phaser.Matrix.prototype.translate = function(x, y)
{
    this.tx += x;
    this.ty += y;

    return this;
};

/**
 * Applies a scale transformation to the matrix.
 *
 * @method scale
 * @param {Number} x The amount to scale horizontally
 * @param {Number} y The amount to scale vertically
 * @return {Matrix} This matrix. Good for chaining method calls.
 **/
Phaser.Matrix.prototype.scale = function(x, y)
{
    this.a *= x;
    this.d *= y;
    this.c *= x;
    this.b *= y;
    this.tx *= x;
    this.ty *= y;

    return this;
};

/**
 * Applies a rotation transformation to the matrix.
 * @method rotate
 * @param {Number} angle The angle in radians.
 * @return {Matrix} This matrix. Good for chaining method calls.
 **/
Phaser.Matrix.prototype.rotate = function(angle)
{
    var cos = Math.cos( angle );
    var sin = Math.sin( angle );

    var a1 = this.a;
    var c1 = this.c;
    var tx1 = this.tx;

    this.a = a1 * cos-this.b * sin;
    this.b = a1 * sin+this.b * cos;
    this.c = c1 * cos-this.d * sin;
    this.d = c1 * sin+this.d * cos;
    this.tx = tx1 * cos - this.ty * sin;
    this.ty = tx1 * sin + this.ty * cos;

    return this;
};

/**
 * Appends the given Matrix to this Matrix.
 *
 * @method append
 * @param {Matrix} matrix
 * @return {Matrix} This matrix. Good for chaining method calls.
 */
Phaser.Matrix.prototype.append = function(matrix)
{
    var a1 = this.a;
    var b1 = this.b;
    var c1 = this.c;
    var d1 = this.d;

    this.a  = matrix.a * a1 + matrix.b * c1;
    this.b  = matrix.a * b1 + matrix.b * d1;
    this.c  = matrix.c * a1 + matrix.d * c1;
    this.d  = matrix.c * b1 + matrix.d * d1;

    this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx;
    this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty;

    return this;
};

/**
 * Resets this Matix to an identity (default) matrix.
 *
 * @method identity
 * @return {Matrix} This matrix. Good for chaining method calls.
 */
Phaser.Matrix.prototype.identity = function()
{
    this.a = 1;
    this.b = 0;
    this.c = 0;
    this.d = 1;
    this.tx = 0;
    this.ty = 0;

    return this;
};

Phaser.identityMatrix = new Phaser.Matrix();

//  Because PIXI uses its own type, we'll replace it with ours to avoid duplicating code or confusion.
PIXI.Matrix = Phaser.Matrix;
PIXI.identityMatrix = Phaser.identityMatrix;
<commit_msg>Fixed Matrix.apply.<commit_after>/**
 * @author Mat Groves http://matgroves.com/ @Doormat23
 */

/**
 * The Matrix class is now an object, which makes it a lot faster,
 * here is a representation of it :
 * | a | b | tx|
 * | c | d | ty|
 * | 0 | 0 | 1 |
 *
 * @class Matrix
 * @constructor
 */
Phaser.Matrix = function()
{
    /**
     * @property a
     * @type Number
     * @default 1
     */
    this.a = 1;

    /**
     * @property b
     * @type Number
     * @default 0
     */
    this.b = 0;

    /**
     * @property c
     * @type Number
     * @default 0
     */
    this.c = 0;

    /**
     * @property d
     * @type Number
     * @default 1
     */
    this.d = 1;

    /**
     * @property tx
     * @type Number
     * @default 0
     */
    this.tx = 0;

    /**
     * @property ty
     * @type Number
     * @default 0
     */
    this.ty = 0;

    /**
    * @property {number} type - The const type of this object.
    * @readonly
    */
    this.type = Phaser.MATRIX;

};

/**
 * Creates a Matrix object based on the given array. The Element to Matrix mapping order is as follows:
 *
 * a = array[0]
 * b = array[1]
 * c = array[3]
 * d = array[4]
 * tx = array[2]
 * ty = array[5]
 *
 * @method fromArray
 * @param array {Array} The array that the matrix will be populated from.
 */
Phaser.Matrix.prototype.fromArray = function(array)
{
    this.a = array[0];
    this.b = array[1];
    this.c = array[3];
    this.d = array[4];
    this.tx = array[2];
    this.ty = array[5];
};

/**
 * Creates an array from the current Matrix object.
 *
 * @method toArray
 * @param transpose {Boolean} Whether we need to transpose the matrix or not
 * @return {Array} the newly created array which contains the matrix
 */
Phaser.Matrix.prototype.toArray = function(transpose)
{
    if(!this.array) this.array = new PIXI.Float32Array(9);
    var array = this.array;

    if(transpose)
    {
        array[0] = this.a;
        array[1] = this.b;
        array[2] = 0;
        array[3] = this.c;
        array[4] = this.d;
        array[5] = 0;
        array[6] = this.tx;
        array[7] = this.ty;
        array[8] = 1;
    }
    else
    {
        array[0] = this.a;
        array[1] = this.c;
        array[2] = this.tx;
        array[3] = this.b;
        array[4] = this.d;
        array[5] = this.ty;
        array[6] = 0;
        array[7] = 0;
        array[8] = 1;
    }

    return array;
};

/**
 * Get a new position with the current transformation applied.
 * Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering)
 *
 * @method apply
 * @param pos {Point} The origin
 * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input)
 * @return {Point} The new point, transformed through this matrix
 */
Phaser.Matrix.prototype.apply = function(pos, newPos)
{
    newPos = newPos || new Phaser.Point();

    var x = pos.x;
    var y = pos.y

    newPos.x = this.a * x + this.c * y + this.tx;
    newPos.y = this.b * x + this.d * y + this.ty;

    return newPos;
};

/**
 * Get a new position with the inverse of the current transformation applied.
 * Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input)
 *
 * @method applyInverse
 * @param pos {Point} The origin
 * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input)
 * @return {Point} The new point, inverse-transformed through this matrix
 */
Phaser.Matrix.prototype.applyInverse = function(pos, newPos)
{
    newPos = newPos || new Phaser.Point();

    var id = 1 / (this.a * this.d + this.c * -this.b);
    var x = pos.x;
    var y = pos.y;

    newPos.x = this.d * id * x + -this.c * id * y + (this.ty * this.c - this.tx * this.d) * id;
    newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id;

    return newPos;
};

/**
 * Translates the matrix on the x and y.
 *
 * @method translate
 * @param {Number} x
 * @param {Number} y
 * @return {Matrix} This matrix. Good for chaining method calls.
 **/
Phaser.Matrix.prototype.translate = function(x, y)
{
    this.tx += x;
    this.ty += y;

    return this;
};

/**
 * Applies a scale transformation to the matrix.
 *
 * @method scale
 * @param {Number} x The amount to scale horizontally
 * @param {Number} y The amount to scale vertically
 * @return {Matrix} This matrix. Good for chaining method calls.
 **/
Phaser.Matrix.prototype.scale = function(x, y)
{
    this.a *= x;
    this.d *= y;
    this.c *= x;
    this.b *= y;
    this.tx *= x;
    this.ty *= y;

    return this;
};

/**
 * Applies a rotation transformation to the matrix.
 * @method rotate
 * @param {Number} angle The angle in radians.
 * @return {Matrix} This matrix. Good for chaining method calls.
 **/
Phaser.Matrix.prototype.rotate = function(angle)
{
    var cos = Math.cos( angle );
    var sin = Math.sin( angle );

    var a1 = this.a;
    var c1 = this.c;
    var tx1 = this.tx;

    this.a = a1 * cos-this.b * sin;
    this.b = a1 * sin+this.b * cos;
    this.c = c1 * cos-this.d * sin;
    this.d = c1 * sin+this.d * cos;
    this.tx = tx1 * cos - this.ty * sin;
    this.ty = tx1 * sin + this.ty * cos;

    return this;
};

/**
 * Appends the given Matrix to this Matrix.
 *
 * @method append
 * @param {Matrix} matrix
 * @return {Matrix} This matrix. Good for chaining method calls.
 */
Phaser.Matrix.prototype.append = function(matrix)
{
    var a1 = this.a;
    var b1 = this.b;
    var c1 = this.c;
    var d1 = this.d;

    this.a  = matrix.a * a1 + matrix.b * c1;
    this.b  = matrix.a * b1 + matrix.b * d1;
    this.c  = matrix.c * a1 + matrix.d * c1;
    this.d  = matrix.c * b1 + matrix.d * d1;

    this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx;
    this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty;

    return this;
};

/**
 * Resets this Matix to an identity (default) matrix.
 *
 * @method identity
 * @return {Matrix} This matrix. Good for chaining method calls.
 */
Phaser.Matrix.prototype.identity = function()
{
    this.a = 1;
    this.b = 0;
    this.c = 0;
    this.d = 1;
    this.tx = 0;
    this.ty = 0;

    return this;
};

Phaser.identityMatrix = new Phaser.Matrix();

//  Because PIXI uses its own type, we'll replace it with ours to avoid duplicating code or confusion.
PIXI.Matrix = Phaser.Matrix;
PIXI.identityMatrix = Phaser.identityMatrix;
<|endoftext|>


<commit_before>
// @require ../init.js
// @require ./elements.js

(function ( $ ) {

  // On mobile a `resize` event may get triggered because of the chrome of the browser

  /* RESIZE */

  let width = $.window.outerWidth,
      height = $.window.outerHeight,
      pixelRatio = $.window.devicePixelRatio || 1; // Used for more reliable zoom detection

  $.$window.on ( 'resize', (e) => {

    const newPixelRatio = $.window.devicePixelRatio || 1,
          newWidth = $.window.outerWidth;

    if ( newWidth !== width || newPixelRatio !== pixelRatio ) {

      width = newWidth;

      $.$window.trigger ( 'resize:width' );

    }

    const newHeight = $.window.outerHeight;

    if ( newHeight !== height || newPixelRatio !== pixelRatio ) {

      height = newHeight;

      $.$window.trigger ( 'resize:height' );

    }

    pixelRatio = newPixelRatio;

  });

}( window.$ ));
<commit_msg>Resize events: more reliable detection<commit_after>
// @require ../init.js
// @require ./elements.js

(function ( $ ) {

  // On mobile a `resize` event may get triggered because of the chrome of the browser

  /* RESIZE */

  let width = $.window.outerWidth,
      height = $.window.outerHeight,
      pixelRatio = $.window.devicePixelRatio || 1; // Used for more reliable zoom detection

  $.$window.on ( 'resize', (e) => {

    const newPixelRatio = $.window.devicePixelRatio || 1,
          newWidth = $.window.outerWidth,
          newHeight = $.window.outerHeight;

    const didPixelRatioChange = newPixelRatio !== pixelRatio,
          didWidthChange = newWidth !== width,
          didHeightChange = newHeight !== height,
          didSomethingChange = didPixelRatioChange || didWidthChange || didHeightChange; // Sometimes for some reason nothing actually changed

    if ( !didSomethingChange || didWidthChange || didPixelRatioChange ) {

      width = newWidth;

      $.$window.trigger ( 'resize:width' );

    }

    if ( !didSomethingChange || didHeightChange || didPixelRatioChange ) {

      height = newHeight;

      $.$window.trigger ( 'resize:height' );

    }

    pixelRatio = newPixelRatio;

  });

}( window.$ ));
<|endoftext|>


<commit_before>var Engine = {

  smoothCamera: {
    target: { x: 0, y: 0 },
    delta: { x: 0, y: 0 },
    step: 0.1,
    precision: 0.001,
  },

  updatesPerSecond: 60,

  run: function() {

    var WebGL = (function () {
      try {
        return
          !!window.WebGLRenderingContext
          && !!document.createElement('canvas').getContext('experimental-webgl');
      } catch(e) {
        return false;
      }
    })();

    this.renderer = WebGL ? new THREE.WebGLRenderer() : new THREE.CanvasRenderer();
    this.renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(this.renderer.domElement);

    this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);
    this.camera.position.z = 5;

    this.scene = new THREE.Scene();
    this.meshes = new Array();

    this.registerClick();
    this.registerRender();
    this.registerWindowResize();

    this.onStart();

  },

  registerUpdate: function(f) {

    _.delay(_.bind(f, this), 1000 / this.updatesPerSecond);

  },

  getGridScale: function() {

    return {
      x: this.block.size.x + this.block.margin.x,
      y: this.block.size.y + this.block.margin.y,
    };

  },

  setCamera: function(x, y) {

    this.smoothCamera.target = { x: x, y: y };
    this.smoothCamera.delta = { x: 0, y: 0 };

    var scale = this.getGridScale();
    this.camera.position.x = this.smoothCamera.target.x * scale.x;
    this.camera.position.y = this.smoothCamera.target.y * scale.y;

  },

  moveCamera: function(dx, dy) {

    this.smoothCamera.target.x += dx;
    this.smoothCamera.target.y += dy;

    this.smoothCamera.delta.x += dx;
    this.smoothCamera.delta.y += dy;

    this.registerCameraDeltaUpdate();

  },

  moveCameraTo: function(x, y) {

    this.moveCamera(x - this.smoothCamera.target.x, y - this.smoothCamera.target.y);

  },

  onStart: function() {

    _.extend(this, {

      block: {
        size: { x: 1, y: 1, z: .25 },
        margin: { x: .75, y: .75 },
      },

      geometry: new THREE.CubeGeometry(1, 1, .2),

      materials: {
        empty: new THREE.MeshBasicMaterial({ color: 0xffffff, wireframe: true }),
        good: new THREE.MeshBasicMaterial({ color: 0x55ff33, wireframe: true }),
        bad: new THREE.MeshBasicMaterial({ color: 0xff0000, wireframe: true }),
        current: new THREE.MeshBasicMaterial({ color: 0x33ccff, wireframe: true }),
      },

    });

    for (var y = 0; y < 3; ++y) {
      for (var x = 0; x < 5; ++x) {
        var mesh = new THREE.Mesh(this.geometry, this.materials.empty);
        mesh.position.x = x * (this.block.size.x + this.block.margin.x);
        mesh.position.y = y * (this.block.size.y + this.block.margin.y);
        this.scene.add(mesh);
      }
    }

  },

  onRender: function() {

    this.renderer.render(this.scene, this.camera);

  },

  registerRender: function() {

    requestAnimationFrame(
      _.bind(
        function() {
          this.onRender();
          this.registerRender();
        },
        this
      )
    );

  },

  onWindowResize: function() {

    this.renderer.setSize(window.innerWidth, window.innerHeight);
    this.camera.aspect = window.innerWidth / window.innerHeight;
    this.camera.updateProjectionMatrix();

  },

  registerWindowResize: function() {

    window.addEventListener('resize', _.bind(this.onWindowResize, this));

  },

  onCameraDeltaUpdate: function() {

    var gridStep = {
      x: this.smoothCamera.step * this.smoothCamera.delta.x,
      y: this.smoothCamera.step * this.smoothCamera.delta.y,
    };

    this.smoothCamera.delta.x -= gridStep.x;
    this.smoothCamera.delta.y -= gridStep.y;

    var scale = this.getGridScale();

    var realStep = {
      x: gridStep.x * scale.x,
      y: gridStep.y * scale.y,
    };

    this.camera.position.x += realStep.x;
    this.camera.position.y += realStep.y;

    if (
      Math.abs(this.smoothCamera.delta.x) > this.smoothCamera.precision
      || Math.abs(this.smoothCamera.delta.y) > this.smoothCamera.precision
    ) {
      console.log("spinnin'");
      this.registerCameraDeltaUpdate();
    } else {
      this.setCamera(this.smoothCamera.target.x, this.smoothCamera.target.y);
    }

  },

  registerCameraDeltaUpdate: function() {

    this.registerUpdate(this.onCameraDeltaUpdate);

  },

  onClick: function(x, y) {

    var rx = x / window.innerWidth * 2 - 1;
    var ry = y / window.innerHeight * -2 + 1;

    if (rx * rx + ry * ry < 0.16) {

      this.onButtonClick();

    } else {

      var a = Math.atan2(ry, rx);

      var dx = 0;
      var dy = 0;

      if (Math.abs(a) < Math.PI / 4) {
        dx = 1;
      } else if (Math.abs(a) > 3 * Math.PI / 4) {
        dx = -1;
      }

      if (Math.abs(a - Math.PI / 2) < Math.PI / 4) {
        dy = 1;
      } else if (Math.abs(a + Math.PI / 2) < Math.PI / 4) {
        dy = -1;
      }

      this.onDirectionClick(dx, dy);

    }

  },

  registerClick: function() {

    document.addEventListener(
      'click',
      _.bind(
        function(e) {
          this.onClick(e.clientX, e.clientY);
          return false;
        },
        this
      )
    );

  },

  onButtonClick: function() {

    console.debug("middle button");

  },

  onDirectionClick: function(dx, dy) {

    console.debug("direction button", dx, dy);

  },

};

Engine.run();
<commit_msg>Refactored the initialization code<commit_after>var Engine = {

  smoothCamera: {
    target: { x: 0, y: 0 },
    delta: { x: 0, y: 0 },
    step: 0.1,
    precision: 0.001,
  },

  updatesPerSecond: 60,

  run: function() {

    var WebGL = (function () {
      try {
        return
          !!window.WebGLRenderingContext
          && !!document.createElement('canvas').getContext('experimental-webgl');
      } catch(e) {
        return false;
      }
    })();

    _.extend(this, {

      block: {
        size: { x: 1, y: 1, z: .25 },
        margin: { x: .75, y: .75 },
      },

      renderer: WebGL ? new THREE.WebGLRenderer() : new THREE.CanvasRenderer(),
      scene: new THREE.Scene(),
      camera: new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000),

      meshes: [],
      geometry: new THREE.CubeGeometry(1, 1, .2),
      materials: {
        empty: new THREE.MeshBasicMaterial({ color: 0xffffff, wireframe: true }),
        good: new THREE.MeshBasicMaterial({ color: 0x55ff33, wireframe: true }),
        bad: new THREE.MeshBasicMaterial({ color: 0xff0000, wireframe: true }),
        current: new THREE.MeshBasicMaterial({ color: 0x33ccff, wireframe: true }),
      },

    });

    this.renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(this.renderer.domElement);
    this.camera.position.z = 5;

    this.registerWindowResize();
    this.registerRender();
    this.registerClick();

  },

  registerUpdate: function(f) {

    _.delay(_.bind(f, this), 1000 / this.updatesPerSecond);

  },

  getGridToScreenScale: function() {

    return {
      x: this.block.size.x + this.block.margin.x,
      y: this.block.size.y + this.block.margin.y,
    };

  },

  setCamera: function(x, y) {

    this.smoothCamera.target = { x: x, y: y };
    this.smoothCamera.delta = { x: 0, y: 0 };

    var scale = this.getGridToScreenScale();
    this.camera.position.x = this.smoothCamera.target.x * scale.x;
    this.camera.position.y = this.smoothCamera.target.y * scale.y;

  },

  moveCamera: function(dx, dy) {

    this.smoothCamera.target.x += dx;
    this.smoothCamera.target.y += dy;

    this.smoothCamera.delta.x += dx;
    this.smoothCamera.delta.y += dy;

    this.registerCameraDeltaUpdate();

  },

  moveCameraTo: function(x, y) {

    this.moveCamera(x - this.smoothCamera.target.x, y - this.smoothCamera.target.y);

  },

  onRender: function() {

    this.renderer.render(this.scene, this.camera);

  },

  registerRender: function() {

    requestAnimationFrame(
      _.bind(
        function() {
          this.onRender();
          this.registerRender();
        },
        this
      )
    );

  },

  onWindowResize: function() {

    this.renderer.setSize(window.innerWidth, window.innerHeight);
    this.camera.aspect = window.innerWidth / window.innerHeight;
    this.camera.updateProjectionMatrix();

  },

  registerWindowResize: function() {

    window.addEventListener('resize', _.bind(this.onWindowResize, this));

  },

  onCameraDeltaUpdate: function() {

    var gridStep = {
      x: this.smoothCamera.step * this.smoothCamera.delta.x,
      y: this.smoothCamera.step * this.smoothCamera.delta.y,
    };

    this.smoothCamera.delta.x -= gridStep.x;
    this.smoothCamera.delta.y -= gridStep.y;

    var scale = this.getGridToScreenScale();

    var realStep = {
      x: gridStep.x * scale.x,
      y: gridStep.y * scale.y,
    };

    this.camera.position.x += realStep.x;
    this.camera.position.y += realStep.y;

    if (
      Math.abs(this.smoothCamera.delta.x) > this.smoothCamera.precision
      || Math.abs(this.smoothCamera.delta.y) > this.smoothCamera.precision
    ) {
      this.registerCameraDeltaUpdate();
    } else {
      this.setCamera(this.smoothCamera.target.x, this.smoothCamera.target.y);
    }

  },

  registerCameraDeltaUpdate: function() {

    this.registerUpdate(this.onCameraDeltaUpdate);

  },

  onClick: function(x, y) {

    var rx = x / window.innerWidth * 2 - 1;
    var ry = y / window.innerHeight * -2 + 1;

    if (rx * rx + ry * ry < 0.16) {

      this.onButtonClick();

    } else {

      var a = Math.atan2(ry, rx);

      var dx = 0;
      var dy = 0;

      if (Math.abs(a) < Math.PI / 4) {
        dx = 1;
      } else if (Math.abs(a) > 3 * Math.PI / 4) {
        dx = -1;
      }

      if (Math.abs(a - Math.PI / 2) < Math.PI / 4) {
        dy = 1;
      } else if (Math.abs(a + Math.PI / 2) < Math.PI / 4) {
        dy = -1;
      }

      this.onDirectionClick(dx, dy);

    }

  },

  registerClick: function() {

    document.addEventListener(
      'click',
      _.bind(
        function(e) {
          this.onClick(e.clientX, e.clientY);
          return false;
        },
        this
      )
    );

  },

  onButtonClick: function() {

    console.debug("middle button");

  },

  onDirectionClick: function(dx, dy) {

    console.debug("direction button", dx, dy);

  },

};

Engine.run();
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete<commit_msg>Well that seemed pretty easy<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete"<|endoftext|>


<commit_before>var BrowserConnection = require('logux-sync/browser-connection')
var MemoryStore = require('logux-core/memory-store')
var ClientSync = require('logux-sync/client-sync')
var Reconnect = require('logux-sync/reconnect')
var shortid = require('shortid')
var Log = require('logux-core/log')

var IndexedStore = require('./indexed-store')

/**
 * Low-level browser API for Logux.
 *
 * @param {object} options Client options.
 * @param {string} options.url Server URL.
 * @param {string} options.subprotocol Client subprotocol version
 *                                     in SemVer format.
 * @param {number|string|false} options.userId User ID. Pass `false` on no user.
 * @param {any} [options.credentials] Client credentials for authentication.
 * @param {string} [options.prefix="logux"] Prefix for `IndexedDB` database
 *                                          to run multiple Logux instances
 *                                          on same web page.
 * @param {string|number} [options.nodeId] Unique client ID.
 *                                         Compacted UUID, by default.
 * @param {number} [options.timeout=20000] Timeout in milliseconds
 *                                         to break connection.
 * @param {number} [options.ping=10000] Milliseconds since last message to test
 *                                      connection by sending ping.
 * @param {Store} [options.store] Store to save log. Will be `IndexedStore`,
 *                                by default.
 * @param {number} [options.minDelay=1000] Minimum delay between reconnections.
 * @param {number} [options.maxDelay=5000] Maximum delay between reconnections.
 * @param {number} [options.attempts=Infinity] Maximum reconnection attempts.
 * @param {bool} [options.allowDangerousProtocol=false] Hide warning in case
 *                                                      using ws: in production.
 *
 * @example
 * token = document.querySelector('meta[name=token]')
 *
 * import Client from 'logux-client/client'
 * const app = new Client({
 *   credentials: token.content,
 *   subprotocol: '1.0.0',
 *   url: 'wss://example.com:1337'
 * })
 * app.sync.connection.connect()
 *
 * @class
 */
function Client (options) {
  /**
   * Client options.
   * @type {object}
   *
   * @example
   * console.log('Logux node ID is ' + app.options.nodeId)
   */
  this.options = options || { }

  if (typeof this.options.url === 'undefined') {
    throw new Error('Missed url option in Logux client')
  }
  if (typeof this.options.subprotocol === 'undefined') {
    throw new Error('Missed subprotocol option in Logux client')
  }
  if (typeof this.options.userId === 'undefined') {
    throw new Error('Missed userId option in Logux client. ' +
                    'Pass false if you have no users.')
  }

  if (typeof this.options.prefix === 'undefined') {
    this.options.prefix = 'logux'
  }

  var userId = this.options.userId
  if (userId) {
    userId += ':'
  } else {
    userId = ''
  }
  this.options.nodeId = userId + shortid.generate()

  var auth
  if (/^ws:\/\//.test(this.options.url) && !options.allowDangerousProtocol) {
    auth = function (cred) {
      if (typeof cred === 'object' && cred.env === 'development') {
        return Promise.resolve(true)
      } else {
        console.error(
          'Without SSL, old proxies can block WebSockets. ' +
          'Use WSS connection for Logux or set allowDangerousProtocol option.'
        )
        return Promise.resolve(false)
      }
    }
  }

  var store = this.options.store
  if (!store) {
    if (global.indexedDB) {
      store = new IndexedStore(this.options.prefix)
    } else {
      store = new MemoryStore()
    }
  }

  /**
   * Client events log.
   * @type {Log}
   *
   * @example
   * app.log.keep(customKeeper)
   */
  this.log = new Log({ store: store, nodeId: this.options.nodeId })

  var ws = new BrowserConnection(this.options.url)
  var connection = new Reconnect(ws, {
    minDelay: this.options.minDelay,
    maxDelay: this.options.maxDelay,
    attempts: this.options.attempts
  })

  /**
   * Sync instance from `logux-sync` to synchronize logs.
   * @type {ClientSync}
   *
   * @example
   * if (client.sync.state === 'synchronized')
   */
  this.sync = new ClientSync(this.options.nodeId, this.log, connection, {
    credentials: this.options.credentials,
    subprotocol: this.options.subprotocol,
    timeout: this.options.timeout,
    ping: this.options.ping,
    auth: auth
  })
}

module.exports = Client
<commit_msg>Remove unnecessary else condition (#10)<commit_after>var BrowserConnection = require('logux-sync/browser-connection')
var MemoryStore = require('logux-core/memory-store')
var ClientSync = require('logux-sync/client-sync')
var Reconnect = require('logux-sync/reconnect')
var shortid = require('shortid')
var Log = require('logux-core/log')

var IndexedStore = require('./indexed-store')

/**
 * Low-level browser API for Logux.
 *
 * @param {object} options Client options.
 * @param {string} options.url Server URL.
 * @param {string} options.subprotocol Client subprotocol version
 *                                     in SemVer format.
 * @param {number|string|false} options.userId User ID. Pass `false` on no user.
 * @param {any} [options.credentials] Client credentials for authentication.
 * @param {string} [options.prefix="logux"] Prefix for `IndexedDB` database
 *                                          to run multiple Logux instances
 *                                          on same web page.
 * @param {string|number} [options.nodeId] Unique client ID.
 *                                         Compacted UUID, by default.
 * @param {number} [options.timeout=20000] Timeout in milliseconds
 *                                         to break connection.
 * @param {number} [options.ping=10000] Milliseconds since last message to test
 *                                      connection by sending ping.
 * @param {Store} [options.store] Store to save log. Will be `IndexedStore`,
 *                                by default.
 * @param {number} [options.minDelay=1000] Minimum delay between reconnections.
 * @param {number} [options.maxDelay=5000] Maximum delay between reconnections.
 * @param {number} [options.attempts=Infinity] Maximum reconnection attempts.
 * @param {bool} [options.allowDangerousProtocol=false] Hide warning in case
 *                                                      using ws: in production.
 *
 * @example
 * token = document.querySelector('meta[name=token]')
 *
 * import Client from 'logux-client/client'
 * const app = new Client({
 *   credentials: token.content,
 *   subprotocol: '1.0.0',
 *   url: 'wss://example.com:1337'
 * })
 * app.sync.connection.connect()
 *
 * @class
 */
function Client (options) {
  /**
   * Client options.
   * @type {object}
   *
   * @example
   * console.log('Logux node ID is ' + app.options.nodeId)
   */
  this.options = options || { }

  if (typeof this.options.url === 'undefined') {
    throw new Error('Missed url option in Logux client')
  }
  if (typeof this.options.subprotocol === 'undefined') {
    throw new Error('Missed subprotocol option in Logux client')
  }
  if (typeof this.options.userId === 'undefined') {
    throw new Error('Missed userId option in Logux client. ' +
                    'Pass false if you have no users.')
  }

  if (typeof this.options.prefix === 'undefined') {
    this.options.prefix = 'logux'
  }

  var userId = this.options.userId
  if (userId) {
    userId += ':'
  } else {
    userId = ''
  }
  this.options.nodeId = userId + shortid.generate()

  var auth
  if (/^ws:\/\//.test(this.options.url) && !options.allowDangerousProtocol) {
    auth = function (cred) {
      if (typeof cred === 'object' && cred.env === 'development') {
        return Promise.resolve(true)
      }

      console.error(
        'Without SSL, old proxies can block WebSockets. ' +
        'Use WSS connection for Logux or set allowDangerousProtocol option.'
      )
      return Promise.resolve(false)
    }
  }

  var store = this.options.store
  if (!store) {
    if (global.indexedDB) {
      store = new IndexedStore(this.options.prefix)
    } else {
      store = new MemoryStore()
    }
  }

  /**
   * Client events log.
   * @type {Log}
   *
   * @example
   * app.log.keep(customKeeper)
   */
  this.log = new Log({ store: store, nodeId: this.options.nodeId })

  var ws = new BrowserConnection(this.options.url)
  var connection = new Reconnect(ws, {
    minDelay: this.options.minDelay,
    maxDelay: this.options.maxDelay,
    attempts: this.options.attempts
  })

  /**
   * Sync instance from `logux-sync` to synchronize logs.
   * @type {ClientSync}
   *
   * @example
   * if (client.sync.state === 'synchronized')
   */
  this.sync = new ClientSync(this.options.nodeId, this.log, connection, {
    credentials: this.options.credentials,
    subprotocol: this.options.subprotocol,
    timeout: this.options.timeout,
    ping: this.options.ping,
    auth: auth
  })
}

module.exports = Client
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {<commit_msg>One more User Story done<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
<|endoftext|>


<commit_before>/*
 * server.js: Rackspace Cloud Files file
 *
 * (C) 2013 Rackspace
 *      Ken Perkins
 * MIT LICENSE
 *
 */

var utile = require('utile'),
    base = require('../../openstack/storage/file');

var File = exports.File = function File(client, details) {
  base.File.call(this, client, details);
};

utile.inherits(File, base.File);

File.prototype.purgeFromCdn = function (emails, callback) {
  this.client.purgeFileFromCdn(this.container, this, emails, callback);
};<commit_msg>Adding toJSON for file<commit_after>/*
 * server.js: Rackspace Cloud Files file
 *
 * (C) 2013 Rackspace
 *      Ken Perkins
 * MIT LICENSE
 *
 */

var utile = require('utile'),
  base = require('../../openstack/storage/file'),
  _ = require('underscore');

var File = exports.File = function File(client, details) {
  base.File.call(this, client, details);
};

utile.inherits(File, base.File);

File.prototype.purgeFromCdn = function (emails, callback) {
  this.client.purgeFileFromCdn(this.container, this, emails, callback);
};

File.prototype.toJSON = function () {
  return _.pick(this, ['name', 'size', 'contentType', 'lastModified',
    'container', 'etag', 'metadata']);
};<|endoftext|>


<commit_before>var flags = require('flags'),
    WebSocket = require('ws'),
    Log = require('modulelog')('mongodb-replica-maintainer'),
    pendingConnect = null,
    pendingReconnect = null,
    pendingAdd = null,
    pingInterval = null,
    server = '',
    ourHostname = '';

flags.defineString('server', '', 'maintainer server endpoint');
flags.defineString('host', '', 'mongodb host string or "" to rely on server');
flags.defineBoolean('hidden', false, 'set the replica hidden option');
flags.defineInteger('ping', 15000, 'ms between pings (2 pings means failed)');
flags.defineInteger('reconnect', 5000, 'ms before reconnecting');
flags.defineInteger('priority', 0, 'this replica\'s priority');
flags.defineInteger('votes', 0, 'this replica\'s votes');
flags.defineString('logger', 'default', 'the class to use for logging');
flags.defineString('log-level', 'info', 'the log level');
flags.parse();
server = flags.get('server');

Log.setClass(flags.get('logger'));
Log.setLevel(flags.get('log-level'));

function reconnect() {
    if (pendingReconnect || !flags.get('reconnect')) {
        return;
    }
    //if we lose the connection, try to reconnect in x seconds
    pendingReconnect = setTimeout(resolveAndConnect, Math.max(100, flags.get('reconnect')));
}

function resolveAndConnect() {
    if (server.indexOf('srv://') === 0) {
        var srv = require('srvclient'),
            hostname = server.substr(6);
        Log.debug('Resolving srv address', {hostname: hostname});
        srv.getTarget(hostname, function(err, target) {
            if (err) {
                Log.error('Failed to resolve srv hostname', {hostname: hostname, error: err});
                setTimeout(resolveAndConnect, Math.max(100, flags.get('reconnect')));
                return;
            }
            Log.debug('Resolving srv target', {target: target, hostname: hostname});
            target.resolve(function(err, addr) {
                if (err) {
                    Log.error('Failed to resolve srv target', {target: target, hostname: hostname, error: err});
                    setTimeout(resolveAndConnect, Math.max(100, flags.get('reconnect')));
                    return;
                }
                connect('ws://' + [addr, target.port].join(':'));
            });
        });
    } else {
        connect(server);
    }
}

function sendAdd(ws) {
    clearTimeout(pendingAdd);
    pendingAdd = null;
    if (ws.readyState !== WebSocket.OPEN) {
        return;
    }
    var host = flags.get('host') || undefined,
        hidden = flags.get('hidden'),
        pri = flags.get('priority'),
        votes = flags.get('votes');
    Log.debug('Sending add', {host: host, hidden: hidden, priority: pri, votes: votes});
    ws.send(JSON.stringify({
        cmd: 'add',
        host: host,
        hidden: hidden,
        priority: pri,
        votes: votes
    }));
    pendingAdd = setTimeout(function() {
        Log.error("Timed out waiting for response to add", {url: ws.url});
        sendAdd(ws);
    }, 15000);
}

function startPing(ws) {
    clearInterval(pingInterval);
    if (!flags.get('ping')) {
        return;
    }
    var interval = Math.max(1000, flags.get('ping'));
    pingInterval = setInterval(function() {
        if (ws.readyState !== WebSocket.OPEN) {
            return;
        }
        ws.ping();
        if (Date.now() - ws.lastPong >= (2 * interval)) {
            Log.error("Timed out waiting for pong", {url: ws.url});
            ws.close();
        }
    }, interval);
}

function connect(address) {
    clearTimeout(pendingReconnect);
    pendingReconnect = null;
    clearTimeout(pendingConnect);
    pendingConnect = null;

    if (address.indexOf('://') === -1) {
        address = 'ws://' + address;
    }

    Log.debug("Connecting to ws", {address: address});

    var ws = new WebSocket(address);
    ws.on('open', function() {
        Log.info("Connected to ws", {address: address});
        clearTimeout(pendingConnect);
        pendingConnect = null;
        //since we just connected we got a "pong"
        ws.lastPong = Date.now();
        sendAdd(ws);
    });
    ws.on('message', function(message) {
        Log.debug("Received message", {message: message});
        var result;
        try {
            result = JSON.parse(message);
        } catch (e) {
            Log.error("Received invalid json", {message: message, error: e});
            ws.close();
            return;
        }
        if (result.hasOwnProperty('added')) {
            clearTimeout(pendingAdd);
            pendingAdd = null;
            if (!result.success) {
                Log.error("Failed to add", {error: result.error});
                pendingAdd = setTimeout(function() {
                    sendAdd(ws);
                }, (Math.random() * 5000) + 10000); //randomly between 10-15 seconds
            }
            Log.info("Added", {hostname: result.added});
            ourHostname = result.added;
            //since we just received a message we got a "pong"
            ws.lastPong = Date.now();
            startPing(ws);
            return;
        }
        if (result.hasOwnProperty('removed') && result.removed === ourHostname && pendingAdd === null) {
            Log.error("Removed from replica set", {hostname: result.removed});
            pendingAdd = setTimeout(function() {
                sendAdd(ws);
            }, (Math.random() * 5000) + 10000); //randomly between 10-15 seconds
        }
    });
    ws.on('error', function(err) {
        Log.error("Error from ws", {error: err});
        clearInterval(pingInterval);
        pingInterval = null;
        clearInterval(pendingAdd);
        pendingAdd = null;
        reconnect();
    });
    ws.on('pong', function() {
        Log.debug("Received pong");
        ws.lastPong = Date.now();
    });
    ws.on('close', function() {
        Log.error("Disconnected from ws", {address: address});
        clearInterval(pingInterval);
        pingInterval = null;
        clearInterval(pendingAdd);
        pendingAdd = null;
        reconnect();
    });

    pendingConnect = setTimeout(function() {
        Log.error("Timed out waiting to connect to ws", {address: address});
        ws.terminate();
        reconnect();
    }, 15000);
}

resolveAndConnect();
<commit_msg>Keep srv resolving at info<commit_after>var flags = require('flags'),
    WebSocket = require('ws'),
    Log = require('modulelog')('mongodb-replica-maintainer'),
    pendingConnect = null,
    pendingReconnect = null,
    pendingAdd = null,
    pingInterval = null,
    server = '',
    ourHostname = '';

flags.defineString('server', '', 'maintainer server endpoint');
flags.defineString('host', '', 'mongodb host string or "" to rely on server');
flags.defineBoolean('hidden', false, 'set the replica hidden option');
flags.defineInteger('ping', 15000, 'ms between pings (2 pings means failed)');
flags.defineInteger('reconnect', 5000, 'ms before reconnecting');
flags.defineInteger('priority', 0, 'this replica\'s priority');
flags.defineInteger('votes', 0, 'this replica\'s votes');
flags.defineString('logger', 'default', 'the class to use for logging');
flags.defineString('log-level', 'info', 'the log level');
flags.parse();
server = flags.get('server');

Log.setClass(flags.get('logger'));
Log.setLevel(flags.get('log-level'));

function reconnect() {
    if (pendingReconnect || !flags.get('reconnect')) {
        return;
    }
    //if we lose the connection, try to reconnect in x seconds
    pendingReconnect = setTimeout(resolveAndConnect, Math.max(100, flags.get('reconnect')));
}

function resolveAndConnect() {
    if (server.indexOf('srv://') === 0) {
        var srv = require('srvclient'),
            hostname = server.substr(6);
        Log.info('Resolving srv address', {hostname: hostname});
        srv.getTarget(hostname, function(err, target) {
            if (err) {
                Log.error('Failed to resolve srv hostname', {hostname: hostname, error: err});
                setTimeout(resolveAndConnect, Math.max(100, flags.get('reconnect')));
                return;
            }
            Log.debug('Resolving srv target', {target: target, hostname: hostname});
            target.resolve(function(err, addr) {
                if (err) {
                    Log.error('Failed to resolve srv target', {target: target, hostname: hostname, error: err});
                    setTimeout(resolveAndConnect, Math.max(100, flags.get('reconnect')));
                    return;
                }
                connect('ws://' + [addr, target.port].join(':'));
            });
        });
    } else {
        connect(server);
    }
}

function sendAdd(ws) {
    clearTimeout(pendingAdd);
    pendingAdd = null;
    if (ws.readyState !== WebSocket.OPEN) {
        return;
    }
    var host = flags.get('host') || undefined,
        hidden = flags.get('hidden'),
        pri = flags.get('priority'),
        votes = flags.get('votes');
    Log.debug('Sending add', {host: host, hidden: hidden, priority: pri, votes: votes});
    ws.send(JSON.stringify({
        cmd: 'add',
        host: host,
        hidden: hidden,
        priority: pri,
        votes: votes
    }));
    pendingAdd = setTimeout(function() {
        Log.error("Timed out waiting for response to add", {url: ws.url});
        sendAdd(ws);
    }, 15000);
}

function startPing(ws) {
    clearInterval(pingInterval);
    if (!flags.get('ping')) {
        return;
    }
    var interval = Math.max(1000, flags.get('ping'));
    pingInterval = setInterval(function() {
        if (ws.readyState !== WebSocket.OPEN) {
            return;
        }
        ws.ping();
        if (Date.now() - ws.lastPong >= (2 * interval)) {
            Log.error("Timed out waiting for pong", {url: ws.url});
            ws.close();
        }
    }, interval);
}

function connect(address) {
    clearTimeout(pendingReconnect);
    pendingReconnect = null;
    clearTimeout(pendingConnect);
    pendingConnect = null;

    if (address.indexOf('://') === -1) {
        address = 'ws://' + address;
    }

    Log.debug("Connecting to ws", {address: address});

    var ws = new WebSocket(address);
    ws.on('open', function() {
        Log.info("Connected to ws", {address: address});
        clearTimeout(pendingConnect);
        pendingConnect = null;
        //since we just connected we got a "pong"
        ws.lastPong = Date.now();
        sendAdd(ws);
    });
    ws.on('message', function(message) {
        Log.debug("Received message", {message: message});
        var result;
        try {
            result = JSON.parse(message);
        } catch (e) {
            Log.error("Received invalid json", {message: message, error: e});
            ws.close();
            return;
        }
        if (result.hasOwnProperty('added')) {
            clearTimeout(pendingAdd);
            pendingAdd = null;
            if (!result.success) {
                Log.error("Failed to add", {error: result.error});
                pendingAdd = setTimeout(function() {
                    sendAdd(ws);
                }, (Math.random() * 5000) + 10000); //randomly between 10-15 seconds
            }
            Log.info("Added", {hostname: result.added});
            ourHostname = result.added;
            //since we just received a message we got a "pong"
            ws.lastPong = Date.now();
            startPing(ws);
            return;
        }
        if (result.hasOwnProperty('removed') && result.removed === ourHostname && pendingAdd === null) {
            Log.error("Removed from replica set", {hostname: result.removed});
            pendingAdd = setTimeout(function() {
                sendAdd(ws);
            }, (Math.random() * 5000) + 10000); //randomly between 10-15 seconds
        }
    });
    ws.on('error', function(err) {
        Log.error("Error from ws", {error: err});
        clearInterval(pingInterval);
        pingInterval = null;
        clearInterval(pendingAdd);
        pendingAdd = null;
        reconnect();
    });
    ws.on('pong', function() {
        Log.debug("Received pong");
        ws.lastPong = Date.now();
    });
    ws.on('close', function() {
        Log.error("Disconnected from ws", {address: address});
        clearInterval(pingInterval);
        pingInterval = null;
        clearInterval(pendingAdd);
        pendingAdd = null;
        reconnect();
    });

    pendingConnect = setTimeout(function() {
        Log.error("Timed out waiting to connect to ws", {address: address});
        ws.terminate();
        reconnect();
    }, 15000);
}

resolveAndConnect();
<|endoftext|>


<commit_before>import React, { PropTypes, Component } from 'react';
import M from '../_common/M';
import NumberPlain from '../_common/NumberPlain';
import NumberColored from '../_common/NumberColored';
import FlexList from '../containers/FlexList';
import KVColumn from '../_common/KVColumn';

export default class ContractDetailsCard extends Component {

	static propTypes = {
		contract: PropTypes.object.isRequired,
		nowEpoch: PropTypes.number,
		transactionId: PropTypes.number,
		actions: PropTypes.object,
	};

	render() {
		const { contract, actions } = this.props;
		const sold = !!contract.sell_price;
		const workAroundForBackendBugIsDigitTrade = contract.shortcode && contract.shortcode.includes('DIGIT');
		const validToSell = contract.is_valid_to_sell === 1 && !contract.is_expired;
		const validationError = contract.validation_error;
		const potentialProfit = (contract.payout - contract.buy_price).toFixed(2);
		const profit = sold && (contract.sell_price - contract.buy_price).toFixed(2);
		return (

				<FlexList>
					<KVColumn label="Entry Price" value={contract.buy_price || '-'} currency={contract.currency} />
					<KVColumn
						label="Exit Price"
						value={sold ? contract.sell_price : '-'}
						currency={contract.currency}
					/>
					<KVColumn
						label="Indicative Price"
						value={contract.bid_price || '-'}
						currency={contract.currency}
						isProfit={v => v - contract.buy_price}
					/>
					<KVColumn
						label={sold ? 'Profit' : 'Potential Profit'}
						value={sold ? profit : potentialProfit}
						currency={contract.currency}
						isProfit={v => v}
					/>
				</FlexList>
				{validToSell && !workAroundForBackendBugIsDigitTrade ?
					<button
						className="sell-at-market-btn"
						disabled={contract.selling}
						onClick={() => actions.sellContract(contract.contract_id, 0)}
					>
						<M m="Sell at Market" /> (<NumberPlain
							value={contract.bid_price}
							currency={contract.currency}
							isProfit={v => v - contract.buy_price}
						/>)
					</button> :

					{validationError &&
						(validationError.message ?
							validationError.message.split(')')[1] :
						validationError)
					}

				}
				{
					sold &&

							{profit >= 0 ? <M m="You won " /> : <M m="You lost " />}
							{profit >= 0 ?
								<NumberColored
									value={profit}
									currency={contract.currency}
									isProfit={v => v}
								/> :
								<NumberColored
									value={-profit}
									currency={contract.currency}
									isProfit={v => -v}
								/>
							}

				}

		);
	}
}
<commit_msg>Change upon review<commit_after>import React, { PropTypes, Component } from 'react';
import M from '../_common/M';
import NumberPlain from '../_common/NumberPlain';
import NumberColored from '../_common/NumberColored';
import FlexList from '../containers/FlexList';
import KVColumn from '../_common/KVColumn';
import toMoney from 'binary-utils/lib/toMoney';

export default class ContractDetailsCard extends Component {

	static propTypes = {
		contract: PropTypes.object.isRequired,
		nowEpoch: PropTypes.number,
		transactionId: PropTypes.number,
		actions: PropTypes.object,
	};

	render() {
		const { contract, actions } = this.props;
		const sold = !!contract.sell_price;
		const workAroundForBackendBugIsDigitTrade = contract.shortcode && contract.shortcode.includes('DIGIT');
		const validToSell = contract.is_valid_to_sell === 1 && !contract.is_expired;
		const validationError = contract.validation_error;
		const potentialProfit = toMoney(contract.payout - contract.buy_price);
		const profit = sold && toMoney(contract.sell_price - contract.buy_price);
		return (

				<FlexList>
					<KVColumn label="Entry Price" value={contract.buy_price || '-'} currency={contract.currency} />
					<KVColumn
						label="Exit Price"
						value={sold ? contract.sell_price : '-'}
						currency={contract.currency}
					/>
					<KVColumn
						label="Indicative Price"
						value={contract.bid_price || '-'}
						currency={contract.currency}
						isProfit={v => v - contract.buy_price}
					/>
					<KVColumn
						label={sold ? 'Profit' : 'Potential Profit'}
						value={sold ? profit : potentialProfit}
						currency={contract.currency}
						isProfit={v => v}
					/>
				</FlexList>
				{validToSell && !workAroundForBackendBugIsDigitTrade ?
					<button
						className="sell-at-market-btn"
						disabled={contract.selling}
						onClick={() => actions.sellContract(contract.contract_id, 0)}
					>
						<M m="Sell at Market" /> (<NumberPlain
							value={contract.bid_price}
							currency={contract.currency}
							isProfit={v => v - contract.buy_price}
						/>)
					</button> :

					{validationError &&
						(validationError.message ?
							validationError.message.split(')')[1] :
						validationError)
					}

				}
				{
					sold &&

							{profit >= 0 ? <M m="You won " /> : <M m="You lost " />}
							{profit >= 0 ?
								<NumberColored
									value={profit}
									currency={contract.currency}
									isProfit={v => v}
								/> :
								<NumberColored
									value={-profit}
									currency={contract.currency}
									isProfit={v => -v}
								/>
							}

				}

		);
	}
}
<|endoftext|>


<commit_before>/**
 *
 * @param {Object} [stats]
 * @constructor
 */
function Human(stats) {
	if(stats) {
		// reset
		this._stats = {};
		this._inventory = {
			sm: [],
			md: [],
			lg: []
		};
		this._hands = [];

		for(var stat in stats) {
			if(stats.hasOwnProperty(stat)) {
				this[stat] = stats[stat];
			}
		}
	}
}

Human.STAND = 'stand';
Human.CROUCH = 'crouch';
Human.PRONE = 'prone';

Human.prototype = {
	_name: '',
	_nickname: '',
	/** @type {Point} */
	_coord: new Point(),

	_stats: {
		hea: 0,
		agi: 0,
		dex: 0,
		str: 0,
		ldr: 0,
		wis: 0,
		lvl: 0,
		mec: 0,
		exp: 0,
		med: 0,
		mrk: 0
	},

	_wear: {
		head: new Wear(),
		body: new Wear(),
		legs: new Wear()
	},

	_hands: [],

	_stance: Human.STAND,

	_inventory: {
		sm: [],
		md: [],
		lg: []
	},

	_thumb: Image,

	_ap: 0,
	_hp: 0,
	_energy: 0,
	_moral: 0
};

/**
 *
 * @param {Wear} wear
 */
Human.prototype.putOn = function(wear) {
	if(!(wear instanceof Wear)) {
		console.warn(wear, "must be an instance of Wear().");
		return;
	}

	this._wear[wear.type] = wear;

	return this;
};

/**
 *
 * @param {Wear} wear
 */
Human.prototype.takeOff = function(wear) {
	this._wear[wear.type] = '';

	return this;
};

/**
 *
 * @param {Item} item
 */
Human.prototype.equip = function(item) {
	if(!(item instanceof Item)) {
		console.warn(item, "must be an instance of Item().");
		return;
	}

	this._inventory[item.size].push(item);

	return this;
};

Human.prototype.unequip = function(item) {
	// remove from inventory
	this._inventory[item.size].forEach(function(invItem, i) {
		if(invItem === item) this._inventory[item.size].splice(i, 1);
	}.bind(this));

	// check hands
	this._hands.forEach(function(handItem, i) {
		if(handItem === item) this._hands.splice(i, 1);
	}.bind(this));

	return this;
};

/**
 *
 * @param {Item} item
 */
Human.prototype.grab = function(item) {
	// check if Human can grab item
	if(this._hands.length == 2) return;
	for(var i=0; i < this._hands.length; i++) {
		/** @type {Item} handItem */
		var handItem = this._hands[i];
		if(handItem.hands == 2) return;
	}

	// check if item is in inventory
	this._inventory[item.size].forEach(function(invItem) {
		if(invItem === item) this._hands.push(item);
	}.bind(this));

	return this;
};

Human.prototype.startTurn = function() {
	// calculate APs
	var ap = ((this._stats.agi * 0.9) + (this._stats.dex * 0.6) + (this._energy * 0.6) + this._hp) / 3;
	ap = Math.round(ap);

	this._ap = ap;

	return this;
};

Human.prototype.endTurn = function() {

	return this;
};

/**
 * @param {Point} coord
 * @return {Number}
 */
Human.prototype.calculateWalk = function(coord) {
	// calculate walking distance
	// TODO: consider world map resp. obsticales
	var distance = Math.abs(this._coord.x - coord.x) + Math.abs(this._coord.y - coord.y);

	// calculate ap-cost
	var tileCost = 0;
	if(this._stance == Human.STAND) 		tileCost = 8;
	else if(this._stance == Human.CROUCH) 	tileCost = 12;
	else if(this._stance == Human.PRONE) 	tileCost = 16;

	var cost = tileCost * distance;

	// TODO: calculate way

	return cost;
};

/**
 * @param {Point} coord
 */
Human.prototype.walk = function(coord) {
	var cost = this.calculateWalk(coord);

	console.log("cost", cost);

	if(this._ap - cost < 0) return;

	this._coord = coord;

	this._ap -= cost;

	return this;
};

/**
 *
 * @param {String} stance {Human.STAND|Human.CROUCH|Human.PRONE}
 */
Human.prototype.changeStance = function(stance) {
	this._stance = stance;
};

Object.defineProperty(Human.prototype, "weightInKG", {
	get: function () {
		var weight = 0,
			/** @type {Item} item **/
			item;
		[ Item.SMALL, Item.MEDIUM, Item.LARGE].forEach(function(type) {
			for(var i=0; i < this._inventory[type].length; i++) {
				item = this._inventory[type][i];
				weight += item.weight;
			}
		}.bind(this));

		return weight;
	}
});

Object.defineProperty(Human.prototype, "weightInPerc", {
	get: function () {
		return Math.round(this.weightInKG / this.strength * 100);
	}
});

// GETTER / SETTER

Object.defineProperty(Human.prototype, "thumb", {
	get: function () {
		return this._thumb;
	},

	set: function(val) {
		var img = new Image();
		img.src = val;
		this._thumb = img;
	}
});

Object.defineProperty(Human.prototype, "name", {
	get: function () {
		return this._name;
	},

	set: function(val) {
		this._name = val;
	}
});

Object.defineProperty(Human.prototype, "nickname", {
	get: function () {
		return this._nickname;
	},

	set: function(val) {
		this._nickname = val;
	}
});

Object.defineProperty(Human.prototype, "health", {
	get: function () {
		return this._stats.hea;
	},

	set: function(val) {
		this._stats.hea = val;
	}
});

Object.defineProperty(Human.prototype, "agility", {
	get: function () {
		return this._stats.agi;
	},

	set: function(val) {
		this._stats.agi = val;
	}
});

Object.defineProperty(Human.prototype, "dexterity", {
	get: function () {
		return this._stats.dex;
	},

	set: function(val) {
		this._stats.dex = val;
	}
});

Object.defineProperty(Human.prototype, "strength", {
	get: function () {
		return this._stats.str;
	},

	set: function(val) {
		this._stats.str = val;
	}
});

Object.defineProperty(Human.prototype, "leadership", {
	get: function () {
		return this._stats.ldr;
	},

	set: function(val) {
		this._stats.ldr = val;
	}
});

Object.defineProperty(Human.prototype, "wisdom", {
	get: function () {
		return this._stats.wis;
	},

	set: function(val) {
		this._stats.wis = val;
	}
});

Object.defineProperty(Human.prototype, "level", {
	get: function () {
		return this._stats.lvl;
	},

	set: function(val) {
		this._stats.lvl = val;
	}
});

Object.defineProperty(Human.prototype, "mecanical", {
	get: function () {
		return this._stats.mec;
	},

	set: function(val) {
		this._stats.mec = val;
	}
});

Object.defineProperty(Human.prototype, "explosives", {
	get: function () {
		return this._stats.exp;
	},

	set: function(val) {
		this._stats.exp = val;
	}
});

Object.defineProperty(Human.prototype, "medical", {
	get: function () {
		return this._stats.med;
	},

	set: function(val) {
		this._stats.med = val;
	}
});

Object.defineProperty(Human.prototype, "marksmanship", {
	get: function () {
		return this._stats.mrk;
	},

	set: function(val) {
		this._stats.mrk = val;
	}
});

Object.defineProperty(Human.prototype, "AP", {
	get: function () {
		return this._ap;
	},

	set: function(val) {
		this._ap = val;
	}
});

Object.defineProperty(Human.prototype, "moral", {
	get: function () {
		return this._moral;
	},

	set: function(val) {
		this._moral = val;
	}
});

Object.defineProperty(Human.prototype, "hp", {
	get: function () {
		return this._hp;
	},

	set: function(val) {
		this._hp = val;
	}
});

Object.defineProperty(Human.prototype, "energy", {
	get: function () {
		return this._energy;
	},

	set: function(val) {
		this._energy = val;
	}
});

Object.defineProperty(Human.prototype, "wear", {
	get: function () {
		return this._wear;
	}
});

Object.defineProperty(Human.prototype, "stance", {
	get: function () {
		return this._stance;
	}
});

Object.defineProperty(Human.prototype, "inventory", {
	get: function () {
		return this._inventory;
	}
});

Object.defineProperty(Human.prototype, "coord", {
	/** @return {Point} */
	get: function () {
		return this._coord;
	},

	/** @param {Point} val */
	set: function(val) {
		this._coord = val;
	}
});
<commit_msg>added waypoint-logic<commit_after>/**
 *
 * @param {Object} [stats]
 * @constructor
 */
function Human(stats) {
	if(stats) {
		// reset
		this._stats = {};
		this._inventory = {
			sm: [],
			md: [],
			lg: []
		};
		this._hands = [];

		for(var stat in stats) {
			if(stats.hasOwnProperty(stat)) {
				this[stat] = stats[stat];
			}
		}
	}
}

Human.STAND = 'stand';
Human.CROUCH = 'crouch';
Human.PRONE = 'prone';

Human.prototype = {
	_name: '',
	_nickname: '',
	/** @type {Point} */
	_coord: new Point(),

	_stats: {
		hea: 0,
		agi: 0,
		dex: 0,
		str: 0,
		ldr: 0,
		wis: 0,
		lvl: 0,
		mec: 0,
		exp: 0,
		med: 0,
		mrk: 0
	},

	_wear: {
		head: new Wear(),
		body: new Wear(),
		legs: new Wear()
	},

	_hands: [],

	_stance: Human.STAND,

	_inventory: {
		sm: [],
		md: [],
		lg: []
	},

	_thumb: Image,

	_ap: Infinity,
	_hp: 0,
	_energy: 0,
	_moral: 0
};

/**
 *
 * @param {Wear} wear
 */
Human.prototype.putOn = function(wear) {
	if(!(wear instanceof Wear)) {
		console.warn(wear, "must be an instance of Wear().");
		return;
	}

	this._wear[wear.type] = wear;

	return this;
};

/**
 *
 * @param {Wear} wear
 */
Human.prototype.takeOff = function(wear) {
	this._wear[wear.type] = '';

	return this;
};

/**
 *
 * @param {Item} item
 */
Human.prototype.equip = function(item) {
	if(!(item instanceof Item)) {
		console.warn(item, "must be an instance of Item().");
		return;
	}

	this._inventory[item.size].push(item);

	return this;
};

Human.prototype.unequip = function(item) {
	// remove from inventory
	this._inventory[item.size].forEach(function(invItem, i) {
		if(invItem === item) this._inventory[item.size].splice(i, 1);
	}.bind(this));

	// check hands
	this._hands.forEach(function(handItem, i) {
		if(handItem === item) this._hands.splice(i, 1);
	}.bind(this));

	return this;
};

/**
 *
 * @param {Item} item
 */
Human.prototype.grab = function(item) {
	// check if Human can grab item
	if(this._hands.length == 2) return;
	for(var i=0; i < this._hands.length; i++) {
		/** @type {Item} handItem */
		var handItem = this._hands[i];
		if(handItem.hands == 2) return;
	}

	// check if item is in inventory
	this._inventory[item.size].forEach(function(invItem) {
		if(invItem === item) this._hands.push(item);
	}.bind(this));

	return this;
};

Human.prototype.startTurn = function() {
	// calculate APs
	var ap = ((this._stats.agi * 0.9) + (this._stats.dex * 0.6) + (this._energy * 0.6) + this._hp) / 3;
	ap = Math.round(ap);

	this._ap = ap;

	return this;
};

Human.prototype.endTurn = function() {

	return this;
};

/**
 *
 * @param {Point} coord
 * @returns {Object}
 */
Human.prototype.calculateDistance = function(coord) {
	// calculate walking distance
	// TODO: consider world map resp. obsticales
	var dist = Math.abs(this._coord.x - coord.x) + Math.abs(this._coord.y - coord.y);
	var output = {};

	// calculate ap-cost
	var tileCost = 0;
	if(this._stance == Human.STAND) 		tileCost = 8;
	else if(this._stance == Human.CROUCH) 	tileCost = 12;
	else if(this._stance == Human.PRONE) 	tileCost = 16;

	var cost = tileCost * dist;

	// caluclate diagonal walking distance
	var distanceX = [], distanceY = [];
	for(var x = this._coord.x; this._coord.x < coord.x ? x <= coord.x : x >= coord.x; this._coord.x < coord.x ? x++ : x--) {
		distanceX.push(x);
	}
	distanceX.type = 'x';
	for(var y = this._coord.y; this._coord.y < coord.y ? y <= coord.y : y >= coord.y; this._coord.y < coord.y ? y++ : y--) {
		distanceY.push(y);
	}
	distanceY.type = 'y';

	// find out which is longest and shortest distance
	var lgDistance = distanceX.length > distanceY.length ? distanceX : distanceY;
	var shDistance = distanceX.length > distanceY.length ? distanceY : distanceX;
	var div = Math.ceil(lgDistance.length / shDistance.length);
	var index = 0;
	var fullDistance = [];

	lgDistance.forEach(function(p1, i) {
		if(i != 0 && i % div == 0) index++;

		if(lgDistance.type == 'x') {
			fullDistance.push( new Point(p1, shDistance[index]) );
		} else if(lgDistance.type == 'y') {
			fullDistance.push( new Point(shDistance[index], p1) );
		}
	});

	// check if last element equals the target coord
	var lastPoint = fullDistance[fullDistance.length-1];
	if(lastPoint.x != coord.x || lastPoint.y != coord.y) {
		fullDistance.push(coord);
	}

	output.fullDistance = fullDistance;
	output.cost = cost;

	return output;
};

/**
 * @param {Point} coord
 */
Human.prototype.walk = function(coord) {
	var distance = this.calculateDistance(coord);
	var cost = distance.cost;

	console.log("cost", cost, "distance", distance.fullDistance);

	if(this._ap - cost < 0) {
		return this;
	}

	this._coord = coord;

	this._ap -= cost;

	return this;
};

/**
 *
 * @param {String} stance {Human.STAND|Human.CROUCH|Human.PRONE}
 */
Human.prototype.changeStance = function(stance) {
	this._stance = stance;
};

Object.defineProperty(Human.prototype, "weightInKG", {
	get: function () {
		var weight = 0,
			/** @type {Item} item **/
			item;
		[ Item.SMALL, Item.MEDIUM, Item.LARGE].forEach(function(type) {
			for(var i=0; i < this._inventory[type].length; i++) {
				item = this._inventory[type][i];
				weight += item.weight;
			}
		}.bind(this));

		return weight;
	}
});

Object.defineProperty(Human.prototype, "weightInPerc", {
	get: function () {
		return Math.round(this.weightInKG / this.strength * 100);
	}
});

// GETTER / SETTER

Object.defineProperty(Human.prototype, "thumb", {
	get: function () {
		return this._thumb;
	},

	set: function(val) {
		var img = new Image();
		img.src = val;
		this._thumb = img;
	}
});

Object.defineProperty(Human.prototype, "name", {
	get: function () {
		return this._name;
	},

	set: function(val) {
		this._name = val;
	}
});

Object.defineProperty(Human.prototype, "nickname", {
	get: function () {
		return this._nickname;
	},

	set: function(val) {
		this._nickname = val;
	}
});

Object.defineProperty(Human.prototype, "health", {
	get: function () {
		return this._stats.hea;
	},

	set: function(val) {
		this._stats.hea = val;
	}
});

Object.defineProperty(Human.prototype, "agility", {
	get: function () {
		return this._stats.agi;
	},

	set: function(val) {
		this._stats.agi = val;
	}
});

Object.defineProperty(Human.prototype, "dexterity", {
	get: function () {
		return this._stats.dex;
	},

	set: function(val) {
		this._stats.dex = val;
	}
});

Object.defineProperty(Human.prototype, "strength", {
	get: function () {
		return this._stats.str;
	},

	set: function(val) {
		this._stats.str = val;
	}
});

Object.defineProperty(Human.prototype, "leadership", {
	get: function () {
		return this._stats.ldr;
	},

	set: function(val) {
		this._stats.ldr = val;
	}
});

Object.defineProperty(Human.prototype, "wisdom", {
	get: function () {
		return this._stats.wis;
	},

	set: function(val) {
		this._stats.wis = val;
	}
});

Object.defineProperty(Human.prototype, "level", {
	get: function () {
		return this._stats.lvl;
	},

	set: function(val) {
		this._stats.lvl = val;
	}
});

Object.defineProperty(Human.prototype, "mecanical", {
	get: function () {
		return this._stats.mec;
	},

	set: function(val) {
		this._stats.mec = val;
	}
});

Object.defineProperty(Human.prototype, "explosives", {
	get: function () {
		return this._stats.exp;
	},

	set: function(val) {
		this._stats.exp = val;
	}
});

Object.defineProperty(Human.prototype, "medical", {
	get: function () {
		return this._stats.med;
	},

	set: function(val) {
		this._stats.med = val;
	}
});

Object.defineProperty(Human.prototype, "marksmanship", {
	get: function () {
		return this._stats.mrk;
	},

	set: function(val) {
		this._stats.mrk = val;
	}
});

Object.defineProperty(Human.prototype, "AP", {
	get: function () {
		return this._ap;
	},

	set: function(val) {
		this._ap = val;
	}
});

Object.defineProperty(Human.prototype, "moral", {
	get: function () {
		return this._moral;
	},

	set: function(val) {
		this._moral = val;
	}
});

Object.defineProperty(Human.prototype, "hp", {
	get: function () {
		return this._hp;
	},

	set: function(val) {
		this._hp = val;
	}
});

Object.defineProperty(Human.prototype, "energy", {
	get: function () {
		return this._energy;
	},

	set: function(val) {
		this._energy = val;
	}
});

Object.defineProperty(Human.prototype, "wear", {
	get: function () {
		return this._wear;
	}
});

Object.defineProperty(Human.prototype, "stance", {
	get: function () {
		return this._stance;
	}
});

Object.defineProperty(Human.prototype, "inventory", {
	get: function () {
		return this._inventory;
	}
});

Object.defineProperty(Human.prototype, "coord", {
	/** @return {Point} */
	get: function () {
		return this._coord;
	},

	/** @param {Point} val */
	set: function(val) {
		this._coord = val;
	}
});
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Wor<commit_msg>Fixing punctuation<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work<|endoftext|>


<commit_before>"use strict";

var Hapi    = require("hapi");
var server  = new Hapi.Server();
var port    = process.env.PORT || 8000;

var options = {
	port: port
};

server.connection(options);

server.register(require("inert"), function (err) {

    if (err) {
        throw err;
    }

    server.route([
        {
            method: "GET",
            path: "/{param*}",
            handler: {
                directory: {
                    path: "./public",
                    listing: true
                }
            }
        },
        {
            method: "GET",
            path: "/data",
            handler: function(req, rep){
                        var Wreck = require('wreck');
                        var uri = 'http://lda.data.parliament.uk/answeredquestions.json?AnsweringBody=Prime%20Minister';

                        Wreck.get(uri, function (err, res, payload) {
                            rep(payload);
                    });
                }
        }
    ]);

    server.start(function () {
        console.log("Server running at: http://localhost:" + server.info.port); //eslint-disable-line no-console
    });
});
<commit_msg>lint 💜:<commit_after>"use strict";

var Hapi    = require("hapi");
var server  = new Hapi.Server();
var port    = process.env.PORT || 8000;

var options = {
	port: port
};

server.connection(options);

server.register(require("inert"), function (err) {

    if (err) {
        throw err;
    }

    server.route([
        {
            method: "GET",
            path: "/{param*}",
            handler: {
                directory: {
                    path: "./public",
                    listing: true
                }
            }
        },
        {
            method: "GET",
            path: "/data",
            handler: function(req, rep){
                        var Wreck = require("wreck");
                        var uri = "http://lda.data.parliament.uk/answeredquestions.json?AnsweringBody=Prime%20Minister";

                        Wreck.get(uri, function (err, res, payload) {
                            rep(payload);
                    });
                }
        }
    ]);

    server.start(function () {
        console.log("Server running at: http://localhost:" + server.info.port); //eslint-disable-line no-console
    });
});
<|endoftext|>