<commit_before>
/* Game namespace */
var game = {

    // an object where to store game information
    data : {
        currentLevel : 1
    },

    // the channels for buttons/doors
    channels : { },

    // Run on page load.
    onload : function () {
        // Initialize the video.
        var scale = 3 * window.devicePixelRatio;
        if (!me.video.init(160, 144, { wrapper : 'screen', scale : scale })) {
            alert('Your browser does not support HTML5 canvas.');
            return;
        }

        // Initialize the audio.
        me.audio.init('ogg');

        // setting up sound
        me.audio.samplePlaying = null;
        me.audio.samplePriority = { action: ['startpause', 'youpi', 'mort', 'interrupteur',
                                             'blockdestroy', 'kick', 'jump', 'oscours'] };

        me.audio.playUnique = function(soundName, channel, loop) {
            // set to default channel
            channel = channel || 'default';

            // get samples priority
            var selfId = me.audio.samplePriority[channel].indexOf(soundName);
            var currentId = me.audio.samplePriority[channel].indexOf(me.audio.samplePlaying);

            // if this sample is in the priority list
            if (selfId >= 0) {
                // if a sound is playing,
                if (currentId >= 0) {
                    // if has a lower priority
                    if (selfId < currentId) {
                        // we stop current sample only
                        me.audio.stop(me.audio.samplePlaying);
                        me.audio.samplePlaying = null;
                    } else {
                        // we do nothing
                        return null;
                    }
                }

                // we play a sound
                me.audio.samplePlaying = soundName;
                return me.audio.play(soundName, loop, function () {
                    me.audio.samplePlaying = null;
                });
            } else {
                return null;
            }
        };

        me.audio.playUniqueTrack = function(trackName) {
            if (me.audio.getCurrentTrack() !== trackName) {
                me.audio.stopTrack();
                me.audio.playTrack(trackName);
            }
        };

        me.state.set(me.state.LOADING, new game.LoadingScreen());

        // Set a callback to run when loading is complete.
        me.loader.onload = this.loaded.bind(this);

        // Load the resources.
        me.loader.preload(game.resources);

        // Initialize melonJS and display a loading screen.
        me.state.change(me.state.LOADING);
    },

    // Run on game resources loaded.
    loaded : function () {
        me.state.set(me.state.MENU, new game.TitleScreen());
        me.state.set(me.state.PLAY, new game.PlayScreen());
        me.state.set(me.state.CREDITS, new game.CreditsScreen());
        me.state.GAME_START = me.state.USER + 1;
        me.state.set(me.state.GAME_START, new game.IntroScreen());

        // add our player entity in the entity pool
        me.pool.register('player', game.PlayerEntity);
        me.pool.register('ball', game.BallEntity);
        me.pool.register('piglet', game.PigletEntity);
        me.pool.register('boar', game.BoarEntity);
        me.pool.register('block', game.BlockEntity);
        me.pool.register('trigger', game.TriggerEntity);
        me.pool.register('door', game.DoorEntity);

        // enable the keyboard
        me.input.bindKey(me.input.KEY.LEFT, 'left');
        me.input.bindKey(me.input.KEY.RIGHT, 'right');
        me.input.bindKey(me.input.KEY.UP, 'up');
        me.input.bindKey(me.input.KEY.C, 'jump', true);
        me.input.bindKey(me.input.KEY.X, 'kick', true);
        me.input.bindKey(me.input.KEY.ESC, 'pause', true);
        // added for debug purposes
        me.input.bindKey(me.input.KEY.E, 'debug', true);

        // sets global gravity
        me.sys.gravity = 0.7;

        this.paused = false;
        me.input.paused = false;

        me.state.transition('fade', 'rgb(215, 232, 148)', 350);

        me.state.onResume = function() {
            if (game.isPaused()) {
                game.pause();
            }
        };

        // starts the game.
        me.state.change(me.state.GAME_START);
    },

    pause: function() {
        this.paused = true;
        me.state.pause(true);
    },

    resume: function() {
        this.paused = false;
        me.state.resume(true);
    },

    isPaused: function() {
        return this.paused;
    },
};
<commit_msg>remove debug input<commit_after>
/* Game namespace */
var game = {

    // an object where to store game information
    data : {
        currentLevel : 1
    },

    // the channels for buttons/doors
    channels : { },

    // Run on page load.
    onload : function () {
        // Initialize the video.
        var scale = 3 * window.devicePixelRatio;
        if (!me.video.init(160, 144, { wrapper : 'screen', scale : scale })) {
            alert('Your browser does not support HTML5 canvas.');
            return;
        }

        // Initialize the audio.
        me.audio.init('ogg');

        // setting up sound
        me.audio.samplePlaying = null;
        me.audio.samplePriority = { action: ['startpause', 'youpi', 'mort', 'interrupteur',
                                             'blockdestroy', 'kick', 'jump', 'oscours'] };

        me.audio.playUnique = function(soundName, channel, loop) {
            // set to default channel
            channel = channel || 'default';

            // get samples priority
            var selfId = me.audio.samplePriority[channel].indexOf(soundName);
            var currentId = me.audio.samplePriority[channel].indexOf(me.audio.samplePlaying);

            // if this sample is in the priority list
            if (selfId >= 0) {
                // if a sound is playing,
                if (currentId >= 0) {
                    // if has a lower priority
                    if (selfId < currentId) {
                        // we stop current sample only
                        me.audio.stop(me.audio.samplePlaying);
                        me.audio.samplePlaying = null;
                    } else {
                        // we do nothing
                        return null;
                    }
                }

                // we play a sound
                me.audio.samplePlaying = soundName;
                return me.audio.play(soundName, loop, function () {
                    me.audio.samplePlaying = null;
                });
            } else {
                return null;
            }
        };

        me.audio.playUniqueTrack = function(trackName) {
            if (me.audio.getCurrentTrack() !== trackName) {
                me.audio.stopTrack();
                me.audio.playTrack(trackName);
            }
        };

        me.state.set(me.state.LOADING, new game.LoadingScreen());

        // Set a callback to run when loading is complete.
        me.loader.onload = this.loaded.bind(this);

        // Load the resources.
        me.loader.preload(game.resources);

        // Initialize melonJS and display a loading screen.
        me.state.change(me.state.LOADING);
    },

    // Run on game resources loaded.
    loaded : function () {
        me.state.set(me.state.MENU, new game.TitleScreen());
        me.state.set(me.state.PLAY, new game.PlayScreen());
        me.state.set(me.state.CREDITS, new game.CreditsScreen());
        me.state.GAME_START = me.state.USER + 1;
        me.state.set(me.state.GAME_START, new game.IntroScreen());

        // add our player entity in the entity pool
        me.pool.register('player', game.PlayerEntity);
        me.pool.register('ball', game.BallEntity);
        me.pool.register('piglet', game.PigletEntity);
        me.pool.register('boar', game.BoarEntity);
        me.pool.register('block', game.BlockEntity);
        me.pool.register('trigger', game.TriggerEntity);
        me.pool.register('door', game.DoorEntity);

        // enable the keyboard
        me.input.bindKey(me.input.KEY.LEFT, 'left');
        me.input.bindKey(me.input.KEY.RIGHT, 'right');
        me.input.bindKey(me.input.KEY.UP, 'up');
        me.input.bindKey(me.input.KEY.C, 'jump', true);
        me.input.bindKey(me.input.KEY.X, 'kick', true);
        me.input.bindKey(me.input.KEY.ESC, 'pause', true);

        // sets global gravity
        me.sys.gravity = 0.7;

        this.paused = false;
        me.input.paused = false;

        me.state.transition('fade', 'rgb(215, 232, 148)', 350);

        me.state.onResume = function() {
            if (game.isPaused()) {
                game.pause();
            }
        };

        // starts the game.
        me.state.change(me.state.GAME_START);
    },

    pause: function() {
        this.paused = true;
        me.state.pause(true);
    },

    resume: function() {
        this.paused = false;
        me.state.resume(true);
    },

    isPaused: function() {
        return this.paused;
    },
};
<|endoftext|>


<commit_before>(function( window, document, undefined ) {
  'use strict';

  var pixelSize = 16;
  var halfPixelSize = 0.5 * pixelSize;

  function randomIntSpread( value, spread ) {
    return Math.round( value + ( Math.random() < 0.5 ? spread : -spread ) );
  }

  function drawPixel( ctx, x, y, size, color ) {
    size = size || pixelSize;
    var halfSize = 0.5 * size;

    ctx.save();

    ctx.beginPath();
    ctx.translate( x, y );
    ctx.rect( 0, 0, size, size );
    ctx.fillStyle = color || '#fff';
    ctx.fill();

    ctx.restore();
  }

  var topRow = [ 81, 87, 69, 82, 84, 89, 85, 73, 79, 80 ];
  var midRow = [ 65, 83, 68, 70, 71, 72, 74, 75, 76 ];
  var bottomRow = [ 90, 88, 67, 86, 66, 78, 77 ];

  function drawKeys( ctx, keys, lastPressed ) {
    var time = Date.now();
    var maxTime = 1000;

    keys.forEach(function( key, index ) {
      var lastPressedTime = lastPressed[ index ];
      if ( !lastPressedTime ) {
        return;
      }

      var dt = time - lastPressedTime;
      if ( dt > maxTime ) {
        lastPressed[ index ] = 0;
        return;
      }

      ctx.globalAlpha = 1 - dt / maxTime;

      // Numeric.
      // 0 - 9.
      if ( 48 <= index && index <= 57 ) {
        index -= 49;
        if ( index < 0 ) {
          index += 10;
        }

        drawPixel( ctx, 3 * pixelSize * index, 2 * pixelSize, 2 * pixelSize, '#f00' );
      }

      var topIndex = topRow.indexOf( index );
      if ( topIndex !== -1 ) {
        drawPixel( ctx, 3 * pixelSize * topIndex + pixelSize, 6 * pixelSize, 2 * pixelSize, '#0f0' );
      }

      var midIndex = midRow.indexOf( index );
      if ( midIndex !== -1 ) {
        drawPixel( ctx, 3 * pixelSize * midIndex + 2 * pixelSize, 10 * pixelSize, 2 * pixelSize, '#00f' );
      }

      var bottomIndex = bottomRow.indexOf( index );
      if ( bottomIndex !== -1 ) {
        drawPixel( ctx, 3 * pixelSize * bottomIndex + 3 * pixelSize, 14 * pixelSize, 2 * pixelSize, '#f0f' );
      }

      ctx.globalAlpha = 1;
    });
  }

  function drawBackground( ctx, width, height, options ) {
    var hue = options.hue || 0;
    var saturation = options.saturation || 0;
    var lightness = options.lightness || 0;

    var hueSpread = options.hueSpread || 10;
    var saturationSpread = options.saturationSpread || 10;
    var lightnessSpread = options.lightnessSpread || 10;

    var h, s, l;

    var x, y;
    for ( y = 0; y < height; y++ ) {
      for ( x = 0; x < width; x++ ) {
        h = randomIntSpread( hue, hueSpread );
        s = randomIntSpread( saturation, saturationSpread );
        l = randomIntSpread( lightness, lightnessSpread );

        var hsl = 'hsl(' + h + ', ' + s + '%, ' + l + '%)';
        drawPixel( ctx, x * pixelSize, y * pixelSize, 0, hsl );
      }
    }
  }

  function Radar( x, y, radius ) {

  }

  function Entity( x, y ) {
    this.x = x;
    this.y = y;

    this.image = null;
  }

  Entity.prototype.update = function() {};
  Entity.prototype.draw = function( ctx ) {
    if ( this.image ) {
      ctx.drawImage( this.image, this.x, this.y );
    }
  };

  function Enemy( x, y ) {
    Entity.call( this, x, y );
  }

  function Player( x, y ) {
    Entity.call( this, x, y );
  }

  Player.prototype.draw = function( ctx ) {
    ctx.beginPath();
    ctx.rect( this.x - halfPixelSize, this.y - halfPixelSize - pixelSize, pixelSize, pixelSize );
    ctx.fillStyle = '#efefd0';
    ctx.fill();

    ctx.beginPath();
    ctx.rect( this.x - halfPixelSize, this.y - halfPixelSize, pixelSize, 2 * pixelSize );
    ctx.fillStyle = '#f43';
    ctx.fill();

    if ( this.radar ) {
      this.radar.draw( this.x, this.y );
    }
  };

  Player.prototype.update = function( dt ) {
    var dx = dt * 128;
    var dy = dt * 128;

    if ( game.input.keys[ 37 ] ) { this.x -= dx; }
    if ( game.input.keys[ 39 ] ) { this.x += dx; }
    if ( game.input.keys[ 38 ] ) { this.y -= dy; }
    if ( game.input.keys[ 40 ] ) { this.y += dy; }
  };

  function Game() {
    this.prevTime = Date.now();
    this.currTime = this.prevTime;
    this.running = true;

    this.canvas = document.createElement( 'canvas' );
    this.ctx = this.canvas.getContext( '2d' );

    this.ctx.webkitImageSmoothingEnabled = false;
    this.ctx.imageSmoothingEnabled = false;

    this.canvas.width = 512;
    this.canvas.height = 512;

    document.body.appendChild( this.canvas );

    this.entities = [];

    this.input = {
      keys: [],
      mouse: {
        x: 0,
        y: 0,

        down: false
      },

      lastPressed: []
    };

    this.player = new Player( 256, 480 );
    this.entities.push( this.player );
    this.backgroundCanvas = document.createElement( 'canvas' );
    this.backgroundCtx = this.backgroundCanvas.getContext( '2d' );
    this.backgroundCanvas.width = this.canvas.width;
    this.backgroundCanvas.height = this.canvas.height;

    drawBackground( this.backgroundCtx, 32, 32, {
      hue: 120,
      saturation: 20,
      lightness: 40,
      hueSpread: 10,
      saturationSpread: 5,
      lightnessSpread: 5
    });
  }

  Game.prototype.draw = function() {
    var ctx = this.ctx;

    var width = ctx.canvas.width,
        height = ctx.canvas.height;

    ctx.clearRect( 0, 0, width, height );
    ctx.fillStyle = 'white';
    ctx.fillRect( 0, 0, width, height );

    ctx.drawImage( this.backgroundCanvas, 0, 0 );
    drawKeys( ctx, this.input.keys, this.input.lastPressed );

    this.entities.forEach(function( entity ) {
      entity.draw( ctx );
    });
  };

  Game.prototype.update = function() {
    if ( !this.prevTime ) {
      this.prevTime = Date.now();
      return;
    }

    this.currTime = Date.now();
    var dt = this.currTime - this.prevTime;
    this.prevTime = this.currTime;

    if ( dt > 1e2 ) {
      dt = 1e2;
    }

    dt *= 1e-3;

    this.entities.forEach(function( entity ) {
      entity.update( dt );
    });
  };

  var game = new Game();

  function onKeyDown( event ) {
    // console.log(event.which)
    game.input.keys[ event.which ] = true;
    game.input.lastPressed[ event.which ] = Date.now();
  }

  function onKeyUp( event ) {
    game.input.keys[ event.which ] = false;
  }

  function tick() {
    if ( !game.running ) {
      return;
    }

    game.update();
    game.draw();
    window.requestAnimationFrame( tick );
  }

  tick();

  document.addEventListener( 'keydown', onKeyDown );
  document.addEventListener( 'keyup', onKeyUp );
}) ( window, document );
<commit_msg>Fix key press fading issue.<commit_after>(function( window, document, undefined ) {
  'use strict';

  var pixelSize = 16;
  var halfPixelSize = 0.5 * pixelSize;

  function randomIntSpread( value, spread ) {
    return Math.round( value + ( Math.random() < 0.5 ? spread : -spread ) );
  }

  function drawPixel( ctx, x, y, size, color ) {
    size = size || pixelSize;
    var halfSize = 0.5 * size;

    ctx.save();

    ctx.beginPath();
    ctx.translate( x, y );
    ctx.rect( 0, 0, size, size );
    ctx.fillStyle = color || '#fff';
    ctx.fill();

    ctx.restore();
  }

  var topRow = [ 81, 87, 69, 82, 84, 89, 85, 73, 79, 80 ];
  var midRow = [ 65, 83, 68, 70, 71, 72, 74, 75, 76 ];
  var bottomRow = [ 90, 88, 67, 86, 66, 78, 77 ];

  function drawKeys( ctx, keys, lastPressed ) {
    var time = Date.now();
    var maxTime = 1000;

    keys.forEach(function( key, index ) {
      var lastPressedTime = lastPressed[ index ];
      if ( !lastPressedTime ) {
        return;
      }

      if ( !key ) {
        var dt = time - lastPressedTime;
        if ( dt > maxTime ) {
          lastPressed[ index ] = 0;
          return;
        }

        ctx.globalAlpha = 1 - dt / maxTime;
      }

      // Numeric.
      // 0 - 9.
      if ( 48 <= index && index <= 57 ) {
        index -= 49;
        if ( index < 0 ) {
          index += 10;
        }

        drawPixel( ctx, 3 * pixelSize * index, 2 * pixelSize, 2 * pixelSize, '#f00' );
      }

      var topIndex = topRow.indexOf( index );
      if ( topIndex !== -1 ) {
        drawPixel( ctx, 3 * pixelSize * topIndex + pixelSize, 6 * pixelSize, 2 * pixelSize, '#0f0' );
      }

      var midIndex = midRow.indexOf( index );
      if ( midIndex !== -1 ) {
        drawPixel( ctx, 3 * pixelSize * midIndex + 2 * pixelSize, 10 * pixelSize, 2 * pixelSize, '#00f' );
      }

      var bottomIndex = bottomRow.indexOf( index );
      if ( bottomIndex !== -1 ) {
        drawPixel( ctx, 3 * pixelSize * bottomIndex + 3 * pixelSize, 14 * pixelSize, 2 * pixelSize, '#f0f' );
      }

      ctx.globalAlpha = 1;
    });
  }

  function drawBackground( ctx, width, height, options ) {
    var hue = options.hue || 0;
    var saturation = options.saturation || 0;
    var lightness = options.lightness || 0;

    var hueSpread = options.hueSpread || 10;
    var saturationSpread = options.saturationSpread || 10;
    var lightnessSpread = options.lightnessSpread || 10;

    var h, s, l;

    var x, y;
    for ( y = 0; y < height; y++ ) {
      for ( x = 0; x < width; x++ ) {
        h = randomIntSpread( hue, hueSpread );
        s = randomIntSpread( saturation, saturationSpread );
        l = randomIntSpread( lightness, lightnessSpread );

        var hsl = 'hsl(' + h + ', ' + s + '%, ' + l + '%)';
        drawPixel( ctx, x * pixelSize, y * pixelSize, 0, hsl );
      }
    }
  }

  function Radar( x, y, radius ) {

  }

  function Entity( x, y ) {
    this.x = x;
    this.y = y;

    this.image = null;
  }

  Entity.prototype.update = function() {};
  Entity.prototype.draw = function( ctx ) {
    if ( this.image ) {
      ctx.drawImage( this.image, this.x, this.y );
    }
  };

  function Enemy( x, y ) {
    Entity.call( this, x, y );
  }

  function Player( x, y ) {
    Entity.call( this, x, y );
  }

  Player.prototype.draw = function( ctx ) {
    ctx.beginPath();
    ctx.rect( this.x - halfPixelSize, this.y - halfPixelSize - pixelSize, pixelSize, pixelSize );
    ctx.fillStyle = '#efefd0';
    ctx.fill();

    ctx.beginPath();
    ctx.rect( this.x - halfPixelSize, this.y - halfPixelSize, pixelSize, 2 * pixelSize );
    ctx.fillStyle = '#f43';
    ctx.fill();

    if ( this.radar ) {
      this.radar.draw( this.x, this.y );
    }
  };

  Player.prototype.update = function( dt ) {
    var dx = dt * 128;
    var dy = dt * 128;

    if ( game.input.keys[ 37 ] ) { this.x -= dx; }
    if ( game.input.keys[ 39 ] ) { this.x += dx; }
    if ( game.input.keys[ 38 ] ) { this.y -= dy; }
    if ( game.input.keys[ 40 ] ) { this.y += dy; }
  };

  function Game() {
    this.prevTime = Date.now();
    this.currTime = this.prevTime;
    this.running = true;

    this.canvas = document.createElement( 'canvas' );
    this.ctx = this.canvas.getContext( '2d' );

    this.ctx.webkitImageSmoothingEnabled = false;
    this.ctx.imageSmoothingEnabled = false;

    this.canvas.width = 512;
    this.canvas.height = 512;

    document.body.appendChild( this.canvas );

    this.entities = [];

    this.input = {
      keys: [],
      mouse: {
        x: 0,
        y: 0,

        down: false
      },

      lastPressed: []
    };

    this.player = new Player( 256, 480 );
    this.entities.push( this.player );
    this.backgroundCanvas = document.createElement( 'canvas' );
    this.backgroundCtx = this.backgroundCanvas.getContext( '2d' );
    this.backgroundCanvas.width = this.canvas.width;
    this.backgroundCanvas.height = this.canvas.height;

    drawBackground( this.backgroundCtx, 32, 32, {
      hue: 120,
      saturation: 20,
      lightness: 40,
      hueSpread: 10,
      saturationSpread: 5,
      lightnessSpread: 5
    });
  }

  Game.prototype.draw = function() {
    var ctx = this.ctx;

    var width = ctx.canvas.width,
        height = ctx.canvas.height;

    ctx.clearRect( 0, 0, width, height );
    ctx.fillStyle = 'white';
    ctx.fillRect( 0, 0, width, height );

    ctx.drawImage( this.backgroundCanvas, 0, 0 );
    drawKeys( ctx, this.input.keys, this.input.lastPressed );

    this.entities.forEach(function( entity ) {
      entity.draw( ctx );
    });
  };

  Game.prototype.update = function() {
    if ( !this.prevTime ) {
      this.prevTime = Date.now();
      return;
    }

    this.currTime = Date.now();
    var dt = this.currTime - this.prevTime;
    this.prevTime = this.currTime;

    if ( dt > 1e2 ) {
      dt = 1e2;
    }

    dt *= 1e-3;

    this.entities.forEach(function( entity ) {
      entity.update( dt );
    });
  };

  var game = new Game();

  function onKeyDown( event ) {
    // console.log(event.which)
    game.input.keys[ event.which ] = true;
    game.input.lastPressed[ event.which ] = Date.now();
  }

  function onKeyUp( event ) {
    game.input.keys[ event.which ] = false;
  }

  function tick() {
    if ( !game.running ) {
      return;
    }

    game.update();
    game.draw();
    window.requestAnimationFrame( tick );
  }

  tick();

  document.addEventListener( 'keydown', onKeyDown );
  document.addEventListener( 'keyup', onKeyUp );
}) ( window, document );
<|endoftext|>


<commit_before>var Game = function(startBoard) {
  this.completed = false;
  this.startBoard = startBoard;
  this.board = this.makeBoard(startBoard);
};

Game.prototype.makeBoard = function(stringBoard){
  if (stringBoard.length !== 16){
    alert("Starting boards must be 16 digits long, you silly hobbit!");
    return false
  } else {
    var board = [];
    for (var i = 0; i < stringBoard.length; i+=4) {
      var array = [];
      for (var j = i; j < i+4; j++) {
      array.push(parseInt(stringBoard[j]));
      }
    board.push(array);
    }
  }
  return board;
};

Game.prototype.logBoard = function(){
  this.board.forEach(function(ele){
    console.log(ele.join(""));
  }
};

Game.prototype.moveLeft = function(){
  var self = this;
  var board = this.board;
  for (var i = 0; i < board.length; i++) {
    var row = board[i];
    var zeroless = row.filter(function(i) { return i !== 0}) // creates row without 0s

    for (var j = 0; j < zeroless.length; j++) {
      if (zeroless[j] === zeroless[j+1]) {
        zeroless[j] = zeroless[j] * 2;
        zeroless.splice(j+1, 1);
      } else {
        zeroless[j] = zeroless[j]
      } // (no change)
    }
    var counter = row.length - zeroless.length;
    for (var k = 0; k < counter; k++) {
      zeroless.push(0);
    }
    self.board[i] = zeroless;
  }
};

test = new Game("0224240200448008");

<commit_msg> added move up and move down methods using transpose<commit_after>var Game = function(startBoard) {
  this.completed = false;
  this.startBoard = startBoard;
  this.board = this.makeBoard(startBoard);
};

Game.prototype.makeBoard = function(stringBoard){
  if (stringBoard.length !== 16){
    alert("Starting boards must be 16 digits long, you silly hobbit!");
    return false
  } else {
    var board = [];
    for (var i = 0; i < stringBoard.length; i+=4) {
      var array = [];
      for (var j = i; j < i+4; j++) {
      array.push(parseInt(stringBoard[j]));
      }
    board.push(array);
    }
  }
  return board;
};

Game.prototype.logBoard = function(){
  this.board.forEach(function(ele){
    console.log(ele.join(" "));
  });
};

Game.prototype.moveLeft = function(){
  var self = this;
  var board = this.board;
  for (var i = 0; i < board.length; i++) {
    var row = board[i];
    var zeroless = row.filter(function(i) { return i !== 0}) // creates row without 0s

    for (var j = 0; j < zeroless.length; j++) {
      if (zeroless[j] === zeroless[j+1]) {
        zeroless[j] = zeroless[j] * 2;
        zeroless.splice(j+1, 1);
      } else {
        zeroless[j] = zeroless[j]
      } // (no change)
    }
    var counter = row.length - zeroless.length;
    for (var k = 0; k < counter; k++) {
      zeroless.push(0);
    }
    self.board[i] = zeroless;
  }
};

Game.prototype.moveRight = function(){
  var self = this;
  var board = this.board;
  for (var i = 0; i < board.length; i++) {
    var row = board[i];
    var zeroless = row.filter(function(i) { return i !== 0} ); // creates row without 0s
    for (var j = zeroless.length - 1; j >= 0; j--) {
     if (zeroless[j] === zeroless[(j-1)]) {
        zeroless[j] = zeroless[j] * 2;
        zeroless.splice(j-1, 1);
      } else {
        zeroless[j] = zeroless[j]
      } // (no change)
    }
    var counter = row.length - zeroless.length;
    for (var k = 0; k < counter; k++) {
      zeroless.unshift(0);
    }
    self.board[i] = zeroless;
  }
};

Game.prototype.moveUp = function(){
  this.board = _.zip.apply(null, this.board);
  this.moveLeft();
  this.board = _.zip.apply(null, this.board);
};

Game.prototype.moveDown = function(){
  this.board = _.zip.apply(null, this.board);
  this.moveRight();
  this.board = _.zip.apply(null, this.board);
};

test = new Game("0224240200448008");

<|endoftext|>


<commit_before>var async = require('async');

/**
 * @constructor
 */
var ScraperPromise = function(scraper) {
	/**
	 * Scraper to use..
	 *
	 * @type {!Scraper}
	 * @private
	 */
	this.scraper = scraper;
	/**
	 * Promise chunks.
	 *
	 * @type {!Array.<function(function(?))>}
	 * @private
	 */
	this.promises = [];
	/**
	 * Function to call when all the promises are fulfilled.
	 *
	 * @type {!function(?)}
	 * @private
	 */
	this.doneCallback = function(utils) {
		return utils.lastReturn;
	};
	/**
	 * Function to call when there's an error.
	 *
	 * @type {!function(?)}
	 * @private
	 */
	this.errorCallback = function(err) {
		throw err;
	};
	/**
	 * A parameter object to be passed to the chain, at the _fire
	 *   method. This should be set immediately before the call, and
	 *   reset to null right after the call, or after it's been stored
	 *   elsewhere.
	 *
	 * @type {?}
	 * @private
	 */
	this.chainParameter = null;
};
ScraperPromise.prototype = {
	constructor: ScraperPromise,
	/**
	 * Sets a promise for a status code, of a response of a request.
	 *
	 * @param  {!(number|function(number))} code Status code to
	 *   dispatch the message. Or a callback function, in this case
	 *   the function's first parameter is the status code, as a
	 *   number.
	 * @param  {!function()} callback Callback function for the case
	 *   where the status code is provided.
	 * @return {!ScraperPromise} This object, so that new promises can
	 *   be made.
	 * @public
	 */
	onStatusCode: function(code, callback) {
		if (typeof code == 'function') {
			callback = code;
			this.promises.push(function onGenericStatusCode(done, utils) {
				done(callback(this.scraper.getStatusCode(), utils));
			});
		} else {
			this.promises.push(function onStatusCode(done, utils) {
				if (code === this.scraper.getStatusCode()) {
					done(callback(utils));
				} else {
					done(utils.lastReturn);
				}

			});
		}
		return this;
	},
	/**
	 * Sets a promise to scrape the retrieved webpage.
	 *
	 * @param  {!function(?, ?)} scrapeFn Function to scrape the
	 *   webpage. The parameters depend on what kind of scraper.
	 * @param  {!function(?)=} callback Callback function with the
	 *   result of the scraping function. If none is provided, the
	 *   result can be accessed in the next promise with
	 *   utils.lastReturn.
	 * @param  {...?} var_args Optional arguments to pass as
	 *   parameters to the scraping function.
	 * @return {!ScraperPromise} This object, so that new promises can
	 *   be made.
	 * @public
	 */
	scrape: function(scrapeFn, callback) {
		var stackTrace = new Error().stack;

		var extraArguments = Array.prototype.slice.call(arguments, 2);
		callback = callback || function(result) {
			return result;
		};
		this.promises.push(function scrape(done, utils) {
			this.scraper.scrape(scrapeFn, function(err, result) {
				if (err) {
					done(undefined, err);
				} else {
					done(callback(result, utils));
				}
			}, extraArguments, stackTrace);
		});
		return this;
	},
	/**
	 * Sets a promise to delay the execution of the promises.
	 *
	 * @param  {!number} time Time in milliseconds to delay the
	 *   execution.
	 * @param  {!function()=} callback Function to call after the
	 *   delay.
	 * @return {!ScraperPromise} This object, so that new promises can
	 *   be made.
	 * @public
	 */
	delay: function(time, callback) {
		callback = callback || function() {};
		this.promises.push(function delay(done, utils) {
			setTimeout(function() {
				done(callback(utils));
			}, time);
		});
		return this;
	},
	/**
	 * Sets a promise to execute a promise after a time period. This
	 *   does not cause the promise chain to block.
	 *
	 * @param  {!number} time Time in milliseconds to the execution of
	 *   the callback.
	 * @param  {!function()} callback Function to call after the
	 *   time period has passed.
	 * @return {!ScraperPromise} This object, so that new promises can
	 *   be made.
	 * @public
	 */
	timeout: function(time, callback) {
		this.promises.push(function timeout(done, utils) {
			setTimeout(function() {
				callback(utils);
			}, time);
			done(undefined);
		});
		return this;
	},
	/**
	 * Sets the end of the promise chain callback, if there were no
	 *   errors.
	 *
	 * @param  {!function()} doneFn Callback function.
	 * @return {!ScraperPromise} This object, so that new promises can
	 *   be made.
	 * @public
	 */
	done: function(doneFn) {
		this.doneCallback = doneFn;
		return this;
	},
	/**
	 * Sets a generic promise.
	 *
	 * @param  {!function()} callback Callback.
	 * @return {!ScraperPromise} This object, so that new promises can
	 *   be made.
	 * @public
	 */
	then: function(callback) {
		this.promises.push(function then(done, utils) {
			done(callback(utils));
		});
		return this;
	},
	/**
	 * Stops the promise chain and resumes it after a callback
	 *   function.
	 *
	 * @param  {!function(!function, !Object)} callback Callback.
	 * @return {!ScraperPromise} This object, so that new promises can
	 *   be made.
	 * @public
	 */
	async: function(callback) {
		this.promises.push(function async(done, utils) {
			callback(done, utils);
		});
		return this;
	},
	/**
	 * @deprecated
	 */
	onError: function(callback) {
		console.warn("The 'onError' is being DEPRECATED in favor of 'catch'");
		return this.catch(callback);
	},
	/**
	 * Sets a promise to when an error occur, note that an error will
	 *   break the promise chain, so this is the next promise to be
	 *   called and if the done promise is not set the last. To avoid
	 *   silent errors, if this promise is not defined the error will
	 *   be thrown up.
	 *
	 * @param  {!function(?)} callback Callback.
	 * @return {!ScraperPromise} This object, so that new promises can
	 *   be made.
	 * @public
	 */
	"catch": function(callback) {
		this.errorCallback = callback;
		return this;
	},
	/**
	 * Makes an HTTP GET request to the url.
	 *
	 * @param  {!string} url Url to make the request.
	 * @return {!ScraperPromise} This object, so that new promises can
	 *   be made.
	 * @public
	 */
	get: function(url) {
		var that = this;
		this.scraper.get(url, function(err) {
			that._fire(err);
		});
		return this;
	},
	/**
	 * Makes a (possible more complex) HTTP request. For more
	 *   information refer to {@link https://github.com/mikeal/request#requestoptions-callback}.
	 *
	 * @param  {!Object} options Options of the request.
	 * @return {!ScraperPromise} This object, so that new promises can
	 *   be made.
	 * @public
	 */
	request: function(options) {
		var that = this;
		this.scraper.request(options, function(err) {
			that._fire(err);
		});
		return this;
	},
	/**
	 * Sets a parameter to be used in the next _fire call.
	 *
	 * @param {?Object} param Parameter.
	 * @public
	 */
	_setChainParameter: function(param) {
		this.chainParameter = param;
	},
	/**
	 * Starts the promise chain.
	 *
	 * @param  {?} error Error object, to fire the error callback,
	 *   from an error that happened before.
	 * @param  {!Scraper} scraper Scraper to use in the promise chain.
	 * @protected
	 */
	_fire: function(error) {
		var that = this,
			param = this.chainParameter,
			stopPointer = {},
			utils = {
				stop: null,
				url: this.scraper.url,
				scraper: this,
				params: param,
				lastReturn: undefined
			},
			keep = true;
		this.chainParameter = null;

		if (error) {
			this.errorCallback(error, utils);
			this.doneCallback(utils);
			return;
		}

		async.eachSeries(this.promises, function dispatcher(fn, callback) {
			var done = function(lastReturn, err) {
				utils.lastReturn = lastReturn;
				if (err === stopPointer) {
					keep = false;
					callback(err);
				} else if (err) {
					callback(err);
				} else if (keep) {
					callback();
				}
			};
			utils.stop = function() {
				done(null, stopPointer);
			};

			try {
				fn.call(that, done, utils);
			} catch (err) {
				done(null, err);
			}
		}, function(err) {
			utils.stop = null;
			if (err && err !== stopPointer) {
				that.errorCallback(err, utils);
			}
			that.doneCallback(utils);
			that.scraper.close();
		});
	},
	/**
	 * Sets the promises.
	 *
	 * @param {!Array.<function(function(?))>} promises Promises array.
	 * @public
	 */
	_setPromises: function(promises) {
		this.promises = promises;
	},
	/**
	 * Clones the promise and the scraper.
	 *
	 * @return {!ScraperPromise} Scraper promise with an empty scraper
	 *   clone.
	 * @public
	 */
	clone: function() {
		var instance = this.scraper.clone(),
			promise = new ScraperPromise(instance);
		promise._setPromises(this.promises);
		promise.done(this.doneCallback);
		promise.onError(this.errorCallback);
		return promise;
	}
};

module.exports = ScraperPromise;
<commit_msg>The then promise now receives the last value returned has the first argument and the utils object as the second.<commit_after>var async = require('async');

/**
 * @constructor
 */
var ScraperPromise = function(scraper) {
	/**
	 * Scraper to use..
	 *
	 * @type {!Scraper}
	 * @private
	 */
	this.scraper = scraper;
	/**
	 * Promise chunks.
	 *
	 * @type {!Array.<function(function(?))>}
	 * @private
	 */
	this.promises = [];
	/**
	 * Function to call when all the promises are fulfilled.
	 *
	 * @type {!function(?)}
	 * @private
	 */
	this.doneCallback = function(utils) {
		return utils.lastReturn;
	};
	/**
	 * Function to call when there's an error.
	 *
	 * @type {!function(?)}
	 * @private
	 */
	this.errorCallback = function(err) {
		throw err;
	};
	/**
	 * A parameter object to be passed to the chain, at the _fire
	 *   method. This should be set immediately before the call, and
	 *   reset to null right after the call, or after it's been stored
	 *   elsewhere.
	 *
	 * @type {?}
	 * @private
	 */
	this.chainParameter = null;
};
ScraperPromise.prototype = {
	constructor: ScraperPromise,
	/**
	 * Sets a promise for a status code, of a response of a request.
	 *
	 * @param  {!(number|function(number))} code Status code to
	 *   dispatch the message. Or a callback function, in this case
	 *   the function's first parameter is the status code, as a
	 *   number.
	 * @param  {!function()} callback Callback function for the case
	 *   where the status code is provided.
	 * @return {!ScraperPromise} This object, so that new promises can
	 *   be made.
	 * @public
	 */
	onStatusCode: function(code, callback) {
		if (typeof code == 'function') {
			callback = code;
			this.promises.push(function onGenericStatusCode(done, utils) {
				done(callback(this.scraper.getStatusCode(), utils));
			});
		} else {
			this.promises.push(function onStatusCode(done, utils) {
				if (code === this.scraper.getStatusCode()) {
					done(callback(utils));
				} else {
					done(utils.lastReturn);
				}

			});
		}
		return this;
	},
	/**
	 * Sets a promise to scrape the retrieved webpage.
	 *
	 * @param  {!function(?, ?)} scrapeFn Function to scrape the
	 *   webpage. The parameters depend on what kind of scraper.
	 * @param  {!function(?)=} callback Callback function with the
	 *   result of the scraping function. If none is provided, the
	 *   result can be accessed in the next promise with
	 *   utils.lastReturn.
	 * @param  {...?} var_args Optional arguments to pass as
	 *   parameters to the scraping function.
	 * @return {!ScraperPromise} This object, so that new promises can
	 *   be made.
	 * @public
	 */
	scrape: function(scrapeFn, callback) {
		var stackTrace = new Error().stack;

		var extraArguments = Array.prototype.slice.call(arguments, 2);
		callback = callback || function(result) {
			return result;
		};
		this.promises.push(function scrape(done, utils) {
			this.scraper.scrape(scrapeFn, function(err, result) {
				if (err) {
					done(undefined, err);
				} else {
					done(callback(result, utils));
				}
			}, extraArguments, stackTrace);
		});
		return this;
	},
	/**
	 * Sets a promise to delay the execution of the promises.
	 *
	 * @param  {!number} time Time in milliseconds to delay the
	 *   execution.
	 * @param  {!function()=} callback Function to call after the
	 *   delay.
	 * @return {!ScraperPromise} This object, so that new promises can
	 *   be made.
	 * @public
	 */
	delay: function(time, callback) {
		callback = callback || function() {};
		this.promises.push(function delay(done, utils) {
			setTimeout(function() {
				done(callback(utils));
			}, time);
		});
		return this;
	},
	/**
	 * Sets a promise to execute a promise after a time period. This
	 *   does not cause the promise chain to block.
	 *
	 * @param  {!number} time Time in milliseconds to the execution of
	 *   the callback.
	 * @param  {!function()} callback Function to call after the
	 *   time period has passed.
	 * @return {!ScraperPromise} This object, so that new promises can
	 *   be made.
	 * @public
	 */
	timeout: function(time, callback) {
		this.promises.push(function timeout(done, utils) {
			setTimeout(function() {
				callback(utils);
			}, time);
			done(undefined);
		});
		return this;
	},
	/**
	 * Sets the end of the promise chain callback, if there were no
	 *   errors.
	 *
	 * @param  {!function()} doneFn Callback function.
	 * @return {!ScraperPromise} This object, so that new promises can
	 *   be made.
	 * @public
	 */
	done: function(doneFn) {
		this.doneCallback = doneFn;
		return this;
	},
	/**
	 * Sets a generic promise.
	 *
	 * @param  {!function()} callback Callback.
	 * @return {!ScraperPromise} This object, so that new promises can
	 *   be made.
	 * @public
	 */
	then: function(callback) {
		this.promises.push(function then(done, utils) {
			done(callback(utils.lastReturn, utils));
		});
		return this;
	},
	/**
	 * Stops the promise chain and resumes it after a callback
	 *   function.
	 *
	 * @param  {!function(!function, !Object)} callback Callback.
	 * @return {!ScraperPromise} This object, so that new promises can
	 *   be made.
	 * @public
	 */
	async: function(callback) {
		this.promises.push(function async(done, utils) {
			callback(done, utils);
		});
		return this;
	},
	/**
	 * @deprecated
	 */
	onError: function(callback) {
		console.warn("The 'onError' is being DEPRECATED in favor of 'catch'");
		return this.catch(callback);
	},
	/**
	 * Sets a promise to when an error occur, note that an error will
	 *   break the promise chain, so this is the next promise to be
	 *   called and if the done promise is not set the last. To avoid
	 *   silent errors, if this promise is not defined the error will
	 *   be thrown up.
	 *
	 * @param  {!function(?)} callback Callback.
	 * @return {!ScraperPromise} This object, so that new promises can
	 *   be made.
	 * @public
	 */
	"catch": function(callback) {
		this.errorCallback = callback;
		return this;
	},
	/**
	 * Makes an HTTP GET request to the url.
	 *
	 * @param  {!string} url Url to make the request.
	 * @return {!ScraperPromise} This object, so that new promises can
	 *   be made.
	 * @public
	 */
	get: function(url) {
		var that = this;
		this.scraper.get(url, function(err) {
			that._fire(err);
		});
		return this;
	},
	/**
	 * Makes a (possible more complex) HTTP request. For more
	 *   information refer to {@link https://github.com/mikeal/request#requestoptions-callback}.
	 *
	 * @param  {!Object} options Options of the request.
	 * @return {!ScraperPromise} This object, so that new promises can
	 *   be made.
	 * @public
	 */
	request: function(options) {
		var that = this;
		this.scraper.request(options, function(err) {
			that._fire(err);
		});
		return this;
	},
	/**
	 * Sets a parameter to be used in the next _fire call.
	 *
	 * @param {?Object} param Parameter.
	 * @public
	 */
	_setChainParameter: function(param) {
		this.chainParameter = param;
	},
	/**
	 * Starts the promise chain.
	 *
	 * @param  {?} error Error object, to fire the error callback,
	 *   from an error that happened before.
	 * @param  {!Scraper} scraper Scraper to use in the promise chain.
	 * @protected
	 */
	_fire: function(error) {
		var that = this,
			param = this.chainParameter,
			stopPointer = {},
			utils = {
				stop: null,
				url: this.scraper.url,
				scraper: this,
				params: param,
				lastReturn: undefined
			},
			keep = true;
		this.chainParameter = null;

		if (error) {
			this.errorCallback(error, utils);
			this.doneCallback(utils);
			return;
		}

		async.eachSeries(this.promises, function dispatcher(fn, callback) {
			var done = function(lastReturn, err) {
				utils.lastReturn = lastReturn;
				if (err === stopPointer) {
					keep = false;
					callback(err);
				} else if (err) {
					callback(err);
				} else if (keep) {
					callback();
				}
			};
			utils.stop = function() {
				done(null, stopPointer);
			};

			try {
				fn.call(that, done, utils);
			} catch (err) {
				done(null, err);
			}
		}, function(err) {
			utils.stop = null;
			if (err && err !== stopPointer) {
				that.errorCallback(err, utils);
			}
			that.doneCallback(utils);
			that.scraper.close();
		});
	},
	/**
	 * Sets the promises.
	 *
	 * @param {!Array.<function(function(?))>} promises Promises array.
	 * @public
	 */
	_setPromises: function(promises) {
		this.promises = promises;
	},
	/**
	 * Clones the promise and the scraper.
	 *
	 * @return {!ScraperPromise} Scraper promise with an empty scraper
	 *   clone.
	 * @public
	 */
	clone: function() {
		var instance = this.scraper.clone(),
			promise = new ScraperPromise(instance);
		promise._setPromises(this.promises);
		promise.done(this.doneCallback);
		promise.onError(this.errorCallback);
		return promise;
	}
};

module.exports = ScraperPromise;
<|endoftext|>


<commit_before>var Game = (function(global, doc){

	var Game, Sprite, SpriteMap, SpriteMapCurves, Stage, GameCanvas, Const, Engine, Directions, RoundRecorder;

	/**
	 * Constants
	 * @type {Object}
	 */
	Const = {
		TILE_SIZE: 20,
		GAME_SPEED: 100, // miliseconds
		UP: 0,
		RIGHT: 1,
		DOWN: 2,
		LEFT: 3
	};

	/**
	 * Sprites maps coords in XY format
	 */
	SpriteMap = {
		// Hands
		HAND_UP: [0, 0],
		HAND_DOWN: [20, 20],
		HAND_RIGHT: [20, 0],
		HAND_LEFT: [0, 20],

		// Arms
		ARMS_V: [0, 40],
		ARMS_H: [20, 40],

		// Itens
		HEART: [0, 100],
		KEY: [20, 100]
	};

	SpriteMapCurves = {
		UR: [0, 60],
		UL: [20, 60],

		RD: [20, 60],
		RU: [20, 80],

		DL: [20, 80],
		DR: [0, 80],

		LU: [0, 80],
		LD: [0, 60],
	};

	Engine = {
		interval: null
	};

	Directions = {
		previous: 0,
		current: 0
	};

	RoundRecorder = {
		IS_CURVE: true,

		timeline: [],

		record: function (x, y, direction) {
			this.timeline.push({x: x, y: y, direction: direction, isCurve: false});
		},

		backInTheTime: function (n) {
			var len = this.timeline.length;
			return this.timeline[len - 1 - n] || undefined;
		},

		chancePast: function (i, x, y, direction, isCurve) {
			this.timeline[i] = {x: x, y: y, direction: direction, isCurve: isCurve || false};
		},

		prevPosition: function () {
			return this.backInTheTime(0);
		},

		lastIndex: function () {
			return this.timeline.length - 1;
		},

		reset: function () {
			this.timeline = [];
		}
	};

	Game = {
		isStarted: false,

		position: [15, 23],

		stageSize: {
			h: 640 / 20,
			v: 480 / 20
		},

		init: function () {
			GameCanvas = doc.getElementById('game');
			GameCanvas.width = 640;
			GameCanvas.height = 480;

			Stage = GameCanvas.getContext('2d');

			Sprite = new Image();
			Sprite.src = 'img/sprites.png';

			this.bindKeyEvents();

			return this;
		},

		loadMap: function () {
			// Implements this after
		},

		getCoords: function (x, y) {
			var tileSize = Const.TILE_SIZE,
				coordX = (((x + 1) * tileSize) - tileSize),
				coordY = (((y + 1) * tileSize) - tileSize);

			return [coordX, coordY];
		},

		drawAt: function (x, y, spriteName) {
			var tileSize = Const.TILE_SIZE,
				coords = this.getCoords(x, y),
				spriteCoords = this.getTileCoordsByName(spriteName);

			if (!spriteCoords) {
				console.log(arguments);
				this.gameOver();
				return;
			}

			Stage.drawImage(Sprite, spriteCoords[0], spriteCoords[1], tileSize, tileSize, coords[0], coords[1], tileSize, tileSize);
		},

		run: function () {
			var self = this;
			doc.body.focus();
			this.isStarted = true;
			this.goToNext();

			Engine.interval = setInterval(function () {
				self.goToNext();
			}, Const.GAME_SPEED);
		},

		canGoNext: function () {
			var goToX,
				goToY,
				x = this.position[0],
				y = this.position[1];

			switch (Directions.current) {
				case Const.UP:
					goToY = y - 1;
				break;
				case Const.DOWN:
					goToY = y + 1;
				break;
				default:
					goToY = y;
			}

			switch (Directions.current) {
				case Const.LEFT:
					goToX = x - 1;
				break;
				case Const.RIGHT:
					goToX = x + 1;
				break;
				default:
					goToX = x;
			}

			if (x <= 0 || y <= 0 || x >= this.stageSize.h || y >= this.stageSize.v) {
				return false;
			} else {
				return [goToX, goToY];
			}
		},

		goToNext: function () {
			var next = this.canGoNext(),
				dirs = ['UP', 'RIGHT', 'DOWN', 'LEFT'],
				before,
				beforeBefore,
				tile,
				n;

			if (next !== false) {
				if (RoundRecorder.prevPosition() !== undefined) {
					before = RoundRecorder.prevPosition();

					if (before.isCurve === false) {
						tile = this.getTileToNextMove(before.direction);
						this.drawAt(before.x, before.y, tile);

						console.log(tile);
					} else {}
				} else {
					console.log('caguei aki');
				}

				this.position = next;
				RoundRecorder.record(next[0], next[1], Directions.current);
				Directions.previous = Directions.current;

				this.drawAt(next[0], next[1], 'HAND_' + dirs[Directions.current]);

				n = this.canGoNext();

				if (n === false) {
					this.gameOver();
				}
			}
		},

		getTileToNextMove: function (dir) {
			var direction = dir || Directions.current,
				tile = '';

			if (direction === Const.LEFT || direction === Const.RIGHT) {
				tile = 'ARMS_H';
			} else if (direction === Const.UP || direction === Const.DOWN) {
				tile = 'ARMS_V';
			}

			return tile;
		},

		getTileCoordsByName: function (name) {
			return SpriteMap['' + name + ''] || SpriteMapCurves['' + name + ''];
		},

		gameOver: function () {
			clearInterval(Engine.interval);
			this.isStarted = false;
			console.log('Oh not! It`s over ;(');
			console.log(RoundRecorder.timeline);
		},

		changeDirectionOnKeyPress: function (event) {
			var current = Directions.current,
				newDirection,
				dirs = ['U', 'R', 'D', 'L'];

			if (this.isStarted ) {
				switch (event.keyCode) {
					case 37:
						newDirection = Const.LEFT;
					break;

					case 38:
						newDirection = Const.UP;
					break;

					case 39:
						newDirection = Const.RIGHT;
					break;

					case 40:
						newDirection = Const.DOWN;
					break;
				}

				if (current === Const.LEFT && newDirection === Const.RIGHT) {
					return;
				}

				if (current === Const.RIGHT && newDirection === Const.LEFT) {
					return;
				}

				if (current === Const.DOWN && newDirection === Const.UP) {
					return;
				}

				if (current === Const.UP && newDirection === Const.DOWN) {
					return;
				}

				if (newDirection !== Directions.previous) {

					RoundRecorder.chancePast(RoundRecorder.lastIndex(), this.position[0], this.position[1], Directions.current, RoundRecorder.IS_CURVE);

					console.log(RoundRecorder.backInTheTime(0));

					Directions.current = newDirection;
					this.fixMoveCurve(dirs[Directions.previous] + dirs[Directions.current]);
				}

			}
		},

		fixMoveCurve: function (tile) {
			Stage.clearRect(this.position[0], this.position[1], Const.TILE_SIZE, Const.TILE_SIZE);
			this.drawAt(this.position[0], this.position[1], tile);
		},

		bindKeyEvents: function () {
			doc.onkeydown = function (e) {
				Game.changeDirectionOnKeyPress(e);
			};
		}
	};

	return Game.init();

}(window, document));

document.getElementById('start').onclick = function () {
	Game.run();
};<commit_msg>turn all things more fast =)<commit_after>var Game = (function(global, doc){

	var Game, Sprite, SpriteMap, SpriteMapCurves, Stage, GameCanvas, Const, Engine, Directions, RoundRecorder;

	/**
	 * Constants
	 * @type {Object}
	 */
	Const = {
		TILE_SIZE: 20,
		GAME_SPEED: 40, // miliseconds
		UP: 0,
		RIGHT: 1,
		DOWN: 2,
		LEFT: 3
	};

	/**
	 * Sprites maps coords in XY format
	 */
	SpriteMap = {
		// Hands
		HAND_UP: [0, 0],
		HAND_DOWN: [20, 20],
		HAND_RIGHT: [20, 0],
		HAND_LEFT: [0, 20],

		// Arms
		ARMS_V: [0, 40],
		ARMS_H: [20, 40],

		// Itens
		HEART: [0, 100],
		KEY: [20, 100]
	};

	SpriteMapCurves = {
		UR: [0, 60],
		UL: [20, 60],

		RD: [20, 60],
		RU: [20, 80],

		DL: [20, 80],
		DR: [0, 80],

		LU: [0, 80],
		LD: [0, 60],
	};

	Engine = {
		interval: null
	};

	Directions = {
		previous: 0,
		current: 0
	};

	RoundRecorder = {
		IS_CURVE: true,

		timeline: [],

		record: function (x, y, direction) {
			this.timeline.push({x: x, y: y, direction: direction, isCurve: false});
		},

		backInTheTime: function (n) {
			var len = this.timeline.length;
			return this.timeline[len - 1 - n] || undefined;
		},

		chancePast: function (i, x, y, direction, isCurve) {
			this.timeline[i] = {x: x, y: y, direction: direction, isCurve: isCurve || false};
		},

		prevPosition: function () {
			return this.backInTheTime(0);
		},

		lastIndex: function () {
			return this.timeline.length - 1;
		},

		reset: function () {
			this.timeline = [];
		}
	};

	Game = {
		isStarted: false,

		position: [15, 23],

		stageSize: {
			h: 640 / 20,
			v: 480 / 20
		},

		init: function () {
			GameCanvas = doc.getElementById('game');
			GameCanvas.width = 640;
			GameCanvas.height = 480;

			Stage = GameCanvas.getContext('2d');

			Sprite = new Image();
			Sprite.src = 'img/sprites.png';

			this.bindKeyEvents();

			return this;
		},

		loadMap: function () {
			// Implements this after
		},

		getCoords: function (x, y) {
			var tileSize = Const.TILE_SIZE,
				coordX = (((x + 1) * tileSize) - tileSize),
				coordY = (((y + 1) * tileSize) - tileSize);

			return [coordX, coordY];
		},

		drawAt: function (x, y, spriteName) {
			var tileSize = Const.TILE_SIZE,
				coords = this.getCoords(x, y),
				spriteCoords = this.getTileCoordsByName(spriteName);

			if (!spriteCoords) {
				console.log(arguments);
				this.gameOver();
				return;
			}

			Stage.drawImage(Sprite, spriteCoords[0], spriteCoords[1], tileSize, tileSize, coords[0], coords[1], tileSize, tileSize);
		},

		run: function () {
			var self = this;
			doc.body.focus();
			this.isStarted = true;
			this.goToNext();

			Engine.interval = setInterval(function () {
				self.goToNext();
			}, Const.GAME_SPEED);
		},

		canGoNext: function () {
			var goToX,
				goToY,
				x = this.position[0],
				y = this.position[1];

			switch (Directions.current) {
				case Const.UP:
					goToY = y - 1;
				break;
				case Const.DOWN:
					goToY = y + 1;
				break;
				default:
					goToY = y;
			}

			switch (Directions.current) {
				case Const.LEFT:
					goToX = x - 1;
				break;
				case Const.RIGHT:
					goToX = x + 1;
				break;
				default:
					goToX = x;
			}

			if (x <= 0 || y <= 0 || x >= this.stageSize.h || y >= this.stageSize.v) {
				return false;
			} else {
				return [goToX, goToY];
			}
		},

		goToNext: function () {
			var next = this.canGoNext(),
				dirs = ['UP', 'RIGHT', 'DOWN', 'LEFT'],
				before,
				beforeBefore,
				tile,
				n;

			if (next !== false) {
				if (RoundRecorder.prevPosition() !== undefined) {
					before = RoundRecorder.prevPosition();

					if (before.isCurve === false) {
						tile = this.getTileToNextMove(before.direction);
						this.drawAt(before.x, before.y, tile);

						console.log(tile);
					} else {}
				} else {
					console.log('caguei aki');
				}

				this.position = next;
				RoundRecorder.record(next[0], next[1], Directions.current);
				Directions.previous = Directions.current;

				this.drawAt(next[0], next[1], 'HAND_' + dirs[Directions.current]);

				n = this.canGoNext();

				if (n === false) {
					this.gameOver();
				}
			}
		},

		getTileToNextMove: function (dir) {
			var direction = dir || Directions.current,
				tile = '';

			if (direction === Const.LEFT || direction === Const.RIGHT) {
				tile = 'ARMS_H';
			} else if (direction === Const.UP || direction === Const.DOWN) {
				tile = 'ARMS_V';
			}

			return tile;
		},

		getTileCoordsByName: function (name) {
			return SpriteMap['' + name + ''] || SpriteMapCurves['' + name + ''];
		},

		gameOver: function () {
			clearInterval(Engine.interval);
			this.isStarted = false;
			console.log('Oh not! It`s over ;(');
			console.log(RoundRecorder.timeline);
		},

		changeDirectionOnKeyPress: function (event) {
			var current = Directions.current,
				newDirection,
				dirs = ['U', 'R', 'D', 'L'];

			if (this.isStarted ) {
				switch (event.keyCode) {
					case 37:
						newDirection = Const.LEFT;
					break;

					case 38:
						newDirection = Const.UP;
					break;

					case 39:
						newDirection = Const.RIGHT;
					break;

					case 40:
						newDirection = Const.DOWN;
					break;
				}

				if (current === Const.LEFT && newDirection === Const.RIGHT) {
					return;
				}

				if (current === Const.RIGHT && newDirection === Const.LEFT) {
					return;
				}

				if (current === Const.DOWN && newDirection === Const.UP) {
					return;
				}

				if (current === Const.UP && newDirection === Const.DOWN) {
					return;
				}

				if (newDirection !== Directions.previous) {

					RoundRecorder.chancePast(RoundRecorder.lastIndex(), this.position[0], this.position[1], Directions.current, RoundRecorder.IS_CURVE);

					console.log(RoundRecorder.backInTheTime(0));

					Directions.current = newDirection;
					this.fixMoveCurve(dirs[Directions.previous] + dirs[Directions.current]);
				}

			}
		},

		fixMoveCurve: function (tile) {
			Stage.clearRect(this.position[0], this.position[1], Const.TILE_SIZE, Const.TILE_SIZE);
			this.drawAt(this.position[0], this.position[1], tile);
		},

		bindKeyEvents: function () {
			doc.onkeydown = function (e) {
				Game.changeDirectionOnKeyPress(e);
			};
		}
	};

	return Game.init();

}(window, document));

document.getElementById('start').onclick = function () {
	Game.run();
};<|endoftext|>


<commit_before>// Initialise Phaser

var w = $(window).width();
var h = $(window).height();
var game = new Phaser.Game(w, h, Phaser.AUTO, 'gameDiv');

window.addEventListener("resize", function() { location.reload(); }, false);
// The above listener reloads the page on screen rotate to get Phaser to reset everything properly for the new orientation.

// Initialise Variables
var audio_duration = [];
var text;
var caption = [];
var page_no;
var counter = 0;
var pages = 0;
var image;
var audio_loc;
var rightbutton;
var leftbutton;
var back_colour = '#3498db';
var caption_colour = '#fff';
var current_audio = 0;
var too_soon = 0;
var main_audio;

function now_okay() {
    too_soon = 0;
}

    function layout_screen () {

    w = $(window).width();
    h = $(window).height();

    game.width=w;
    game.height=h;
    // game.stage.bounds.width = w;
    // game.stage.bounds.height = h;

    if (game.renderType === Phaser.WEBGL) {
	   game.renderer.resize(w, h);
    }

    var imageW;
    var imageH;
    /*
    if (h>w) {
      imageW=w*0.8;
      imageH = (imageW*0.7);
    } else {
      imageH = h*0.7;
      imageW= imageH*1.333;
    }

    image.width=imageW;
    image.height=imageH;
    image.x=w/2;
    image.y=h*0.05;
    */
    image.width=w;
    image.height=h;
    image.x=w/2;
    image.y=0;

    leftbutton.width= w/2;
    leftbutton.height=h;

    rightbutton.width= w/2;
    rightbutton.height=h;
    rightbutton.x = w/2;

    text.x = w/2;
    text.y=(h-h*0.2);

    page_no.x = (w*0.9);
    page_no.y = (h-h*0.1);

} // END layout_screen

function listener_left () {

  if (too_soon==0) {
    game.time.events.add(Phaser.Timer.SECOND * 1.5, now_okay, this);
    too_soon=1;
    counter--;
    if (counter<0) { counter = 0 };
    fx.stop(current_audio);
    fx.play(counter);
    current_audio = counter;
    text.text = caption[counter];
    page_no.text = counter+1;
    image.loadTexture(counter+1);
    image.anchor.setTo(0.5, 0);

    /*
    var imageW;
    var imageH;

    if (h>w) {
      imageW=w*0.8;
      imageH = (imageW*0.7);
    } else {
      imageH = h*0.7;
      imageW= imageH*1.333;
    }

    image.width=imageW;
    image.height=imageH;
    */
    image.width=w;
    image.height=h;

    if (counter >= pages-2) { counter = 0; }

  } // END too_soon

} // END listener_left

function listener_right () {

  if (too_soon==0) {
    game.time.events.add(Phaser.Timer.SECOND * 1.5, now_okay, this);
    too_soon=1;
    counter++;
    fx.stop(current_audio);
    fx.play(counter);
    current_audio = counter;
    text.text = caption[counter];
    page_no.text = counter+1;

    image.loadTexture(counter+1);
    image.anchor.setTo(0.5, 0);
    /*
    var imageW;
    var imageH;

    if (h>w) {
      imageW=w*0.8;
      imageH = (imageW*0.7);
    } else {
      imageH = h*0.7;
      imageW= imageH*1.333;
    }

    image.width=imageW;
    image.height=imageH;
    */
    image.width=w;
    image.height=h;
    if (counter >= pages-1) { counter = -1; }
  } // END Too Soon

} // END listener_right

function goto_start () {

  if (too_soon==0) {
    game.time.events.add(Phaser.Timer.SECOND * 1.5, now_okay, this);
    too_soon=1;
    counter=0;
    fx.stop(current_audio);
    fx.play(counter);
    current_audio = counter;
    text.text = caption[counter];
    page_no.text = counter+1;
    image.loadTexture(counter+1);
    image.anchor.setTo(0.5, 0);

      /*
    var imageW;
    var imageH;

    if (h>w) {
      imageW=w*0.8;
      imageH = (imageW*0.7);
    } else {
      imageH = h*0.7;
      imageW= imageH*1.333;
    }

    image.width=imageW;
    image.height=imageH;
    */
    image.width=w;
    image.height=h;

  } // END too_soon

} // END goto_start

// Add all the states
game.state.add('boot', bootState);
game.state.add('load', loadState);
game.state.add('play', playState);
// Start the 'boot' state
// game.state.start('boot');
<commit_msg>Bug Fix<commit_after>// Initialise Phaser

var w = $(window).width();
var h = $(window).height();
var game = new Phaser.Game(w, h, Phaser.AUTO, 'gameDiv');

window.addEventListener("resize", function() { location.reload(); }, false);
// The above listener reloads the page on screen rotate to get Phaser to reset everything properly for the new orientation.

// Initialise Variables
var audio_duration = [];
var text;
var caption = [];
var page_no;
var counter = 0;
var pages = 0;
var image;
var audio_loc;
var rightbutton;
var leftbutton;
var back_colour = '#3498db';
var caption_colour = '#fff';
var current_audio = 0;
var too_soon = 0;
var main_audio;
var fx;

function now_okay() {
    too_soon = 0;
}

    function layout_screen () {

    w = $(window).width();
    h = $(window).height();

    game.width=w;
    game.height=h;
    // game.stage.bounds.width = w;
    // game.stage.bounds.height = h;

    if (game.renderType === Phaser.WEBGL) {
	   game.renderer.resize(w, h);
    }

    var imageW;
    var imageH;
    /*
    if (h>w) {
      imageW=w*0.8;
      imageH = (imageW*0.7);
    } else {
      imageH = h*0.7;
      imageW= imageH*1.333;
    }

    image.width=imageW;
    image.height=imageH;
    image.x=w/2;
    image.y=h*0.05;
    */
    image.width=w;
    image.height=h;
    image.x=w/2;
    image.y=0;

    leftbutton.width= w/2;
    leftbutton.height=h;

    rightbutton.width= w/2;
    rightbutton.height=h;
    rightbutton.x = w/2;

    text.x = w/2;
    text.y=(h-h*0.2);

    page_no.x = (w*0.9);
    page_no.y = (h-h*0.1);

} // END layout_screen

function listener_left () {

  if (too_soon==0) {
    game.time.events.add(Phaser.Timer.SECOND * 1.5, now_okay, this);
    too_soon=1;
    counter--;
    if (counter<0) { counter = 0 };
    fx.stop(current_audio);
    fx.play(counter);
    current_audio = counter;
    text.text = caption[counter];
    page_no.text = counter+1;
    image.loadTexture(counter+1);
    image.anchor.setTo(0.5, 0);

    /*
    var imageW;
    var imageH;

    if (h>w) {
      imageW=w*0.8;
      imageH = (imageW*0.7);
    } else {
      imageH = h*0.7;
      imageW= imageH*1.333;
    }

    image.width=imageW;
    image.height=imageH;
    */
    image.width=w;
    image.height=h;

    if (counter >= pages-2) { counter = 0; }

  } // END too_soon

} // END listener_left

function listener_right () {

  if (too_soon==0) {
    game.time.events.add(Phaser.Timer.SECOND * 1.5, now_okay, this);
    too_soon=1;
    counter++;
    fx.stop(current_audio);
    fx.play(counter);
    current_audio = counter;
    text.text = caption[counter];
    page_no.text = counter+1;

    image.loadTexture(counter+1);
    image.anchor.setTo(0.5, 0);
    /*
    var imageW;
    var imageH;

    if (h>w) {
      imageW=w*0.8;
      imageH = (imageW*0.7);
    } else {
      imageH = h*0.7;
      imageW= imageH*1.333;
    }

    image.width=imageW;
    image.height=imageH;
    */
    image.width=w;
    image.height=h;
    if (counter >= pages-1) { counter = -1; }
  } // END Too Soon

} // END listener_right

function goto_start () {

  if (too_soon==0) {
    game.time.events.add(Phaser.Timer.SECOND * 1.5, now_okay, this);
    too_soon=1;
    counter=0;
    fx.stop(current_audio);
    fx.play(counter);
    current_audio = counter;
    text.text = caption[counter];
    page_no.text = counter+1;
    image.loadTexture(counter+1);
    image.anchor.setTo(0.5, 0);

      /*
    var imageW;
    var imageH;

    if (h>w) {
      imageW=w*0.8;
      imageH = (imageW*0.7);
    } else {
      imageH = h*0.7;
      imageW= imageH*1.333;
    }

    image.width=imageW;
    image.height=imageH;
    */
    image.width=w;
    image.height=h;

  } // END too_soon

} // END goto_start

// Add all the states
game.state.add('boot', bootState);
game.state.add('load', loadState);
game.state.add('play', playState);
// Start the 'boot' state
// game.state.start('boot');
<|endoftext|>


<commit_before>var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update });
var platform, player, cursor, stars, score, baddie, baddie_go_right, sfxStar, scoreText, sfxDeath, diamonds, sfxDiamond;

function preload() {
  game.load.image('sky', 'assets/sky.png');
  game.load.image('ground', 'assets/platform.png');
  game.load.image('star', 'assets/star.png');
  game.load.image('diamond', 'assets/diamond.png');
  game.load.spritesheet('dude', 'assets/dude.png', 32, 48);
  game.load.spritesheet('baddie', 'assets/baddie.png', 32, 32);
  game.load.audio('sfx:ping', 'assets/audio/p-ping.mp3');
  game.load.audio('sfx:death', 'assets/audio/death.wav');
  game.load.audio('sfx:diamond', 'assets/audio/diamond.wav');
}

function create() {
  // enable arcade Physics
  game.physics.startSystem(Phaser.Physics.ARCADE);

  // background
  game.add.sprite(0, 0, 'sky');

  //  Audio setup
  sfxStar = game.add.audio('sfx:ping');
  sfxStar.allowMultiple = true;
  sfxDeath = game.add.audio('sfx:death');
  sfxDeath.allowMultiple = true;
  sfxDiamond = game.add.audio('sfx:diamond');
  sfxDiamond.allowMultiple = true;

  // group the ground and plataforms to walk and jump
  platform = game.add.group();
  platform.enableBody = true;

  // ground
  var ground = platform.create(0, game.world.height - 64, 'ground');

  //scale to fit the canvas
  ground.scale.setTo(2, 2);
  // dont let the ground to fall
  ground.body.immovable = true;

  // platform
  var ledge = platform.create(400, 400, 'ground');
  ledge.body.immovable = true;
  // another platform
  ledge = platform.create(-150, 250, 'ground');
  ledge.body.immovable = true;
  game.add.sprite(0, 0, 'star');

  // player
  player = game.add.sprite(32, game.world.height - 150, 'dude');

  // enable pysics on the player
  game.physics.arcade.enable(player);

  //Player physics properties, body represents the body in physics
  player.body.bounce.y = 0.2;
  player.body.gravity.y = 300;
  player.body.collideWorldBounds = true;

  // animate the dude to walk left and right
  player.animations.add('left', [0, 1, 2, 3], 10, true);
  player.animations.add('right', [5, 6, 7, 8], 10, true);
  cursor = game.input.keyboard.createCursorKeys();

  // Stars
  stars = game.add.group();
  stars.enableBody = true;

  // create the stars
  for (var i = 0; i < 12; i++) {
    var star = stars.create(i * 70, 0, 'star');
    star.body.gravity.y = 300;
    star.body.bounce.y = 0.4 + Math.random() * 0.2;
    // add sound to each star object
    sfxStar.addMarker('star',0,1.5);
  }

  // create the diamonds
  diamonds = game.add.group();
  diamonds.enableBody = true;

  // create the diamonds
  for (var i = 0; i < 6; i++) {
    var diamond = diamonds.create(i * 120, 20, 'diamond');
    diamond.body.gravity.y = 200;
    diamond.body.bounce.y = 0.2 + Math.random() * 0.4;
    // add sound to each diamond object
    sfxDiamond.addMarker('diamond',0,1.5);
  }

  // baddie
  baddie = game.add.sprite(0, 0, 'baddie');
  game.physics.arcade.enable(baddie);
  baddie.body.bounce.y = 0.2;
  baddie.body.gravity.y = 300;
  baddie.body.collideWorldBounds = true;

  // animate the buddie
  baddie.animations.add('left', [0, 1], 10, true);
  baddie.animations.add('right', [2, 3], 10, true);

  // variable that says if baddie go riht or left
  baddie_go_right = true;

  // score
  score = 0;
  scoreText = game.add.text(16, 16, 'score: 0', {fontSize: '32px', fill: '#000'});

}

function update() {
  // Allows the player collide with the ground
  var hitPlatform = game.physics.arcade.collide(player, platform);
  game.physics.arcade.collide(baddie, platform);

  // reset the player velocity
  player.body.velocity.x = 0;

  // Move
  if(cursor.left.isDown){
    player.body.velocity.x = -150;
    player.animations.play('left');
  }else if(cursor.right.isDown){
    player.body.velocity.x = 150;
    player.animations.play('right');
  }else{
    player.animations.stop();
    player.frame = 4;
  }

  if (baddie_go_right) {
    baddie.body.velocity.x = 80;
    baddie.animations.play('right');
    if(baddie.x === game.world.width - 32){ // 32 is the width of the buddie
      baddie_go_right = false;
    }
  }else{
    baddie.body.velocity.x = -80;
    baddie.animations.play('left');
    if (baddie.x === 0) {
      baddie_go_right = true;
    }
  }

  // Jump
  if(cursor.up.isDown && player.body.touching.down && hitPlatform){
    player.body.velocity.y = -350;
  }

  // starts collition
  game.physics.arcade.collide(stars, platform);
  game.physics.arcade.overlap(player, stars, collectStar, null, this);

  // starts diamond
  game.physics.arcade.collide(diamonds, platform);
  game.physics.arcade.overlap(player, diamonds, collectDiamond, null, this);

  // baddie kills
  game.physics.arcade.overlap(player, baddie, killPlayer, null, this);
}

function collectStar(player, star){
  // add sound to start before kill it
  sfxStar.play('star');
  star.kill();
  score += 10;
  scoreText.text = 'Score: ' + score;
}

function collectDiamond(player, diamond){
  // add sound to diamond before kill it
  sfxDiamond.play('diamond');
  diamond.kill();
  score += 13;
  scoreText.text = 'Score: ' + score;
}

function killPlayer(player){
  sfxDeath.play();
  player.kill();
  scoreText.text = 'GAME OVER';
}
<commit_msg>add logic for the badie to follow the player and try to catch him<commit_after>var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update });
var platform, player, cursor, stars, score, baddie, baddie_go_right, sfxStar, scoreText, sfxDeath, diamonds, sfxDiamond;

function preload() {
  game.load.image('sky', 'assets/sky.png');
  game.load.image('ground', 'assets/platform.png');
  game.load.image('star', 'assets/star.png');
  game.load.image('diamond', 'assets/diamond.png');
  game.load.spritesheet('dude', 'assets/dude.png', 32, 48);
  game.load.spritesheet('baddie', 'assets/baddie.png', 32, 32);
  game.load.audio('sfx:ping', 'assets/audio/p-ping.mp3');
  game.load.audio('sfx:death', 'assets/audio/death.wav');
  game.load.audio('sfx:diamond', 'assets/audio/diamond.wav');
}

function create() {
  // enable arcade Physics
  game.physics.startSystem(Phaser.Physics.ARCADE);

  // background
  game.add.sprite(0, 0, 'sky');

  //  Audio setup
  sfxStar = game.add.audio('sfx:ping');
  sfxStar.allowMultiple = true;
  sfxDeath = game.add.audio('sfx:death');
  sfxDeath.allowMultiple = true;
  sfxDiamond = game.add.audio('sfx:diamond');
  sfxDiamond.allowMultiple = true;

  // group the ground and plataforms to walk and jump
  platform = game.add.group();
  platform.enableBody = true;

  // ground
  var ground = platform.create(0, game.world.height - 64, 'ground');

  //scale to fit the canvas
  ground.scale.setTo(2, 2);
  // dont let the ground to fall
  ground.body.immovable = true;

  // platform
  var ledge = platform.create(400, 400, 'ground');
  ledge.body.immovable = true;
  // another platform
  ledge = platform.create(-150, 250, 'ground');
  ledge.body.immovable = true;
  game.add.sprite(0, 0, 'star');

  // player
  player = game.add.sprite(32, game.world.height - 150, 'dude');

  // enable pysics on the player
  game.physics.arcade.enable(player);

  //Player physics properties, body represents the body in physics
  player.body.bounce.y = 0.2;
  player.body.gravity.y = 300;
  player.body.collideWorldBounds = true;

  // animate the dude to walk left and right
  player.animations.add('left', [0, 1, 2, 3], 10, true);
  player.animations.add('right', [5, 6, 7, 8], 10, true);
  cursor = game.input.keyboard.createCursorKeys();

  // Stars
  stars = game.add.group();
  stars.enableBody = true;

  // create the stars
  for (var i = 0; i < 12; i++) {
    var star = stars.create(i * 70, 0, 'star');
    star.body.gravity.y = 300;
    star.body.bounce.y = 0.4 + Math.random() * 0.2;
    // add sound to each star object
    sfxStar.addMarker('star',0,1.5);
  }

  // create the diamonds
  diamonds = game.add.group();
  diamonds.enableBody = true;

  // create the diamonds
  for (var i = 0; i < 6; i++) {
    var diamond = diamonds.create(i * 120, 20, 'diamond');
    diamond.body.gravity.y = 200;
    diamond.body.bounce.y = 0.2 + Math.random() * 0.4;
    // add sound to each diamond object
    sfxDiamond.addMarker('diamond',0,1.5);
  }

  // baddie
  baddie = game.add.sprite(0, 0, 'baddie');
  game.physics.arcade.enable(baddie);
  baddie.body.bounce.y = 0.2;
  baddie.body.gravity.y = 300;
  baddie.body.collideWorldBounds = true;

  // animate the buddie
  baddie.animations.add('left', [0, 1], 10, true);
  baddie.animations.add('right', [2, 3], 10, true);

  // variable that says if baddie go riht or left
  baddie_go_right = true;

  // score
  score = 0;
  scoreText = game.add.text(16, 16, 'score: 0', {fontSize: '32px', fill: '#000'});

}

function update() {
  // Allows the player collide with the ground
  var hitPlatform = game.physics.arcade.collide(player, platform);
  var hitPlatformBaddie = game.physics.arcade.collide(baddie, platform);
  game.physics.arcade.collide(baddie, platform);

  // reset the player velocity
  player.body.velocity.x = 0;

  // Move
  if(cursor.left.isDown){
    player.body.velocity.x = -150;
    player.animations.play('left');
  }else if(cursor.right.isDown){
    player.body.velocity.x = 150;
    player.animations.play('right');
  }else{
    player.animations.stop();
    player.frame = 4;
  }
  if(player.body.y+16 > baddie.body.y){
    if(baddie.x === game.world.width - 32){ // 32 is the width of the buddie
      baddie.body.velocity.x = -80;
      baddie.animations.play('left');
    }else if(baddie.x === 0){
      baddie.body.velocity.x = 80;
      baddie.animations.play('right');
    }
  }else if(player.body.y+16 < Math.floor(baddie.body.y) && baddie.body.touching.down && hitPlatformBaddie){
    console.log("player "+player.body.y);
    console.log("baddie "+baddie.body.y);
    baddie.body.velocity.y = -350;
  }else if (player.body.x > baddie.body.x) {
    baddie.body.velocity.x = 80;
    baddie.animations.play('right');

  }else if(player.body.x < baddie.body.x){
    baddie.body.velocity.x = -80;
    baddie.animations.play('left');
  }

  // Jump
  if(cursor.up.isDown && player.body.touching.down && hitPlatform){
    player.body.velocity.y = -350;
  }

  // starts collition
  game.physics.arcade.collide(stars, platform);
  game.physics.arcade.overlap(player, stars, collectStar, null, this);

  // starts diamond
  game.physics.arcade.collide(diamonds, platform);
  game.physics.arcade.overlap(player, diamonds, collectDiamond, null, this);

  // baddie kills
  game.physics.arcade.overlap(player, baddie, killPlayer, null, this);
}

function collectStar(player, star){
  // add sound to start before kill it
  sfxStar.play('star');
  star.kill();
  score += 10;
  scoreText.text = 'Score: ' + score;
}

function collectDiamond(player, diamond){
  // add sound to diamond before kill it
  sfxDiamond.play('diamond');
  diamond.kill();
  score += 13;
  scoreText.text = 'Score: ' + score;
}

function killPlayer(player){
  sfxDeath.play();
  player.kill();
  scoreText.text = 'GAME OVER';
}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

import Jed from "jed";
import locales from "./locales";

export function init(lang) {
    if (!lang) {
        lang = window.navigator.languages && window.navigator.languages.length ?
            window.navigator.languages[0] :
            (window.navigator.language || window.navigator.userLanguage || "en");
    }

    var langShort = lang.split(/[-_]/)[0];

    var localeData = locales[lang] || locales[langShort] || {};

    console.log(`User languages: ${lang}, ${langShort}. Using ${locales[lang] ? lang : locales[langShort] ? langShort : "en (default)"}`);

    return new Jed(localeData);
}
<commit_msg>Fix for variations in language tags<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

import Jed from "jed";
import locales from "./locales";

// Convert a language tag to a dash-separated lowercase string
function normalize(tag) {
    return tag.replace(/_/g, "-").toLowerCase();
}

export function init(lang) {
    if (!lang) {
        lang = window.navigator.languages && window.navigator.languages.length ?
            window.navigator.languages[0] :
            (window.navigator.language || window.navigator.userLanguage || "en");
    }

    // Normalize the given language tag and extract the language code alone
    lang = normalize(lang);
    var langShort = lang.split("-")[0];

    // Find the user language in the available locales
    var allLanguages = Object.keys(locales).map(normalize);
    var langIndex = allLanguages.indexOf(lang);
    if (langIndex < 0) {
        langIndex = allLanguages.indexOf(langShort);
    }

    var localeData = langIndex >= 0 ? locales[Object.keys(locales)[langIndex]] : {};

    return new Jed(localeData);
}
<|endoftext|>


<commit_before>(function($){
  $(function(){
    $('.carousel.carousel-slider').carousel({full_width: true});
 $('.collapsible').collapsible({
      accordion : false
    });
    $('.button-collapse').sideNav();
    $('.parallax').parallax();
$('.modal-trigger').leanModal();

  }); // end of document ready
})(jQuery); // end of jQuery name space
var audio = new Audio('z.mp3');
audio.play();
<commit_msg>Update init.js<commit_after>(function($){
  $(function(){
 $('.collapsible').collapsible({
      accordion : false
    });
    $('.button-collapse').sideNav();
    $('.parallax').parallax();
$('.modal-trigger').leanModal();
$('.carousel.carousel-slider').carousel({full_width: true});
  }); // end of document ready
})(jQuery); // end of jQuery name space
var audio = new Audio('z.mp3');
audio.play();
<|endoftext|>


<commit_before>var lbry = {
  isConnected: false,
  rootPath: '.',
  daemonConnectionString: 'http://localhost:5279/lbryapi',
  colors: {
    primary: '#155B4A'
  },
  defaultClientSettings: {
    showNsfw: false,
  }
};

lbry.jsonrpc_call = function (connectionString, method, params, callback, errorCallback, connectFailedCallback, timeout) {
  var xhr = new XMLHttpRequest;
  if (typeof connectFailedCallback !== 'undefined') {
    if (timeout) {
      xhr.timeout = timeout;
    }

    xhr.addEventListener('error', function (e) {
      connectFailedCallback(e);
    });
    xhr.addEventListener('timeout', function() {
      connectFailedCallback(new Error('XMLHttpRequest connection timed out'));
    })
  }
  xhr.addEventListener('load', function() {
    var response = JSON.parse(xhr.responseText);

    if (response.error) {
      if (errorCallback) {
        errorCallback(response.error);
      }
    } else if (callback) {
      callback(response.result);
    }
  });

  xhr.open('POST', connectionString, true);
  xhr.send(JSON.stringify({
    'jsonrpc': '2.0',
    'method': method,
    'params': params,
    'id': 0
  }));
}

lbry.call = function (method, params, callback, errorCallback, connectFailedCallback) {
  lbry.jsonrpc_call(lbry.daemonConnectionString, method, [params], callback, errorCallback, connectFailedCallback);
}

//core
lbry.connect = function(callback)
{
  // Check every half second to see if the daemon's running.
  // Returns true to callback once connected, or false if it takes too long and we give up.
  function checkDaemonRunning(tryNum=0) {
    lbry.daemonRunningStatus(function (runningStatus) {
      if (runningStatus) {
        lbry.isConnected = true;
        callback(true);
      } else {
        if (tryNum <= 600) { // Move # of tries into constant or config option
          setTimeout(function () {
            checkDaemonRunning(tryNum + 1);
          }, 500);
        } else {
          callback(false);
        }
      }
    });
  }
  checkDaemonRunning();
}

lbry.daemonRunningStatus = function (callback) {
  // Returns true/false whether the daemon is running (i.e. fully conncected to the network),
  // or null if the AJAX connection to the daemon fails.

  lbry.call('is_running', {}, callback, null, function () {
    callback(null);
  });
};

lbry.getDaemonStatus = function (callback) {
  lbry.call('daemon_status', {}, callback);
};

lbry.getStartNotice = function(callback) {
  lbry.call('get_start_notice', {}, callback);
}

lbry.checkFirstRun = function(callback) {
  lbry.call('is_first_run', {}, callback);
}

lbry.getNewAddress = function(callback) {
  lbry.call('get_new_address', {}, callback);
}

lbry.checkAddressIsMine = function(address, callback) {
  lbry.call('address_is_mine', {address: address}, callback);
}

lbry.getDaemonSettings = function(callback) {
  lbry.call('get_settings', {}, callback);
}

lbry.setDaemonSettings = function(settings, callback) {
  lbry.call('set_settings', settings, callback);
}

lbry.setDaemonSetting = function(setting, value, callback) {
  var setSettingsArgs = {};
  setSettingsArgs[setting] = value;
  lbry.call('set_settings', setSettingsArgs, callback)
}

lbry.getBalance = function(callback)
{
  lbry.call("get_balance", {}, callback);
}

lbry.sendToAddress = function(amount, address, callback, errorCallback)
{
  lbry.call("send_amount_to_address", { "amount" : amount, "address": address }, callback, errorCallback);
}

lbry.resolveName = function(name, callback) {
  lbry.call('resolve_name', { 'name': name }, callback, () => {
    // For now, assume any error means the name was not resolved
    callback(null);
  });
}

lbry.getStream = function(name, callback) {
  lbry.call('get', { 'name': name }, callback);
};

lbry.getClaimInfo = function(name, callback) {
  lbry.call('get_claim_info', { name: name }, callback);
}

lbry.getMyClaim = function(name, callback) {
  lbry.call('get_my_claim', { name: name }, callback);
}

lbry.getCostEstimate = function(name, callback) {
  lbry.call('get_est_cost', { name: name }, callback);
}

lbry.getFileStatus = function(name, callback) {
  lbry.call('get_lbry_file', { 'name': name }, callback);
}

lbry.getFilesInfo = function(callback) {
  lbry.call('get_lbry_files', {}, callback);
}

lbry.startFile = function(name, callback) {
  lbry.call('start_lbry_file', { name: name }, callback);
}

lbry.stopFile = function(name, callback) {
  lbry.call('stop_lbry_file', { name: name }, callback);
}

lbry.deleteFile = function(name, deleteTargetFile=true, callback) {
  lbry.call('delete_lbry_file', {
    name: name,
    delete_target_file: deleteTargetFile,
  }, callback);
}

lbry.revealFile = function(path, callback) {
  lbry.call('reveal', { path: path }, callback);
}

lbry.getFileInfoWhenListed = function(name, callback, timeoutCallback, tryNum=0) {
  // Calls callback with file info when it appears in the list of files returned by lbry.getFilesInfo().
  // If timeoutCallback is provided, it will be called if the file fails to appear.
  lbry.getFilesInfo(function(filesInfo) {
    for (var fileInfo of filesInfo) {
      if (fileInfo.lbry_uri == name) {
        callback(fileInfo);
        return;
      }
    }

    if (tryNum <= 200) {
      setTimeout(function() { lbry.getFileInfoWhenListed(name, callback, timeoutCallback, tryNum + 1) }, 250);
    } else if (timeoutCallback) {
      timeoutCallback();
    }
  });
}

lbry.publish = function(params, fileListedCallback, publishedCallback, errorCallback) {
  // Publishes a file.
  // The optional fileListedCallback is called when the file becomes available in
  // lbry.getFilesInfo() during the publish process.

  // Use ES6 named arguments instead of directly passing param dict?
  lbry.call('publish', params, publishedCallback, (errorInfo) => {
    errorCallback({
      name: fault.fault,
      message: fault.faultString,
    });
  });
  if (fileListedCallback) {
    lbry.getFileInfoWhenListed(params.name, function(fileInfo) {
      fileListedCallback(fileInfo);
    });
  }
}

lbry.getVersionInfo = function(callback) {
  lbry.call('version', {}, callback);
};

lbry.checkNewVersionAvailable = function(callback) {
  lbry.call('version', {}, function(versionInfo) {
    var ver = versionInfo.lbrynet_version.split('.');

    var maj = parseInt(ver[0]),
        min = parseInt(ver[1]),
        patch = parseInt(ver[2]);

    var remoteVer = versionInfo.remote_lbrynet.split('.');
    var remoteMaj = parseInt(remoteVer[0]),
        remoteMin = parseInt(remoteVer[1]),
        remotePatch = parseInt(remoteVer[2]);

    if (maj < remoteMaj) {
      var newVersionAvailable = true;
    } else if (maj == remoteMaj) {
      if (min < remoteMin) {
        var newVersionAvailable = true;
      } else if (min == remoteMin) {
        var newVersionAvailable = (patch < remotePatch);
      } else {
        var newVersionAvailable = false;
      }
    } else {
      var newVersionAvailable = false;
    }
    callback(newVersionAvailable);
  }, function(err) {
    if (err.fault == 'NoSuchFunction') {
      // Really old daemon that can't report a version
      callback(true);
    }
  });
}

lbry.getClientSettings = function() {
  var outSettings = {};
  for (let setting of Object.keys(lbry.defaultClientSettings)) {
    var localStorageVal = localStorage.getItem('setting_' + setting);
    outSettings[setting] = (localStorageVal === null ? lbry.defaultClientSettings[setting] : JSON.parse(localStorageVal));
  }
  return outSettings;
}

lbry.getClientSetting = function(setting) {
  var localStorageVal = localStorage.getItem('setting_' + setting);
  return (localStorageVal === null ? lbry.defaultClientSettings[setting] : JSON.parse(localStorageVal));
}

lbry.setClientSettings = function(settings) {
  for (let setting of Object.keys(settings)) {
    lbry.setClientSetting(setting, settings[setting]);
  }
}

lbry.setClientSetting = function(setting, value) {
  return localStorage.setItem('setting_' + setting, JSON.stringify(value));
}

lbry.reportBug = function(message, callback) {
  lbry.call('upload_log', {
    name_prefix: 'report',
    exclude_previous: false,
    force: true,
    message: message
  }, callback);
}

//utilities
lbry.formatCredits = function(amount, precision)
{
  return amount.toFixed(precision || 1).replace(/\.?0+$/, '');
}

lbry.formatName = function(name) {
  // Converts LBRY name to standard format (all lower case, no special characters, spaces replaced by dashes)
  name = name.replace(" ", "-");
  name = name.toLowerCase().replace(/[^a-z0-9\-]/g, '');
  return name;
}

lbry.loadJs = function(src, type, onload)
{
  var lbryScriptTag = document.getElementById('lbry'),
      newScriptTag = document.createElement('script'),
      type = type || 'text/javascript';

  newScriptTag.src = src;
  newScriptTag.type = type;
  if (onload)
  {
    newScript.onload = onload;
  }
  lbryScriptTag.parentNode.insertBefore(newScriptTag, lbryScriptTag);
}

lbry.imagePath = function(file)
{
  return lbry.rootPath + '/img/' + file;
}

lbry.getMediaType = function(contentType, fileName) {
  if (contentType) {
    return /^[^/]+/.exec(contentType);
  } else if (fileName) {
    var dotIndex = fileName.lastIndexOf('.');
    if (dotIndex == -1) {
      return 'unknown';
    }

    var ext = fileName.substr(dotIndex + 1);
    if (/^mp4|mov|m4v|flv|f4v$/i.test(ext)) {
      return 'video';
    } else if (/^mp3|m4a|aac|wav|flac|ogg$/i.test(ext)) {
      return 'audio';
    } else if (/^html|htm|pdf|odf|doc|docx|md|markdown|txt$/i.test(ext)) {
      return 'document';
    } else {
      return 'unknown';
    }
  } else {
    return 'unknown';
  }
}

lbry.stop = function(callback) {
  lbry.call('stop', {}, callback);
};

<commit_msg>formatName now using different text sanitation method<commit_after>var lbry = {
  isConnected: false,
  rootPath: '.',
  daemonConnectionString: 'http://localhost:5279/lbryapi',
  colors: {
    primary: '#155B4A'
  },
  defaultClientSettings: {
    showNsfw: false,
  }
};

lbry.jsonrpc_call = function (connectionString, method, params, callback, errorCallback, connectFailedCallback, timeout) {
  var xhr = new XMLHttpRequest;
  if (typeof connectFailedCallback !== 'undefined') {
    if (timeout) {
      xhr.timeout = timeout;
    }

    xhr.addEventListener('error', function (e) {
      connectFailedCallback(e);
    });
    xhr.addEventListener('timeout', function() {
      connectFailedCallback(new Error('XMLHttpRequest connection timed out'));
    })
  }
  xhr.addEventListener('load', function() {
    var response = JSON.parse(xhr.responseText);

    if (response.error) {
      if (errorCallback) {
        errorCallback(response.error);
      }
    } else if (callback) {
      callback(response.result);
    }
  });

  xhr.open('POST', connectionString, true);
  xhr.send(JSON.stringify({
    'jsonrpc': '2.0',
    'method': method,
    'params': params,
    'id': 0
  }));
}

lbry.call = function (method, params, callback, errorCallback, connectFailedCallback) {
  lbry.jsonrpc_call(lbry.daemonConnectionString, method, [params], callback, errorCallback, connectFailedCallback);
}

//core
lbry.connect = function(callback)
{
  // Check every half second to see if the daemon's running.
  // Returns true to callback once connected, or false if it takes too long and we give up.
  function checkDaemonRunning(tryNum=0) {
    lbry.daemonRunningStatus(function (runningStatus) {
      if (runningStatus) {
        lbry.isConnected = true;
        callback(true);
      } else {
        if (tryNum <= 600) { // Move # of tries into constant or config option
          setTimeout(function () {
            checkDaemonRunning(tryNum + 1);
          }, 500);
        } else {
          callback(false);
        }
      }
    });
  }
  checkDaemonRunning();
}

lbry.daemonRunningStatus = function (callback) {
  // Returns true/false whether the daemon is running (i.e. fully conncected to the network),
  // or null if the AJAX connection to the daemon fails.

  lbry.call('is_running', {}, callback, null, function () {
    callback(null);
  });
};

lbry.getDaemonStatus = function (callback) {
  lbry.call('daemon_status', {}, callback);
};

lbry.getStartNotice = function(callback) {
  lbry.call('get_start_notice', {}, callback);
}

lbry.checkFirstRun = function(callback) {
  lbry.call('is_first_run', {}, callback);
}

lbry.getNewAddress = function(callback) {
  lbry.call('get_new_address', {}, callback);
}

lbry.checkAddressIsMine = function(address, callback) {
  lbry.call('address_is_mine', {address: address}, callback);
}

lbry.getDaemonSettings = function(callback) {
  lbry.call('get_settings', {}, callback);
}

lbry.setDaemonSettings = function(settings, callback) {
  lbry.call('set_settings', settings, callback);
}

lbry.setDaemonSetting = function(setting, value, callback) {
  var setSettingsArgs = {};
  setSettingsArgs[setting] = value;
  lbry.call('set_settings', setSettingsArgs, callback)
}

lbry.getBalance = function(callback)
{
  lbry.call("get_balance", {}, callback);
}

lbry.sendToAddress = function(amount, address, callback, errorCallback)
{
  lbry.call("send_amount_to_address", { "amount" : amount, "address": address }, callback, errorCallback);
}

lbry.resolveName = function(name, callback) {
  lbry.call('resolve_name', { 'name': name }, callback, () => {
    // For now, assume any error means the name was not resolved
    callback(null);
  });
}

lbry.getStream = function(name, callback) {
  lbry.call('get', { 'name': name }, callback);
};

lbry.getClaimInfo = function(name, callback) {
  lbry.call('get_claim_info', { name: name }, callback);
}

lbry.getMyClaim = function(name, callback) {
  lbry.call('get_my_claim', { name: name }, callback);
}

lbry.getCostEstimate = function(name, callback) {
  lbry.call('get_est_cost', { name: name }, callback);
}

lbry.getFileStatus = function(name, callback) {
  lbry.call('get_lbry_file', { 'name': name }, callback);
}

lbry.getFilesInfo = function(callback) {
  lbry.call('get_lbry_files', {}, callback);
}

lbry.startFile = function(name, callback) {
  lbry.call('start_lbry_file', { name: name }, callback);
}

lbry.stopFile = function(name, callback) {
  lbry.call('stop_lbry_file', { name: name }, callback);
}

lbry.deleteFile = function(name, deleteTargetFile=true, callback) {
  lbry.call('delete_lbry_file', {
    name: name,
    delete_target_file: deleteTargetFile,
  }, callback);
}

lbry.revealFile = function(path, callback) {
  lbry.call('reveal', { path: path }, callback);
}

lbry.getFileInfoWhenListed = function(name, callback, timeoutCallback, tryNum=0) {
  // Calls callback with file info when it appears in the list of files returned by lbry.getFilesInfo().
  // If timeoutCallback is provided, it will be called if the file fails to appear.
  lbry.getFilesInfo(function(filesInfo) {
    for (var fileInfo of filesInfo) {
      if (fileInfo.lbry_uri == name) {
        callback(fileInfo);
        return;
      }
    }

    if (tryNum <= 200) {
      setTimeout(function() { lbry.getFileInfoWhenListed(name, callback, timeoutCallback, tryNum + 1) }, 250);
    } else if (timeoutCallback) {
      timeoutCallback();
    }
  });
}

lbry.publish = function(params, fileListedCallback, publishedCallback, errorCallback) {
  // Publishes a file.
  // The optional fileListedCallback is called when the file becomes available in
  // lbry.getFilesInfo() during the publish process.

  // Use ES6 named arguments instead of directly passing param dict?
  lbry.call('publish', params, publishedCallback, (errorInfo) => {
    errorCallback({
      name: fault.fault,
      message: fault.faultString,
    });
  });
  if (fileListedCallback) {
    lbry.getFileInfoWhenListed(params.name, function(fileInfo) {
      fileListedCallback(fileInfo);
    });
  }
}

lbry.getVersionInfo = function(callback) {
  lbry.call('version', {}, callback);
};

lbry.checkNewVersionAvailable = function(callback) {
  lbry.call('version', {}, function(versionInfo) {
    var ver = versionInfo.lbrynet_version.split('.');

    var maj = parseInt(ver[0]),
        min = parseInt(ver[1]),
        patch = parseInt(ver[2]);

    var remoteVer = versionInfo.remote_lbrynet.split('.');
    var remoteMaj = parseInt(remoteVer[0]),
        remoteMin = parseInt(remoteVer[1]),
        remotePatch = parseInt(remoteVer[2]);

    if (maj < remoteMaj) {
      var newVersionAvailable = true;
    } else if (maj == remoteMaj) {
      if (min < remoteMin) {
        var newVersionAvailable = true;
      } else if (min == remoteMin) {
        var newVersionAvailable = (patch < remotePatch);
      } else {
        var newVersionAvailable = false;
      }
    } else {
      var newVersionAvailable = false;
    }
    callback(newVersionAvailable);
  }, function(err) {
    if (err.fault == 'NoSuchFunction') {
      // Really old daemon that can't report a version
      callback(true);
    }
  });
}

lbry.getClientSettings = function() {
  var outSettings = {};
  for (let setting of Object.keys(lbry.defaultClientSettings)) {
    var localStorageVal = localStorage.getItem('setting_' + setting);
    outSettings[setting] = (localStorageVal === null ? lbry.defaultClientSettings[setting] : JSON.parse(localStorageVal));
  }
  return outSettings;
}

lbry.getClientSetting = function(setting) {
  var localStorageVal = localStorage.getItem('setting_' + setting);
  return (localStorageVal === null ? lbry.defaultClientSettings[setting] : JSON.parse(localStorageVal));
}

lbry.setClientSettings = function(settings) {
  for (let setting of Object.keys(settings)) {
    lbry.setClientSetting(setting, settings[setting]);
  }
}

lbry.setClientSetting = function(setting, value) {
  return localStorage.setItem('setting_' + setting, JSON.stringify(value));
}

lbry.reportBug = function(message, callback) {
  lbry.call('upload_log', {
    name_prefix: 'report',
    exclude_previous: false,
    force: true,
    message: message
  }, callback);
}

//utilities
lbry.formatCredits = function(amount, precision)
{
  return amount.toFixed(precision || 1).replace(/\.?0+$/, '');
}

lbry.formatName = function(name) {
  // Converts LBRY name to standard format (all lower case, no special characters, spaces replaced by dashes)
  name = name.replace('/\s+/g', '-');
  name = name.toLowerCase().replace(/[^a-z0-9\-]/g, '');
  return name;
}

lbry.loadJs = function(src, type, onload)
{
  var lbryScriptTag = document.getElementById('lbry'),
      newScriptTag = document.createElement('script'),
      type = type || 'text/javascript';

  newScriptTag.src = src;
  newScriptTag.type = type;
  if (onload)
  {
    newScript.onload = onload;
  }
  lbryScriptTag.parentNode.insertBefore(newScriptTag, lbryScriptTag);
}

lbry.imagePath = function(file)
{
  return lbry.rootPath + '/img/' + file;
}

lbry.getMediaType = function(contentType, fileName) {
  if (contentType) {
    return /^[^/]+/.exec(contentType);
  } else if (fileName) {
    var dotIndex = fileName.lastIndexOf('.');
    if (dotIndex == -1) {
      return 'unknown';
    }

    var ext = fileName.substr(dotIndex + 1);
    if (/^mp4|mov|m4v|flv|f4v$/i.test(ext)) {
      return 'video';
    } else if (/^mp3|m4a|aac|wav|flac|ogg$/i.test(ext)) {
      return 'audio';
    } else if (/^html|htm|pdf|odf|doc|docx|md|markdown|txt$/i.test(ext)) {
      return 'document';
    } else {
      return 'unknown';
    }
  } else {
    return 'unknown';
  }
}

lbry.stop = function(callback) {
  lbry.call('stop', {}, callback);
};

<|endoftext|>