<commit_before>// miner ver01
//Thanks to Giulia Alfonsi <electric.g@gmail.com>
//for providing the stopwatch timer JS (stopwatch.js)
// James & Matt of WDI Purple-Rain for some troubleshooting!

$(document).ready(function(){

// define some items on the DOM using Jquery
var $button = $('.start-pass');
var $button2 = $('.guess').hide();
var $button3 = $('.pass').hide();
var $input = $('input').hide();
var $rebus = $('img');
var $h1 = $('h1');
var $time = $('#time').hide();
var answer = '';
var location = '';
var P1totalTime = 0
var P2totalTime = 0
var play2
var play1
var p1Score = 0
var p2Score = 0
var guesses = 0
var pass
// player turns
var roundNo = 0
var pointAward =0
//two arrays for images & answers, need to not repeat used items

var usedImages =[ ]
var rebusArray =
 [
          {
          answer:"changing times",
          location: "img/01.jpg"
          },
          {
          answer:"not for all the tea in china",
          location: "img/02.jpg"
          },
           {
          answer:"it doesn't ring a bell",
          location: "img/03.jpg"
          },
           {
          answer:"richard nixon",
          location: "img/04.jpg"
          },
           {
          answer:"take it or leave it",
          location: "img/06.jpg"
          },
];

//length of the array in a varaible
var RebusL = rebusArray.length

var playerScore = function (){

  if ( play2 === 'Player 2') {
        P2totalTime += (m * 60 + s)
        if (P2totalTime < 5) {

          p2Score += 1000
        } else if (P2totalTime < 10 ) {
          p2Score += 500
        } else if (P2totalTime < 20 ) {
          p2Score += 100
        } else {
          P2totalTime += 10
        }

    } else {
        P1totalTime += (m * 60 + s)

if (P1totalTime < 5) {

          p1Score += 1000
        } else if (P2totalTime < 10 ) {
          p1Score += 500
        } else if (P2totalTime < 20 ) {
          p1Score += 100
        } else {
          p1Score += 10
        }

    }
}
// match'em or else
var compareGuess = function(){
  var guess = $('#guess').val();
  // console.log(randomRedbus.answer);
  if (guess === answer) {
    stop();
    $time.fadeTo('1000', 1);
    $button.text('Next Round / P2');
    $button2.hide();
    playerScore();

    // var totalTime =   (m *60) + s

    $input.hide();

  } else if (guesses === 3) {

    stop()
    $time.fadeTo('1000', 1);
    $button.text('Next Round / P2')
    $button2.hide();
    $input.hide();
    $h1.html(answer);
    playerScore();
   // trying to add slicer here
  // splicer();

    // randomRebus.splice(push(usedImages), 1)[0];
    }
    console.log('you guessed wrong')
    guesses++
    $('#wrong').text(guesses)
}

// checks (even /odd) goes to next round, updates player no.
var turner = function() {
  roundNo++;
  if (roundNo > RebusL) {
    winState()
    } else if (roundNo %2 === 0) {
        playerState = 'p1'
        play2 = ('Player 2');
        $h1.text(play2)
        reset();
        start();
        $input.show();
        guesses=0;
        // var P1totalTime += (m *60) + s
      } else {
        play1 = ('Player 1');
        playerState = 'p2'
        $h1.text(play1)
          reset();
          start();
          $input.show();
          guesses=0;

      }
     $('#wrong').text(guesses)
}

//random number function
var randomNo = function () {

  return Math.floor(Math.random()*RebusL)
  }

// var randomRebus = RebusArray[randomNo()];

//button one click  (PASS & Start)

$button.click(function(){

  var randomRebus = rebusArray[randomNo()];
  $button.text('PASS');
  $button2.show();
  $input.show();
  $time.fadeTo('1000', 0.2);
  turner();
  start();

$rebus.attr("src", randomRebus.location);
// answer values stored in variable, avoids confusion on repeatedly calling function
  answer = randomRebus.answer;
  location = randomRebus.location;
  itemPlace = rebusArray.indexOf(randomRebus);

});

// pointscheme

// var awardPoints = function () {

// switch (totalTime) {
//     case totalTime < 10:
//       pointAward += 100;
//       break;
//     case totalTime < 20:
//       pointAward += 50;
//       break;
//     default:
//       pointAward += 0;
//       }

// }

var winState = function(){

   stop()
    $time.hide();
    $button.hide()
    $button2.hide();
    $input.hide();
    $rebus = $('img').hide();
    console.log(P1totalTime)
    console.log(P2totalTime)
    if ( p1Score > p2Score ) {

      $h1.html('Player 1 Wins' + '
 ' + p1Score + '
 p2 score
  ' + p2Score  );
    } else {

       $h1.html('Player 2 Wins'+ '
 ' + p2Score + '
 p1 Score:
  ' +  p1Score  );
    }

}

// how to get rid of selected images?? splicer so image

// function splicer(){
//   // var k = rebusArray.indexOf(randomRebus);
//     if(itemPlace != -1)
//     // rebusArray.delete(itemPlace, 1);
//     console.log(itemPlace)
//       console.log(itemPlace)
//         console.log(itemPlace)
//         rebusArray.splice(itemPlace);

//   }

$button3.click(function(){
$button3.hide();
$button2.hide();
pass = 'skipped'
$button.show();

 // stop();
 //    $time.fadeTo('1000', 1);
 //    $button.text('Next Round / P2');

 //    playerScore();

});

$button2.click(function(){

compareGuess();
});
show()

});
<commit_msg>Update script.js<commit_after>// miner ver01
//Thanks to Giulia Alfonsi <electric.g@gmail.com>
//for providing the stopwatch timer JS (stopwatch.js)
// James & Matt of WDI Purple-Rain for some troubleshooting!

$(document).ready(function(){

// define some items on the DOM using Jquery
var $button = $('.start-pass');
var $button2 = $('.guess').hide();
var $button3 = $('.pass').hide();
var $input = $('input').hide();
var $rebus = $('img');
var $h1 = $('h1');
var $time = $('#time').hide();
var answer = '';
var location = '';
var P1totalTime = 0
var P2totalTime = 0
var play2
var play1
var p1Score = 0
var p2Score = 0
var guesses = 0
var pass
// player turns
var roundNo = 0
var pointAward =0
//two arrays for images & answers, need to not repeat used items

var usedImages =[ ]
var rebusArray =
 [
          {
          answer:"changing times",
          location: "img/01.jpg"
          },
          {
          answer:"not for all the tea in china",
          location: "img/02.jpg"
          },
           {
          answer:"it doesn't ring a bell",
          location: "img/03.jpg"
          },
           {
          answer:"richard nixon",
          location: "img/04.jpg"
          },
           {
          answer:"take it or leave it",
          location: "img/06.jpg"
          },
];

//length of the array in a varaible
var RebusL = rebusArray.length

var playerScore = function (){

  if ( play2 === 'Player 2') {
        P2totalTime += (m * 60 + s)
        if (P2totalTime < 5) {

          p2Score += 1000
        } else if (P2totalTime < 10 ) {
          p2Score += 500
        } else if (P2totalTime < 20 ) {
          p2Score += 100
        } else {
          P2totalTime += 10
        }

    } else {
        P1totalTime += (m * 60 + s)

if (P1totalTime < 5) {

          p1Score += 1000
        } else if (P2totalTime < 10 ) {
          p1Score += 500
        } else if (P2totalTime < 20 ) {
          p1Score += 100
        } else {
          p1Score += 10
        }

    }
}
// match'em or else
var compareGuess = function(){
  var guess = $('#guess').val();
  // console.log(randomRedbus.answer);
  if (guess === answer) {
    stop();
    $time.fadeTo('1000', 1);
    $button.text('Next Round / P2');
    $button2.hide();
    playerScore();

    // var totalTime =   (m *60) + s

    $input.hide();

  } else if (guesses === 3) {

    stop()
    $time.fadeTo('1000', 1);
    $button.text('Next Round / P2')
    $button2.hide();
    $input.hide();
    $h1.html(answer);
    playerScore();
   // trying to add slicer here
  // splicer();

    // randomRebus.splice(push(usedImages), 1)[0];
    }
    console.log('you guessed wrong')
    guesses++
    $('#wrong').text(guesses)
}

// checks (even /odd) goes to next round, updates player no.
var turner = function() {
  roundNo++;
  if (roundNo > RebusL) {
    winState()
    } else if (roundNo %2 === 0) {
        playerState = 'p1'
        play2 = ('Player 2');
        $h1.text(play2)
        reset();
        start();
        $input.show();
        guesses=0;
        // var P1totalTime += (m *60) + s
      } else {
        play1 = ('Player 1');
        playerState = 'p2'
        $h1.text(play1)
          reset();
          start();
          $input.show();
          guesses=0;

      }
     $('#wrong').text(guesses)
}

//random number function
var randomNo = function () {

  return Math.floor(Math.random()*RebusL)
  }

// var randomRebus = RebusArray[randomNo()];

//button one click  (PASS & Start)

$button.click(function(){

  var randomRebus = rebusArray[randomNo()];
  $button.text('PASS');
  $button2.show();
  $input.show();
  $time.fadeTo('1000', 0.2);
  turner();
  start();

$rebus.attr("src", randomRebus.location);
// answer values stored in variable, avoids confusion on repeatedly calling function
  answer = randomRebus.answer;
  location = randomRebus.location;
  itemPlace = rebusArray.indexOf(randomRebus);

});

// pointscheme

// var awardPoints = function () {

// switch (totalTime) {
//     case totalTime < 10:
//       pointAward += 100;
//       break;
//     case totalTime < 20:
//       pointAward += 50;
//       break;
//     default:
//       pointAward += 0;
//       }

// }

var winState = function(){

   stop()
    $time.hide();
    $button.hide()
    $button2.hide();
    $input.hide();
    $rebus = $('img').hide();
    console.log(P1totalTime)
    console.log(P2totalTime)
    if ( p1Score > p2Score ) {

      $h1.html('Player 1 Wins w score of' + ' ' + p1Score + '
 p2 score
  ' + p2Score  );
    } else {

       $h1.html('Player 2 Wins w score of '+ '  ' + p2Score + '
 p1 Score:
  ' +  p1Score  );
    }

}

// how to get rid of selected images?? splicer so image

// function splicer(){
//   // var k = rebusArray.indexOf(randomRebus);
//     if(itemPlace != -1)
//     // rebusArray.delete(itemPlace, 1);
//     console.log(itemPlace)
//       console.log(itemPlace)
//         console.log(itemPlace)
//         rebusArray.splice(itemPlace);

//   }

$button3.click(function(){
$button3.hide();
$button2.hide();
pass = 'skipped'
$button.show();

 // stop();
 //    $time.fadeTo('1000', 1);
 //    $button.text('Next Round / P2');

 //    playerScore();

});

$button2.click(function(){

compareGuess();
});
show()

});
<|endoftext|>


<commit_before>var GameState = function (game) {
};

//load assets
GameState.prototype.preload = function(){

    this.game.load.image('map', 'assets/map.png'); // thjs is the background
    this.game.load.image('ground', 'assets/block.png');//this is the ground
    this.game.load.image('block', 'assets/pixel_1.png');//this is the image for the platforms, the block argument in the create function below links the sprite to the platform
    this.game.load.spritesheet('player', 'assets/dude.png', 32, 48);
    this.game.load.image('cat', 'assets/cat.png');

};

GameState.prototype.create = function () {
    //this.game.add.sprite(0,0, 'map');

    //movement:
    this.MAX_SPEED = 500; //px/s
    this.ACCELERATION = 1500; //px/s/s
    this.DRAG = 900; //px/s
    this.GRAVITY = 2600;
    this.JUMP_SPEED = -1000;
    //create player
    this.player = this.game.add.sprite(this.game.width/2, this.game.height - 90, 'player');
    this.player.anchor.set(0.5);

    this.player.yOrig = this.player.y;
    this.player.yChange = 0;

    //add player movement animations;
    this.player.animations.add('left', [0,1,2,3], 10, true);
    this.player.animations.add('right', [5,6,7,8], 10, true);

    //physics
    this.game.physics.enable(this.player, Phaser.Physics.ARCADE);
    //make player collide with the boundaries of the game
    this.player.body.collideWorldBounds = true;
    this.player.body.maxVelocity.setTo(this.MAX_SPEED, this.MAX_SPEED * 10);
    this.player.body.drag.setTo(this.DRAG,0);

    this.player.body.gravity.y = this.GRAVITY;
    this.player.body.checkCollision.up = false;
    //this.player.body.checkCollision.left = false;
    //this.player.body.checkCollision.right = false;

    //create floor
    this.ground = this.game.add.group();
    for(var x = 0; x < this.game.width; x += 32) {
        // Add the ground blocks, enable physics on each, make them immovable
        var groundBlock = this.game.add.sprite(x, this.game.height - 32, 'ground');
        this.game.physics.enable(groundBlock, Phaser.Physics.ARCADE);
        groundBlock.body.immovable = true;
        groundBlock.body.allowGravity = false;
        this.ground.add(groundBlock);
    }

    //console.log("this is the players y pos" + this.player.y);
    //create platforms
    this.platformsCreate();

    //controls:
    this.game.input.keyboard.addKeyCapture([
        Phaser.Keyboard.LEFT,
        Phaser.Keyboard.RIGHT,
        Phaser.Keyboard.UP,
        Phaser.Keyboard.DOWN
    ]);

    //scaling
    this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
    this.scale.maxWidth = this.game.width;
    this.scale.maxHeight = this.game.height;
    this.scale.pageAlignHorizontally = true;
    this.scale.pageAlignVertically = true;
    this.scale.setScreenSize( true );

    //camera
    this.cameraYMin = 99999;
    this.platformYMin = 99999;

    //trigger the counter which destroys the floor
    this.destructionCounter();

    //initialize Platformcounter
    this.platformCounter = 0;

};

    /****************************************************************************************************************/
    /*                      Player related settings and controls                                                                  /
    /************************************************************************************************************** */

 GameState.prototype.update = function() {
     //collission checking
     this.physics.arcade.collide(this.player, this.ground);
     this.physics.arcade.collide(this.player, this.platforms);

     this.platforms.forEachAlive(function(platform){
         platform.body.y += 1;
     });

     //controls
     if (this.leftInputIsActive()) {
         this.player.body.acceleration.x = -this.ACCELERATION;
         this.player.animations.play('left');
     } else if (this.rightInputIsActive()) {
         this.player.body.acceleration.x = this.ACCELERATION;
         this.player.animations.play('right');
     } else {
         this.player.body.acceleration.x = 0;
         this.player.animations.stop();
         //we need to do this to display the static position when standing
         this.player.frame = 4;
     }

     //check whether the player is on the ground
     var onTheGround = this.player.body.touching.down;
     if (onTheGround && this.upInputIsActive()){
         this.player.body.velocity.y = this.JUMP_SPEED;
     }

     this.world.setBounds(0, -this.player.yChange, this.world.width, this.game.height + this.player.yChange);

     this.platforms.forEachAlive(function (elem) {
         this.platformYMin = Math.min(this.platformYMin, elem.y);
         if (elem.y > this.camera.y + this.game.height) {
             elem.kill();
             this.score();
         }
     }, this);

     //make player die on ground contact
     this.die();
 };

GameState.prototype.score = function(){
    this.platformCounter ++;
    console.log(this.platformCounter);
    this.game.debug.text(this.platformCounter, 20, 20);
};

GameState.prototype.platformsCreate = function(){
         //FUCK EVERYTHING
         this.platforms = this.add.group();
         this.platforms.enableBody = true;

         //determine the number of platforms you want to create (the wide ones)
         var numberofPlatforms = 1000;
         this.platforms.createMultiple( numberofPlatforms, 'block' );

         // create a batch of platforms that start to move up the level
         for( var i = 0; i < numberofPlatforms; i++ ) {
             //modify the last parameter in this line to change the width of the platforms
             this.platformsCreateOne( this.rnd.integerInRange( 0, this.world.width - 45 ), this.world.height - 100 - 100 * i, 160 );
         }
     };

GameState.prototype.platformsCreateOne = function( x, y, width) {
    // this is a helper function since writing all of this out can get verbose elsewhere
    var platform = this.platforms.getFirstDead();

         //should this turn out to be backstabby later on, simply remove the if statement and only write the codeblock
         //but this is textbook-like error handling....probably a little shady

         if(platform) {
             platform.reset(x, y);
             platform.scale.x = width;
             platform.scale.y = 16;
             platform.body.immovable = true;
             return platform;
         }
     };

GameState.prototype.destructionCounter = function(){
    //this sets a timer that calls the floor destruction method after a while
    game.time.events.add(Phaser.Timer.SECOND * 10, this.destroyFloor, this);
};

GameState.prototype.destroyFloor = function () {
    //this destroys the floor
    this.ground.destroy();
};

GameState.prototype.die = function () {
    //make the player die
    if(this.player.y > 725){
        this.game.add.sprite(260,200,'cat');
        //console.log("you have died");
        this.player.destroy();
        this.platforms.destroy();
        this.game.debug.text("Game over. Your score is " + this.platformCounter, 20, 20);
        localStorage.setItem('score', this.platformCounter);
        console.log("Your score has been saved");
        console.log(localStorage.getItem('score'));
        this.displayText();

        this.time.events.add(Phaser.Timer.SECOND * 10, this.destroyWorld, this);
        console.log("timer has expired");
    }

};

GameState.prototype.displayText = function () {
    this.text = this.game.add.text(this.game.world.centerX, this.game.world.centerY,this.platformCounter + "Punkte", {
        font:"65px Arial",
        fill: "#ff0044",
        align: "center"
    });

    this.text.anchor.setTo(0.5, 0.5);
};

//destroy game after the timer has expired

GameState.prototype.destroyWorld = function() {
    //this.platforms.destroy;
    this.player.destroy();
    this.world.destroy();
};

//Player-left movement:
GameState.prototype.leftInputIsActive = function(){
    var isActive = false;

    isActive = this.input.keyboard.isDown(Phaser.Keyboard.LEFT);
    isActive |= (this.game.input.activePointer.isDown &&
                this.game.input.activePointer.x < this.game.width/4);

    return isActive;
};

GameState.prototype.rightInputIsActive = function(){
    var isActive = false;

    isActive = this.input.keyboard.isDown(Phaser.Keyboard.RIGHT);
    isActive |= (this.game.input.activePointer.isDown &&
                this.game.input.activePointer.x > this.game.width/2 + this.game.width/4);

    return isActive;
};

GameState.prototype.upInputIsActive = function(duration){
    var isActive = false;

    isActive = this.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR, duration);
    isActive |= (this.game.input.activePointer.justPressed(duration + 1000/60) &&
                this.game.input.activePointer.x > this.game.width/4 &&
                this.game.input.activePointer.x < this.game.width/2 + this.game.width/4);

    return isActive;
};

var game = new Phaser.Game(848,750, Phaser.AUTO, 'game');
game.state.add('game', GameState, true);<commit_msg>finally<commit_after>var GameState = function (game) {
};

//load assets
GameState.prototype.preload = function(){

    this.game.load.image('map', 'assets/map.png'); // thjs is the background
    this.game.load.image('ground', 'assets/block.png');//this is the ground
    this.game.load.image('block', 'assets/pixel_1.png');//this is the image for the platforms, the block argument in the create function below links the sprite to the platform
    this.game.load.spritesheet('player', 'assets/dude.png', 32, 48);
    this.game.load.image('cat', 'assets/cat.png');

};

GameState.prototype.create = function () {
    //this.game.add.sprite(0,0, 'map');

    //movement:
    this.MAX_SPEED = 500; //px/s
    this.ACCELERATION = 1500; //px/s/s
    this.DRAG = 900; //px/s
    this.GRAVITY = 2600;
    this.JUMP_SPEED = -1000;
    //create player
    this.player = this.game.add.sprite(this.game.width/2, this.game.height - 90, 'player');
    this.player.anchor.set(0.5);

    this.player.yOrig = this.player.y;
    this.player.yChange = 0;

    //add player movement animations;
    this.player.animations.add('left', [0,1,2,3], 10, true);
    this.player.animations.add('right', [5,6,7,8], 10, true);

    //physics
    this.game.physics.enable(this.player, Phaser.Physics.ARCADE);
    //make player collide with the boundaries of the game
    this.player.body.collideWorldBounds = true;
    this.player.body.maxVelocity.setTo(this.MAX_SPEED, this.MAX_SPEED * 10);
    this.player.body.drag.setTo(this.DRAG,0);

    this.player.body.gravity.y = this.GRAVITY;
    this.player.body.checkCollision.up = false;
    //this.player.body.checkCollision.left = false;
    //this.player.body.checkCollision.right = false;

    //create floor
    this.ground = this.game.add.group();
    for(var x = 0; x < this.game.width; x += 32) {
        // Add the ground blocks, enable physics on each, make them immovable
        var groundBlock = this.game.add.sprite(x, this.game.height - 32, 'ground');
        this.game.physics.enable(groundBlock, Phaser.Physics.ARCADE);
        groundBlock.body.immovable = true;
        groundBlock.body.allowGravity = false;
        this.ground.add(groundBlock);
    }

    //console.log("this is the players y pos" + this.player.y);
    //create platforms
    this.platformsCreate();

    //controls:
    this.game.input.keyboard.addKeyCapture([
        Phaser.Keyboard.LEFT,
        Phaser.Keyboard.RIGHT,
        Phaser.Keyboard.UP,
        Phaser.Keyboard.DOWN
    ]);

    //scaling
    this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
    this.scale.maxWidth = this.game.width;
    this.scale.maxHeight = this.game.height;
    this.scale.pageAlignHorizontally = true;
    this.scale.pageAlignVertically = true;
    this.scale.setScreenSize( true );

    //camera
    this.cameraYMin = 99999;
    this.platformYMin = 99999;

    //trigger the counter which destroys the floor
    this.destructionCounter();

    //initialize Platformcounter
    this.platformCounter = 0;

};

    /****************************************************************************************************************/
    /*                      Player related settings and controls                                                                  /
    /************************************************************************************************************** */

 GameState.prototype.update = function() {
     //collission checking
     this.physics.arcade.collide(this.player, this.ground);
     this.physics.arcade.collide(this.player, this.platforms);

     this.platforms.forEachAlive(function(platform){
         platform.body.y += 1;
     });

     //controls
     if (this.leftInputIsActive()) {
         this.player.body.acceleration.x = -this.ACCELERATION;
         this.player.animations.play('left');
     } else if (this.rightInputIsActive()) {
         this.player.body.acceleration.x = this.ACCELERATION;
         this.player.animations.play('right');
     } else {
         this.player.body.acceleration.x = 0;
         this.player.animations.stop();
         //we need to do this to display the static position when standing
         this.player.frame = 4;
     }

     //check whether the player is on the ground
     var onTheGround = this.player.body.touching.down;
     if (onTheGround && this.upInputIsActive()){
         this.player.body.velocity.y = this.JUMP_SPEED;
     }

     this.world.setBounds(0, -this.player.yChange, this.world.width, this.game.height + this.player.yChange);

     this.platforms.forEachAlive(function (elem) {
         this.platformYMin = Math.min(this.platformYMin, elem.y);
         if (elem.y > this.camera.y + this.game.height) {
             elem.kill();
             this.score();
         }
     }, this);

     //make player die on ground contact
     this.die();
 };

GameState.prototype.score = function(){
    this.platformCounter ++;
    console.log(this.platformCounter);
    this.game.debug.text(this.platformCounter, 20, 20);
};

GameState.prototype.platformsCreate = function(){
         //FUCK EVERYTHING
         this.platforms = this.add.group();
         this.platforms.enableBody = true;

         //determine the number of platforms you want to create (the wide ones)
         var numberofPlatforms = 1000;
         this.platforms.createMultiple( numberofPlatforms, 'block' );

         // create a batch of platforms that start to move up the level
         for( var i = 0; i < numberofPlatforms; i++ ) {
             //modify the last parameter in this line to change the width of the platforms
             this.platformsCreateOne( this.rnd.integerInRange( 0, this.world.width - 45 ), this.world.height - 100 - 100 * i, 160 );
         }
     };

GameState.prototype.platformsCreateOne = function( x, y, width) {
    // this is a helper function since writing all of this out can get verbose elsewhere
    var platform = this.platforms.getFirstDead();

         //should this turn out to be backstabby later on, simply remove the if statement and only write the codeblock
         //but this is textbook-like error handling....probably a little shady

         if(platform) {
             platform.reset(x, y);
             platform.scale.x = width;
             platform.scale.y = 16;
             platform.body.immovable = true;
             return platform;
         }
     };

GameState.prototype.destructionCounter = function(){
    //this sets a timer that calls the floor destruction method after a while
    game.time.events.add(Phaser.Timer.SECOND * 10, this.destroyFloor, this);
};

GameState.prototype.destroyFloor = function () {
    //this destroys the floor
    this.ground.destroy();
};

GameState.prototype.die = function () {
    if(this.player.y > 725){
        this.game.add.sprite(260,200,'cat');
        //console.log("you have died");
        this.player.destroy();
        this.platforms.destroy();
        this.game.debug.text("Game over. Your score is " + this.platformCounter, 20, 20);
        localStorage.setItem('score', this.platformCounter);

        //************************************************************////
        //***********************************************************/////
        /**/console.log("Your score has been saved");               /////
        /**/console.log(localStorage.getItem('score'));              ////
        /**/this.displayText();                                      ///
        /***********************************************************///
        /***********************************************************///

        this.time.events.add(Phaser.Timer.SECOND * 10, this.destroyWorld, this);
        console.log("timer has expired");
    }
    //make the player die

};

GameState.prototype.displayText = function () {
    this.text = this.game.add.text(this.game.world.centerX, this.game.world.centerY,this.platformCounter + "Punkte", {
        font:"65px Arial",
        fill: "#ff0044",
        align: "center"
    });

    this.text.anchor.setTo(0.5, 0.5);
};

//destroy game after the timer has expired

GameState.prototype.destroyWorld = function() {
    //this.platforms.destroy;
    this.player.destroy();
    this.world.destroy();
};

//Player-left movement:
GameState.prototype.leftInputIsActive = function(){
    var isActive = false;

    isActive = this.input.keyboard.isDown(Phaser.Keyboard.LEFT);
    isActive |= (this.game.input.activePointer.isDown &&
                this.game.input.activePointer.x < this.game.width/4);

    return isActive;
};

GameState.prototype.rightInputIsActive = function(){
    var isActive = false;

    isActive = this.input.keyboard.isDown(Phaser.Keyboard.RIGHT);
    isActive |= (this.game.input.activePointer.isDown &&
                this.game.input.activePointer.x > this.game.width/2 + this.game.width/4);

    return isActive;
};

GameState.prototype.upInputIsActive = function(duration){
    var isActive = false;

    isActive = this.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR, duration);
    isActive |= (this.game.input.activePointer.justPressed(duration + 1000/60) &&
                this.game.input.activePointer.x > this.game.width/4 &&
                this.game.input.activePointer.x < this.game.width/2 + this.game.width/4);

    return isActive;
};

var game = new Phaser.Game(848,750, Phaser.AUTO, 'game');
game.state.add('game', GameState, true);<|endoftext|>


<commit_before>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var cwidth = 960;
        var cheight = 540;
        var moves = {
            u: [0,-1],
            d: [0,1],
            l: [-1,0],
            r: [1,0]
        };
        var nodemap = [];
        var origroomlist = [];
        var roomlist = [];
        var removelist = [];
        document.getElementById("paintbtn").onclick = paint;

        function removeRooms(){
            origroomlist = roomlist.slice(0);
            removelist = [];
            for(var i = 0; i< roomlist.length; i++){
                var remove = 1;
                var tempHeight = roomlist[i].height;
                var tempWidth = roomlist[i].width;
                for(var j = 0; j< tempWidth; j++){
                    for(var k = 0; k< tempHeight; k++){
                        if(nodemap[roomlist[i].x + j][roomlist[i].y + k].isVisited == 1){
                            remove = 0;
                            break;
                        }
                    }
                }

                if(remove ==1 ){
                    roomlist[i].removed = 1;
                }
            }
        }

        function shuffle(array) {
          var currentIndex = array.length, temporaryValue, randomIndex ;

          // While there remain elements to shuffle...
          while (0 !== currentIndex) {

            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
          }
          return array;
        }

        function reset(){
            c.clearRect ( 0 , 0 , canvas.width, canvas.height );
            c.beginPath();
            nodemap = [];
            roomlist = [];
        }

        function walk(start, stop, steps){
            var distX = stop.x - start.x;
            var distY = stop.y - start.y;

            var walkSteps = [];
            for(var i = 0; i< Math.abs(distX); i++){
                if(distX < 0){
                    walkSteps.push(moves.l);
                } else {
                    walkSteps.push(moves.r);
                }
            }
            for(var i = 0; i< Math.abs(distY); i++){
                if(distY < 0){
                    walkSteps.push(moves.u);
                } else {
                    walkSteps.push(moves.d);
                }
            }

            //add a number of random pairs based on how big our grid is
            for(var i = 0; i< steps; i++){
                var rand = Math.floor(Math.random() * 2);
                if(rand < 1){
                    walkSteps.push(moves.u);
                    walkSteps.push(moves.d);
                } else{
                    walkSteps.push(moves.l);
                    walkSteps.push(moves.r);
                }
            }
            return shuffle(walkSteps);
        }

        function createRoom(x, y, pw, ph){
            var randw = Math.floor((Math.random() * (pw/2) + 1) );
            var randh = Math.floor((Math.random() * (ph/2) + 1) );

            for(i = 0; i< randw; i++){
                for(j = 0; j< randh; j++){
                    nodemap[x+i][y+j].isRoom = 1;
                }
            }
            var room = {
              x:x,
              y:y,
              width: randw,
              height: randh,
              removed: 0
            };
            roomlist.push(room);
            return [randw, randh];
        }

        function paint(){
            reset();

            var widthSelect = document.getElementById("width");
            var pathWidth = parseInt(widthSelect.options[widthSelect.selectedIndex].value);

            var heightSelect = document.getElementById("height");
            var pathHeight = parseInt(heightSelect.options[heightSelect.selectedIndex].value);

            //create a start and endpoint based on the grid size
            var startpoint = {
               x: -1,
               y: -1
            }
           var endpoint = {
               x: -1,
               y: -1
            }
            startpoint.x = 0;
            startpoint.y = pathHeight - 1;
            endpoint.x = pathWidth - 1;
            endpoint.y = 0;

            //paint the base grid
            for(var i = 0; i< pathWidth; i++){
                nodemap.push([]);
                for(var j = 0; j< pathHeight; j++){
                    var node = {
                        isVisited: 0,
                        isRoom:0,
                        n:0,
                        s:0,
                        e:0,
                        w:0,
                        x:i,
                        y:j
                    };
                    nodemap[i].push(node);
               }
           }

           //create a random path that we will walk
           var randsteps = 2* Math.floor((pathWidth/2) * (pathHeight/2));
           var walkArray = walk(startpoint, endpoint, randsteps);

           //create two moving points representing where we are and where we were
           var movingpoint = {
               x: -1,
               y: -1
           };
           var movingpointold = {
               x: -1,
               y: -1
           };
           movingpoint.x = startpoint.x;
           movingpoint.y = startpoint.y;
           movingpointold.x = startpoint.x;
           movingpointold.y = startpoint.y;

           //set the start node as visited in the beginning
           nodemap[startpoint.x][startpoint.y].isVisited = 1;

           //loop through the walk
           for (var i = 0; i< walkArray.length; i++){
               movingpoint.x = movingpoint.x + walkArray[i][0];
               movingpoint.y = movingpoint.y + walkArray[i][1];
               var oppcurrMoveX = -1 * walkArray[i][0];
               var oppcurrMoveY = -1 * walkArray[i][1];
               var index = -1;
               for(var j = i; j< walkArray.length; j++){
                   if(walkArray[j][0] == oppcurrMoveX && walkArray[j][1] == oppcurrMoveY){
                       index = j;
                       break;
                   }
               }
               if(movingpoint.x > pathWidth -1){
                   movingpoint.x = movingpoint.x - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if(movingpoint.x < 0){
                   movingpoint.x = movingpoint.x + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if(movingpoint.y > pathHeight -1){
                   movingpoint.y = movingpoint.y - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if( movingpoint.y < 0){
                   movingpoint.y = movingpoint.y + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
                }

               var movedirX = movingpoint.x - movingpointold.x;
               var movedirY = movingpoint.y - movingpointold.y;

               if(movedirX < 0){
                   nodemap[movingpointold.x][movingpointold.y].w = 1;
                   nodemap[movingpoint.x][movingpoint.y].e = 1;
               }else if(movedirX > 0){
                   nodemap[movingpointold.x][movingpointold.y].e = 1;
                   nodemap[movingpoint.x][movingpoint.y].w = 1;
               }
               if(movedirY < 0){
                   nodemap[movingpointold.x][movingpointold.y].n =1;
                   nodemap[movingpoint.x][movingpoint.y].s = 1;
               }else if(movedirY >0){
                   nodemap[movingpointold.x][movingpointold.y].s = 1;
                   nodemap[movingpoint.x][movingpoint.y].n = 1;
               }

               nodemap[movingpoint.x][movingpoint.y].isVisited = 1

               movingpointold.x = movingpoint.x;
               movingpointold.y = movingpoint.y;
           }

           //create a branch point
           var branchpoints = [];
           for(var i = 0; i< nodemap.length; i++){
               for(var j = 0; j< nodemap[i].length; j++){
                   var neighboorcount = 0;
                   try{
                       if(nodemap[i][j-1].isVisited == 1){
                           neighboorcount++;
                       }
                   } catch(e){
                       neighboorcount++;
                   }
                   try{
                       if(nodemap[i][j+1].isVisited == 1){
                           neighboorcount++;
                       }
                   }catch(e){
                       neighboorcount++;
                   }
                   try{
                       if(nodemap[i-1][j].isVisited == 1){
                           neighboorcount++;
                       }
                   }catch(e){
                       neighboorcount++;
                   }
                   try{
                       if(nodemap[i +1][j].isVisited == 1){
                           neighboorcount++;
                       }
                   }catch(e){
                       neighboorcount++;
                   }

                   if(neighboorcount <=2 && neighboorcount > 0){
                       branchpoints.push(nodemap[i][j]);
                   }
               }
           }

           //create random rooms
           for(var i = 0; i< Math.floor(pathWidth/2)+1; i++){
                for(var j = 0; j< Math.floor(pathHeight/2)+1; j++){
                    var randRoom = Math.floor((Math.random() * 9));
                    if(randRoom < 1){
                        roomDim = createRoom(i,j,pathWidth,pathHeight);
                        //c.beginPath();
                        //c.fillStyle = "#FFFFFF";
                        //c.fillRect(i*30 + 6, j*30 + 6, roomDim[0]*30 - 6*2, roomDim[1]*30 - 6*2);
                        //c.stroke();
                    }
                }
            }

            //get rid of rooms that aren't attached
            removeRooms();

           //paint the map data
           for(var i = 0; i< nodemap.length; i++){
               for(var j = 0; j < nodemap[i].length; j++){
                   c.fillStyle = "#000000";
                   c.fillRect(i*30, j*30, 30, 30);
                   if(nodemap[i][j].isVisited == 1){
                       c.fillStyle = "#FFFFFF";
                       c.fillRect(i*30 + 6, j*30 + 6, 18, 18);
                       if(nodemap[i][j].n){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 12, j*30, 6, 6);
                       }
                       if(nodemap[i][j].s){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 12, j*30 + 24, 6, 6);
                       }
                       if(nodemap[i][j].e){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 24, j*30 + 12, 6, 6);
                       }
                       if(nodemap[i][j].w){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30, j*30 + 12, 6, 6);
                       }
                   }
                   if(nodemap[i][j].isRoom == 1){
                       //c.fillStyle = "#FFFFFF";
                       //c.fillRect(i*30, j*30, 30, 30);

                   }
               }
           }

           //paint the original rooms
           /*for(var i = 0; i< origroomlist.length; i++){
                c.beginPath();
                c.fillStyle = "#33CCFF";
                c.fillRect(origroomlist[i].x*30 + 6, origroomlist[i].y*30 + 6, origroomlist[i].width*30 - 6*2, origroomlist[i].height*30 - 6*2);
                c.stroke();
            }*/

           //paint the rooms so they look nice
           for(var i = 0; i< roomlist.length; i++){
               if(roomlist[i].removed == 0){
                   c.beginPath();
                   c.fillStyle = "#FFFFFF";
                   c.fillRect(roomlist[i].x*30 + 6, roomlist[i].y*30 + 6, roomlist[i].width*30 - 6*2, roomlist[i].height*30 - 6*2);
                   c.stroke();
               }
            }

            for(var i = 0; i< branchpoints.length; i++){
                c.fillStyle = "#CC66FF";
                c.fillRect(branchpoints[i].x*30 + 6, branchpoints[i].y*30 + 6, 18, 18);
            }

            //paint the start, branch, and end points.
            c.fillStyle = "#33CC33";
            c.fillRect(startpoint.x*30 + 6, startpoint.y*30 + 6, 18, 18);
            c.fillStyle = "#CC0000";
            c.fillRect(endpoint.x*30 + 6, endpoint.y*30 + 6, 18, 18);

        }
    }
})(window, document, undefined);
<commit_msg>Update script.js<commit_after>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var cwidth = 960;
        var cheight = 540;
        var moves = {
            u: [0,-1],
            d: [0,1],
            l: [-1,0],
            r: [1,0]
        };
        var nodemap = [];
        var origroomlist = [];
        var roomlist = [];
        var removelist = [];
        document.getElementById("paintbtn").onclick = paint;

        function removeRooms(){
            origroomlist = roomlist.slice(0);
            removelist = [];
            for(var i = 0; i< roomlist.length; i++){
                var remove = 1;
                var tempHeight = roomlist[i].height;
                var tempWidth = roomlist[i].width;
                for(var j = 0; j< tempWidth; j++){
                    for(var k = 0; k< tempHeight; k++){
                        if(nodemap[roomlist[i].x + j][roomlist[i].y + k].isVisited == 1){
                            remove = 0;
                            break;
                        }
                    }
                }

                if(remove ==1 ){
                    roomlist[i].removed = 1;
                }
            }
        }

        function shuffle(array) {
          var currentIndex = array.length, temporaryValue, randomIndex ;

          // While there remain elements to shuffle...
          while (0 !== currentIndex) {

            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
          }
          return array;
        }

        function reset(){
            c.clearRect ( 0 , 0 , canvas.width, canvas.height );
            c.beginPath();
            nodemap = [];
            roomlist = [];
        }

        function walk(start, stop, steps){
            var distX = stop.x - start.x;
            var distY = stop.y - start.y;

            var walkSteps = [];
            for(var i = 0; i< Math.abs(distX); i++){
                if(distX < 0){
                    walkSteps.push(moves.l);
                } else {
                    walkSteps.push(moves.r);
                }
            }
            for(var i = 0; i< Math.abs(distY); i++){
                if(distY < 0){
                    walkSteps.push(moves.u);
                } else {
                    walkSteps.push(moves.d);
                }
            }

            //add a number of random pairs based on how big our grid is
            for(var i = 0; i< steps; i++){
                var rand = Math.floor(Math.random() * 2);
                if(rand < 1){
                    walkSteps.push(moves.u);
                    walkSteps.push(moves.d);
                } else{
                    walkSteps.push(moves.l);
                    walkSteps.push(moves.r);
                }
            }
            return shuffle(walkSteps);
        }

        function createRoom(x, y, pw, ph){
            var randw = Math.floor((Math.random() * (pw/2) + 1) );
            var randh = Math.floor((Math.random() * (ph/2) + 1) );

            for(i = 0; i< randw; i++){
                for(j = 0; j< randh; j++){
                    nodemap[x+i][y+j].isRoom = 1;
                }
            }
            var room = {
              x:x,
              y:y,
              width: randw,
              height: randh,
              removed: 0
            };
            roomlist.push(room);
            return [randw, randh];
        }

        function paint(){
            reset();

            var widthSelect = document.getElementById("width");
            var pathWidth = parseInt(widthSelect.options[widthSelect.selectedIndex].value);

            var heightSelect = document.getElementById("height");
            var pathHeight = parseInt(heightSelect.options[heightSelect.selectedIndex].value);

            //create a start and endpoint based on the grid size
            var startpoint = {
               x: -1,
               y: -1
            }
           var endpoint = {
               x: -1,
               y: -1
            }
            startpoint.x = 0;
            startpoint.y = pathHeight - 1;
            endpoint.x = pathWidth - 1;
            endpoint.y = 0;

            //paint the base grid
            for(var i = 0; i< pathWidth; i++){
                nodemap.push([]);
                for(var j = 0; j< pathHeight; j++){
                    var node = {
                        isVisited: 0,
                        isRoom:0,
                        n:0,
                        s:0,
                        e:0,
                        w:0,
                        x:i,
                        y:j
                    };
                    nodemap[i].push(node);
               }
           }

           //create a random path that we will walk
           var randsteps = 2* Math.floor((pathWidth/2) * (pathHeight/2));
           var walkArray = walk(startpoint, endpoint, randsteps);

           //create two moving points representing where we are and where we were
           var movingpoint = {
               x: -1,
               y: -1
           };
           var movingpointold = {
               x: -1,
               y: -1
           };
           movingpoint.x = startpoint.x;
           movingpoint.y = startpoint.y;
           movingpointold.x = startpoint.x;
           movingpointold.y = startpoint.y;

           //set the start node as visited in the beginning
           nodemap[startpoint.x][startpoint.y].isVisited = 1;

           //loop through the walk
           for (var i = 0; i< walkArray.length; i++){
               movingpoint.x = movingpoint.x + walkArray[i][0];
               movingpoint.y = movingpoint.y + walkArray[i][1];
               var oppcurrMoveX = -1 * walkArray[i][0];
               var oppcurrMoveY = -1 * walkArray[i][1];
               var index = -1;
               for(var j = i; j< walkArray.length; j++){
                   if(walkArray[j][0] == oppcurrMoveX && walkArray[j][1] == oppcurrMoveY){
                       index = j;
                       break;
                   }
               }
               if(movingpoint.x > pathWidth -1){
                   movingpoint.x = movingpoint.x - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if(movingpoint.x < 0){
                   movingpoint.x = movingpoint.x + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if(movingpoint.y > pathHeight -1){
                   movingpoint.y = movingpoint.y - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if( movingpoint.y < 0){
                   movingpoint.y = movingpoint.y + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
                }

               var movedirX = movingpoint.x - movingpointold.x;
               var movedirY = movingpoint.y - movingpointold.y;

               if(movedirX < 0){
                   nodemap[movingpointold.x][movingpointold.y].w = 1;
                   nodemap[movingpoint.x][movingpoint.y].e = 1;
               }else if(movedirX > 0){
                   nodemap[movingpointold.x][movingpointold.y].e = 1;
                   nodemap[movingpoint.x][movingpoint.y].w = 1;
               }
               if(movedirY < 0){
                   nodemap[movingpointold.x][movingpointold.y].n =1;
                   nodemap[movingpoint.x][movingpoint.y].s = 1;
               }else if(movedirY >0){
                   nodemap[movingpointold.x][movingpointold.y].s = 1;
                   nodemap[movingpoint.x][movingpoint.y].n = 1;
               }

               nodemap[movingpoint.x][movingpoint.y].isVisited = 1

               movingpointold.x = movingpoint.x;
               movingpointold.y = movingpoint.y;
           }

           //create a branch point
           var branchpoints = [];
           for(var i = 0; i< nodemap.length; i++){
               for(var j = 0; j< nodemap[i].length; j++){
                   var neighboorcount = 0;
                   try{
                       if(nodemap[i][j-1].isVisited == 1){
                           neighboorcount++;
                       }
                   } catch(e){
                       neighboorcount++;
                   }
                   try{
                       if(nodemap[i][j+1].isVisited == 1){
                           neighboorcount++;
                       }
                   }catch(e){
                       neighboorcount++;
                   }
                   try{
                       if(nodemap[i-1][j].isVisited == 1){
                           neighboorcount++;
                       }
                   }catch(e){
                       neighboorcount++;
                   }
                   try{
                       if(nodemap[i +1][j].isVisited == 1){
                           neighboorcount++;
                       }
                   }catch(e){
                       neighboorcount++;
                   }

                   if(neighboorcount <=2 && neighboorcount > 0 && nodemap[i][j].isVisited == 1){
                       branchpoints.push(nodemap[i][j]);
                   }
               }
           }

           //create random rooms
           for(var i = 0; i< Math.floor(pathWidth/2)+1; i++){
                for(var j = 0; j< Math.floor(pathHeight/2)+1; j++){
                    var randRoom = Math.floor((Math.random() * 9));
                    if(randRoom < 1){
                        roomDim = createRoom(i,j,pathWidth,pathHeight);
                        //c.beginPath();
                        //c.fillStyle = "#FFFFFF";
                        //c.fillRect(i*30 + 6, j*30 + 6, roomDim[0]*30 - 6*2, roomDim[1]*30 - 6*2);
                        //c.stroke();
                    }
                }
            }

            //get rid of rooms that aren't attached
            removeRooms();

           //paint the map data
           for(var i = 0; i< nodemap.length; i++){
               for(var j = 0; j < nodemap[i].length; j++){
                   c.fillStyle = "#000000";
                   c.fillRect(i*30, j*30, 30, 30);
                   if(nodemap[i][j].isVisited == 1){
                       c.fillStyle = "#FFFFFF";
                       c.fillRect(i*30 + 6, j*30 + 6, 18, 18);
                       if(nodemap[i][j].n){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 12, j*30, 6, 6);
                       }
                       if(nodemap[i][j].s){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 12, j*30 + 24, 6, 6);
                       }
                       if(nodemap[i][j].e){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 24, j*30 + 12, 6, 6);
                       }
                       if(nodemap[i][j].w){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30, j*30 + 12, 6, 6);
                       }
                   }
                   if(nodemap[i][j].isRoom == 1){
                       //c.fillStyle = "#FFFFFF";
                       //c.fillRect(i*30, j*30, 30, 30);

                   }
               }
           }

           //paint the original rooms
           /*for(var i = 0; i< origroomlist.length; i++){
                c.beginPath();
                c.fillStyle = "#33CCFF";
                c.fillRect(origroomlist[i].x*30 + 6, origroomlist[i].y*30 + 6, origroomlist[i].width*30 - 6*2, origroomlist[i].height*30 - 6*2);
                c.stroke();
            }*/

           //paint the rooms so they look nice
           for(var i = 0; i< roomlist.length; i++){
               if(roomlist[i].removed == 0){
                   c.beginPath();
                   c.fillStyle = "#FFFFFF";
                   c.fillRect(roomlist[i].x*30 + 6, roomlist[i].y*30 + 6, roomlist[i].width*30 - 6*2, roomlist[i].height*30 - 6*2);
                   c.stroke();
               }
            }

            for(var i = 0; i< branchpoints.length; i++){
                c.fillStyle = "#CC66FF";
                c.fillRect(branchpoints[i].x*30 + 6, branchpoints[i].y*30 + 6, 18, 18);
            }

            //paint the start, branch, and end points.
            c.fillStyle = "#33CC33";
            c.fillRect(startpoint.x*30 + 6, startpoint.y*30 + 6, 18, 18);
            c.fillStyle = "#CC0000";
            c.fillRect(endpoint.x*30 + 6, endpoint.y*30 + 6, 18, 18);

        }
    }
})(window, document, undefined);
<|endoftext|>


<commit_before>(function($) {
    "use strict";
    $.fn.pbTouchSlider = function(options) {
        var slider_Opts = $.extend({
            slider_Wrap : '', // Assign a unique ID to the div.o-sliderContainer
            slider_Item : '.o-slider--item', // Single Item
            slider_Drag : true, // Your choise.. to dragIt or not to dragIt..this is the question...
            slider_Dots : { // Wanna see dots or not?
              class :'.o-slider-pagination',
              enabled : true
            },
            slider_Arrows : { // Wanna see Arrows or not?
              class :'.o-slider-arrows',
              enabled : true
            },
            slider_Threshold : 25, // Percentage of  dragX before go to next/prev slider
            slider_Speed : 1000,
            slider_Ease : 'cubic-bezier(0.5, 0, 0.5, 1)',  // see http://cubic-bezier.com/
            slider_Breakpoints : { // Kind of media queries ( can add more if you know how to do it :D and if you need )
                default : {
                    height : 500 //  height on desktop
                },
                tablet : {
                    height : 400, // height on tablet
                    media : 1024 // tablet breakpoint
                },
                smartphone : {
                    height : 300, // height on smartphone
                    media : 768 // smartphone breakpoint
                }
            }
        }, options);

        /*:::::::: LOADER ::::::::*/
        var loaderHtml = '
'+
                          '
'+
                          '

'+
                          '

'+
                          '

'+
                          '

'+
                          '

';
        $(slider_Opts.slider_Wrap).each( function(){$(this).append(loaderHtml);});
        function loader(visibility) {
            var thisLoader = $(slider_Opts.slider_Wrap +' .loaderWrap');
            if (visibility === true)
                $(thisLoader).show();
             else
                $(thisLoader).hide();
        }

        /*:::::::: RESPONSIVE ::::::::*/
        function setResponsive() {
            var VW = document.documentElement.clientWidth;
            if (VW >= slider_Opts.slider_Breakpoints.tablet.media) {
                $(pbSlider.slider_Wrap + '.o-sliderContainer,'+ pbSlider.slider_Wrap + ' ' + pbSlider.slider_Item).css({height: slider_Opts.slider_Breakpoints.default.height});
            } else if (VW >= slider_Opts.slider_Breakpoints.smartphone.media) {
                $(pbSlider.slider_Wrap + '.o-sliderContainer,'+ pbSlider.slider_Wrap + ' ' + pbSlider.slider_Item).css({height: slider_Opts.slider_Breakpoints.tablet.height});
            } else {
                $(pbSlider.slider_Wrap + '.o-sliderContainer,'+ pbSlider.slider_Wrap + ' ' + pbSlider.slider_Item).css({height: slider_Opts.slider_Breakpoints.smartphone.height});
            }
        }
        $(window).resize(function() {setResponsive();});

        /*:::::::: OBJECT SLIDER ::::::::*/
        var pbSlider = {};
        pbSlider.slider_Wrap = slider_Opts.slider_Wrap;
        pbSlider.slider_Item = slider_Opts.slider_Item;
        pbSlider.slider_Dots = slider_Opts.slider_Dots;
        pbSlider.slider_Threshold = slider_Opts.slider_Threshold;
        pbSlider.slider_Active = 0;
        pbSlider.slider_Count = 0;
        pbSlider.slider_NavWrap = '

';
        pbSlider.slider_NavPagination ='

';
        pbSlider.slider_NavArrows ='

';

        /*:::::::: APPEND ANIMATION ::::::::*/
        $('head').append(
            ''
        );
        function setImages(target){
          $(target).each(function(){
            var bg = $(this).attr('data-image');
            //console.log(bg)
            $(this).css({'background-image':'url('+bg+')'});
          });
        }
        setImages(pbSlider.slider_Item);
        /*:::::::: ONlOAD STUFF ::::::::*/
        $(window).on('load', function() {
            setTimeout ( function(){
              loader(false);
            },1000);
            $(pbSlider.slider_Wrap + ' .o-slider-controls').addClass('isVisible');
            $(pbSlider.slider_Draggable).addClass('isVisible');
            setResponsive();
        });

        /*:::::::: INIT ::::::::*/
        pbSlider.pbInit = function(selector) {
            pbSlider.slider_Draggable = selector;
            pbSlider.slider_Count = $(pbSlider.slider_Wrap).find(pbSlider.slider_Item).length;
            $(selector).css('width', pbSlider.slider_Count * 100 + '%');
            $(pbSlider.slider_Item).css({'width': 100 / pbSlider.slider_Count+ '%'});

            var incrSlides = 0;
            $(pbSlider.slider_Wrap).find(pbSlider.slider_Item).each(function() {
                $(this).attr('data-id', 'slide-' + (incrSlides++));
            });

            if(slider_Opts.slider_Arrows.enabled === true || slider_Opts.slider_Dots.enabled === true ){
              $(pbSlider.slider_Wrap).append(pbSlider.slider_NavWrap);
            }

            if(slider_Opts.slider_Arrows.enabled === true){$(pbSlider.slider_Wrap).append(pbSlider.slider_NavArrows);}

            if(slider_Opts.slider_Dots.enabled === true){
              var incrPagination = 0;
              $(pbSlider.slider_Wrap).append(pbSlider.slider_NavPagination);
              for (incrPagination; incrPagination < pbSlider.slider_Count; incrPagination++) {
                  var activeStatus = incrPagination === pbSlider.slider_Active ? ' class="isActive"' : '';
                  var gotoSlide = 'data-increase="' + [incrPagination] + '"';
                  var background = $(pbSlider.slider_Wrap).find("[data-id='slide-" + incrPagination + "']").attr('data-image');
                  //background = background.replace('url(','').replace(')','').replace(/\"/gi, "");
                  console.log(background);
                  $(pbSlider.slider_Wrap).find(pbSlider.slider_Dots.class).append(
                    '
'+
                      ''+
                    '
');
              }
            }
            setTimeout(function() {
              $(pbSlider.slider_Item + '[data-id=slide-' + pbSlider.slider_Active + ']').addClass('isActive');
            },400);
            /*:::::::: HAMMER => see http://hammerjs.github.io/  ::::::::*/
            if(slider_Opts.slider_Drag === true){
              $(pbSlider.slider_Draggable).addClass('isDraggable');
              var stuff4hammer = document.querySelector(pbSlider.slider_Wrap);
              var hammerOpts =   {
                dragLockToAxis: true,
                dragBlockHorizontal: true,
                touchAction: 'pan-x',
                cssProps: {userSelect: true}
              }
              var hammertime = new Hammer(stuff4hammer, hammerOpts);
              hammertime.on('pan', function(e) {
                e.preventDefault();
                var percentage = 100 / pbSlider.slider_Count * e.deltaX / window.innerWidth;
                var percentageCalc = percentage - 100 / pbSlider.slider_Count * pbSlider.slider_Active;
                var notDraggable = $(e.target).find('.slider-textWrap').length;
                  if(pbSlider.slider_Active != pbSlider.slider_Count-1 && pbSlider.slider_Active != 0){
                    $(pbSlider.slider_Wrap).find(pbSlider.slider_Item).addClass('isMoving');
                  }
                  $(pbSlider.slider_Draggable).css({
                      'perspective': '1000px',
                      'backface-visibility': 'hidden',
                      'transform': 'translateX( ' + percentageCalc + '% )'
                  });
                  if (e.isFinal) {
                      if (e.velocityX > 1) {
                          pbSlider.pbGoslide(pbSlider.slider_Active - 1);
                      } else if (e.velocityX < -1) {
                          pbSlider.pbGoslide(pbSlider.slider_Active + 1);
                      } else {
                          if (percentage <= -(pbSlider.slider_Threshold / pbSlider.slider_Count)) {
                              pbSlider.pbGoslide(pbSlider.slider_Active + 1);
                          } else if (percentage >= (pbSlider.slider_Threshold / pbSlider.slider_Count)) {
                              pbSlider.pbGoslide(pbSlider.slider_Active - 1);
                          } else {
                              pbSlider.pbGoslide(pbSlider.slider_Active);
                          }
                      }
                  }
              });
            }
            $(pbSlider.slider_Wrap + ' .o-slider-pagination li').on('click', function() {

                var this_data = $(this).attr('data-increase');
                if(!$(this).hasClass('isActive')){
                  pbSlider.pbGoslide(this_data);
                }
                //console.log(this_data + ' / ' + pbSlider.slider_Active );
            });
            $(pbSlider.slider_Wrap + ' .o-slider-prev').addClass('isDisabled');
            $(pbSlider.slider_Wrap + ' .o-slider-arrows li').on('click', function() {
                if ($(this).hasClass('o-slider-next')) {
                    pbSlider.pbGoslide(pbSlider.slider_Active + 1);
                } else {
                    pbSlider.pbGoslide(pbSlider.slider_Active - 1);
                }
            });
        };
        /*:::::::: SLIDER ENGINE ::::::::*/
        pbSlider.pbGoslide = function(number) {
            $(pbSlider.slider_Wrap + ' .o-slider-arrows li').removeClass('isDisabled');

            if (number < 0) {
                pbSlider.slider_Active = 0;
            } else if (number > pbSlider.slider_Count - 1) {
                pbSlider.slider_Active = pbSlider.slider_Count - 1;
            } else {
                pbSlider.slider_Active = number;
                loader(true);
            }

            if (pbSlider.slider_Active >= pbSlider.slider_Count - 1) {
              var firstS = $(pbSlider.slider_Wrap).find(pbSlider.slider_Item).first();
                $(pbSlider.slider_Wrap + ' .o-slider-next').addClass('isDisabled');
            } else if (pbSlider.slider_Active <= 0) {
                $(pbSlider.slider_Wrap + ' .o-slider-prev').addClass('isDisabled');
            } else {
                $(pbSlider.slider_Wrap + ' .o-slider-arrows li').removeClass('isDisabled');
            }
            if(pbSlider.slider_Active != pbSlider.slider_Count-1 && pbSlider.slider_Active != 0){
              $(pbSlider.slider_Wrap).find(pbSlider.slider_Item).addClass('isMoving');

            }
            $(pbSlider.slider_Draggable).addClass('isAnimate');
            var percentage = -(100 / pbSlider.slider_Count) * pbSlider.slider_Active;
            $(pbSlider.slider_Draggable).css({
                'perspective': '1000px',
                'backface-visibility': 'hidden',
                'transform': 'translateX( ' + percentage + '% )'
            });
            clearTimeout(pbSlider.timer);
            pbSlider.timer = setTimeout(function() {
                $(pbSlider.slider_Wrap).find(pbSlider.slider_Draggable).removeClass('isAnimate');
                $(pbSlider.slider_Wrap).find(pbSlider.slider_Item).removeClass('isActive').removeClass('isMoving');
                $(pbSlider.slider_Wrap).find(pbSlider.slider_Item + '[data-id=slide-' + pbSlider.slider_Active + ']').addClass('isActive');
                $(pbSlider.slider_Wrap + ' .o-slider--item img').css('transform', 'translateX(0px )');
                loader(false);
            }, slider_Opts.slider_Speed);
            if(slider_Opts.slider_Dots.enabled === true){
              var sliderDots = $(pbSlider.slider_Wrap).find(pbSlider.slider_Dots.class + ' > *');
              var increase = 0;
              for (increase; increase < sliderDots.length; increase++) {
                  var className = increase == pbSlider.slider_Active ? 'isActive' : '';
                  $(pbSlider.slider_Wrap).find(sliderDots[increase]).removeClass('isActive').addClass(className);
                  $(pbSlider.slider_Wrap).find(sliderDots[increase]).children().removeClass('isActive').addClass(className);
             }
             setTimeout(function() {
               $(pbSlider.slider_Wrap).find(sliderDots).children().removeClass('isActive');
             },500);
            }
            pbSlider.slider_Active = Number(pbSlider.slider_Active);
        };
        pbSlider.auto = function() {
            pbSlider.autoTimer = setInterval(function() {
                if (pbSlider.slider_Active >= pbSlider.slider_Count - 1) {
                    pbSlider.pbGoslide(0);
                } else {
                    $(pbSlider.slider_Wrap + ' .o-slider-next').trigger('click');
                }
            }, 3000);
        }
        //pbSlider.auto();
        pbSlider.pbInit(this);
    };

}(jQuery));
<commit_msg>js fix<commit_after>(function($) {
    "use strict";
    $.fn.pbTouchSlider = function(options) {
        var slider_Opts = $.extend({
            slider_Wrap : '', // Assign a unique ID to the div.o-sliderContainer
            slider_Item : '.o-slider--item', // Single Item
            slider_Drag : true, // Your choise.. to dragIt or not to dragIt..this is the question...
            slider_Dots : { // Wanna see dots or not?
              class :'.o-slider-pagination',
              enabled : true
            },
            slider_Arrows : { // Wanna see Arrows or not?
              class :'.o-slider-arrows',
              enabled : true
            },
            slider_Threshold : 25, // Percentage of  dragX before go to next/prev slider
            slider_Speed : 1000,
            slider_Ease : 'cubic-bezier(0.5, 0, 0.5, 1)',  // see http://cubic-bezier.com/
            slider_Breakpoints : { // Kind of media queries ( can add more if you know how to do it :D and if you need )
                default : {
                    height : 500 //  height on desktop
                },
                tablet : {
                    height : 400, // height on tablet
                    media : 1024 // tablet breakpoint
                },
                smartphone : {
                    height : 300, // height on smartphone
                    media : 768 // smartphone breakpoint
                }
            }
        }, options);

        /*:::::::: LOADER ::::::::*/
        var loaderHtml = '
'+
                          '
'+
                          '

'+
                          '

'+
                          '

'+
                          '

'+
                          '

';
        $(slider_Opts.slider_Wrap).each( function(){$(this).append(loaderHtml);});
        function loader(visibility) {
            var thisLoader = $(slider_Opts.slider_Wrap +' .loaderWrap');
            if (visibility === true)
                $(thisLoader).show();
             else
                $(thisLoader).hide();
        }

        /*:::::::: RESPONSIVE ::::::::*/
        function setResponsive() {
            var VW = document.documentElement.clientWidth;
            if (VW >= slider_Opts.slider_Breakpoints.tablet.media) {
                $(pbSlider.slider_Wrap + '.o-sliderContainer,'+ pbSlider.slider_Wrap + ' ' + pbSlider.slider_Item).css({height: slider_Opts.slider_Breakpoints.default.height});
            } else if (VW >= slider_Opts.slider_Breakpoints.smartphone.media) {
                $(pbSlider.slider_Wrap + '.o-sliderContainer,'+ pbSlider.slider_Wrap + ' ' + pbSlider.slider_Item).css({height: slider_Opts.slider_Breakpoints.tablet.height});
            } else {
                $(pbSlider.slider_Wrap + '.o-sliderContainer,'+ pbSlider.slider_Wrap + ' ' + pbSlider.slider_Item).css({height: slider_Opts.slider_Breakpoints.smartphone.height});
            }
        }
        $(window).resize(function() {setResponsive();});

        /*:::::::: OBJECT SLIDER ::::::::*/
        var pbSlider = {};
        pbSlider.slider_Wrap = slider_Opts.slider_Wrap;
        pbSlider.slider_Item = slider_Opts.slider_Item;
        pbSlider.slider_Dots = slider_Opts.slider_Dots;
        pbSlider.slider_Threshold = slider_Opts.slider_Threshold;
        pbSlider.slider_Active = 0;
        pbSlider.slider_Count = 0;
        pbSlider.slider_NavWrap = '

';
        pbSlider.slider_NavPagination ='

';
        pbSlider.slider_NavArrows ='

';

        /*:::::::: APPEND ANIMATION ::::::::*/
        $('head').append(
            ''
        );

        /*:::::::: ONlOAD STUFF ::::::::*/
        $(window).on('load', function() {
          $(pbSlider.slider_Item).each(function(){
            var bg = $(this).attr('data-image');
            $(this).css({'background-image':'url('+bg+')'});
          });
          setTimeout ( function(){
              loader(false);
            },1000);
            $(pbSlider.slider_Wrap + ' .o-slider-controls').addClass('isVisible');
            $(pbSlider.slider_Draggable).addClass('isVisible');
            setResponsive();
        });

        /*:::::::: INIT ::::::::*/
        pbSlider.pbInit = function(selector) {
            pbSlider.slider_Draggable = selector;
            pbSlider.slider_Count = $(pbSlider.slider_Wrap).find(pbSlider.slider_Item).length;
            $(selector).css('width', pbSlider.slider_Count * 100 + '%');
            $(pbSlider.slider_Item).css({'width': 100 / pbSlider.slider_Count+ '%'});

            var incrSlides = 0;
            $(pbSlider.slider_Wrap).find(pbSlider.slider_Item).each(function() {
                $(this).attr('data-id', 'slide-' + (incrSlides++));
            });

            if(slider_Opts.slider_Arrows.enabled === true || slider_Opts.slider_Dots.enabled === true ){
              $(pbSlider.slider_Wrap).append(pbSlider.slider_NavWrap);
            }

            if(slider_Opts.slider_Arrows.enabled === true){$(pbSlider.slider_Wrap).append(pbSlider.slider_NavArrows);}

            if(slider_Opts.slider_Dots.enabled === true){
              var incrPagination = 0;
              $(pbSlider.slider_Wrap).append(pbSlider.slider_NavPagination);
              for (incrPagination; incrPagination < pbSlider.slider_Count; incrPagination++) {
                  var activeStatus = incrPagination === pbSlider.slider_Active ? ' class="isActive"' : '';
                  var gotoSlide = 'data-increase="' + [incrPagination] + '"';
                  var background = $(pbSlider.slider_Wrap).find("[data-id='slide-" + incrPagination + "']").attr('data-image');
                  //background = background.replace('url(','').replace(')','').replace(/\"/gi, "");
                  console.log(background);
                  $(pbSlider.slider_Wrap).find(pbSlider.slider_Dots.class).append(
                    '
'+
                      ''+
                    '
');
              }
            }
            setTimeout(function() {
              $(pbSlider.slider_Item + '[data-id=slide-' + pbSlider.slider_Active + ']').addClass('isActive');
            },400);
            /*:::::::: HAMMER => see http://hammerjs.github.io/  ::::::::*/
            if(slider_Opts.slider_Drag === true){
              $(pbSlider.slider_Draggable).addClass('isDraggable');
              var stuff4hammer = document.querySelector(pbSlider.slider_Wrap);
              var hammerOpts =   {
                dragLockToAxis: true,
                dragBlockHorizontal: true,
                touchAction: 'pan-x',
                cssProps: {userSelect: true}
              }
              var hammertime = new Hammer(stuff4hammer, hammerOpts);
              hammertime.on('pan', function(e) {
                e.preventDefault();
                var percentage = 100 / pbSlider.slider_Count * e.deltaX / window.innerWidth;
                var percentageCalc = percentage - 100 / pbSlider.slider_Count * pbSlider.slider_Active;
                var notDraggable = $(e.target).find('.slider-textWrap').length;
                  if(pbSlider.slider_Active != pbSlider.slider_Count-1 && pbSlider.slider_Active != 0){
                    $(pbSlider.slider_Wrap).find(pbSlider.slider_Item).addClass('isMoving');
                  }
                  $(pbSlider.slider_Draggable).css({
                      'perspective': '1000px',
                      'backface-visibility': 'hidden',
                      'transform': 'translateX( ' + percentageCalc + '% )'
                  });
                  if (e.isFinal) {
                      if (e.velocityX > 1) {
                          pbSlider.pbGoslide(pbSlider.slider_Active - 1);
                      } else if (e.velocityX < -1) {
                          pbSlider.pbGoslide(pbSlider.slider_Active + 1);
                      } else {
                          if (percentage <= -(pbSlider.slider_Threshold / pbSlider.slider_Count)) {
                              pbSlider.pbGoslide(pbSlider.slider_Active + 1);
                          } else if (percentage >= (pbSlider.slider_Threshold / pbSlider.slider_Count)) {
                              pbSlider.pbGoslide(pbSlider.slider_Active - 1);
                          } else {
                              pbSlider.pbGoslide(pbSlider.slider_Active);
                          }
                      }
                  }
              });
            }
            $(pbSlider.slider_Wrap + ' .o-slider-pagination li').on('click', function() {

                var this_data = $(this).attr('data-increase');
                if(!$(this).hasClass('isActive')){
                  pbSlider.pbGoslide(this_data);
                }
                //console.log(this_data + ' / ' + pbSlider.slider_Active );
            });
            $(pbSlider.slider_Wrap + ' .o-slider-prev').addClass('isDisabled');
            $(pbSlider.slider_Wrap + ' .o-slider-arrows li').on('click', function() {
                if ($(this).hasClass('o-slider-next')) {
                    pbSlider.pbGoslide(pbSlider.slider_Active + 1);
                } else {
                    pbSlider.pbGoslide(pbSlider.slider_Active - 1);
                }
            });
        };
        /*:::::::: SLIDER ENGINE ::::::::*/
        pbSlider.pbGoslide = function(number) {
            $(pbSlider.slider_Wrap + ' .o-slider-arrows li').removeClass('isDisabled');

            if (number < 0) {
                pbSlider.slider_Active = 0;
            } else if (number > pbSlider.slider_Count - 1) {
                pbSlider.slider_Active = pbSlider.slider_Count - 1;
            } else {
                pbSlider.slider_Active = number;
                loader(true);
            }

            if (pbSlider.slider_Active >= pbSlider.slider_Count - 1) {
              var firstS = $(pbSlider.slider_Wrap).find(pbSlider.slider_Item).first();
                $(pbSlider.slider_Wrap + ' .o-slider-next').addClass('isDisabled');
            } else if (pbSlider.slider_Active <= 0) {
                $(pbSlider.slider_Wrap + ' .o-slider-prev').addClass('isDisabled');
            } else {
                $(pbSlider.slider_Wrap + ' .o-slider-arrows li').removeClass('isDisabled');
            }
            if(pbSlider.slider_Active != pbSlider.slider_Count-1 && pbSlider.slider_Active != 0){
              $(pbSlider.slider_Wrap).find(pbSlider.slider_Item).addClass('isMoving');

            }
            $(pbSlider.slider_Draggable).addClass('isAnimate');
            var percentage = -(100 / pbSlider.slider_Count) * pbSlider.slider_Active;
            $(pbSlider.slider_Draggable).css({
                'perspective': '1000px',
                'backface-visibility': 'hidden',
                'transform': 'translateX( ' + percentage + '% )'
            });
            clearTimeout(pbSlider.timer);
            pbSlider.timer = setTimeout(function() {
                $(pbSlider.slider_Wrap).find(pbSlider.slider_Draggable).removeClass('isAnimate');
                $(pbSlider.slider_Wrap).find(pbSlider.slider_Item).removeClass('isActive').removeClass('isMoving');
                $(pbSlider.slider_Wrap).find(pbSlider.slider_Item + '[data-id=slide-' + pbSlider.slider_Active + ']').addClass('isActive');
                $(pbSlider.slider_Wrap + ' .o-slider--item img').css('transform', 'translateX(0px )');
                loader(false);
            }, slider_Opts.slider_Speed);
            if(slider_Opts.slider_Dots.enabled === true){
              var sliderDots = $(pbSlider.slider_Wrap).find(pbSlider.slider_Dots.class + ' > *');
              var increase = 0;
              for (increase; increase < sliderDots.length; increase++) {
                  var className = increase == pbSlider.slider_Active ? 'isActive' : '';
                  $(pbSlider.slider_Wrap).find(sliderDots[increase]).removeClass('isActive').addClass(className);
                  $(pbSlider.slider_Wrap).find(sliderDots[increase]).children().removeClass('isActive').addClass(className);
             }
             setTimeout(function() {
               $(pbSlider.slider_Wrap).find(sliderDots).children().removeClass('isActive');
             },500);
            }
            pbSlider.slider_Active = Number(pbSlider.slider_Active);
        };
        pbSlider.auto = function() {
            pbSlider.autoTimer = setInterval(function() {
                if (pbSlider.slider_Active >= pbSlider.slider_Count - 1) {
                    pbSlider.pbGoslide(0);
                } else {
                    $(pbSlider.slider_Wrap + ' .o-slider-next').trigger('click');
                }
            }, 3000);
        }
        //pbSlider.auto();
        pbSlider.pbInit(this);
    };

}(jQuery));
<|endoftext|>


<commit_before>(function ($) {
    $.fn.slides = function (options) {
        $.extend($.fn.slides.settings, $.fn.slides.defaults, options);

        return this.each(function () {
            $.fn.slides.init(this);
        });
    };

    $.fn.slides.settings = {},
    $.fn.slides.slides = [];
    $.fn.slides.current = 0;

    $.fn.slides.defaults = {
        duration: 0,
        help: true,
        bindings: {
            37: "prev", // left
            38: "prev", // up
            75: "prev", // k
            39: "next", // right
            40: "next", // down
            74: "next", // j
            32: "next", // space
            72: "help", // h
        },
    };

    $.fn.slides.init = function (element) {
        $.fn.slides.root = root = $(element);
        $.fn.slides.header = header = root.find("> header");
        $.fn.slides.footer = footer = root.find("> footer");
        var slides = $.fn.slides.slides;

        /* Hide header, footer and (slides > 1). */
        root.addClass("slides").children("section").each(function () {
            slides.push($(this));
        });
        $.each(slides.slice(1), function () {
            $(this).hide();
        });
        $.fn.slides.gotohash();

        $(document).keydown(function (event) {
            var key = (event.keyCode ? event.keyCode : event.which);
            console.log(key);
            var fnname = $.fn.slides.settings.bindings[key],
                fn = $.fn.slides[fnname];
            if (fn) {
                fn();
                return false;
            };
        });

        if ("hashchange" in $(window)) {
            $(window).hashchange(function () {
                $.fn.slides.gotohash();
            });
        };

        $.fn.slides.flash("This webpage is a presentation! Press h for help.");
    };

    $.fn.slides.goto = function (index) {
        var slides = $.fn.slides.slides,
            current = $.fn.slides.current,
            settings = $.fn.slides.settings;
        if (index >= slides.length || index < 0 || (index > 1 && index == current))
            return;
        $.fn.slides.hide(slides[current]);
        $.fn.slides.show(slides[index]);
        $.fn.slides.current = index;
        location.hash = "#slide" + (index + 1);
    };

    $.fn.slides.next = function () {
        $.fn.slides.goto($.fn.slides.current + 1);
    }

    $.fn.slides.prev = function () {
        $.fn.slides.goto($.fn.slides.current - 1);
    }

    $.fn.slides.show = function (slide) {
        slide.show($.fn.slides.settings.duration);
    };

    $.fn.slides.hide = function (slide) {
        slide.hide($.fn.slides.settings.duration);
    };

    $.fn.slides.gotohash = function (hash) {
        var hash = hash;
        if (typeof hash == "undefined")
            hash = location.hash || "#slide1";
        var slide = hash.replace(/^#slide/, "");
        $.fn.slides.goto(parseInt(slide, 10) - 1);
    };

    $.fn.slides.flash = function (message, duration) {
        var elem = $("#flash");
        var duration = duration >= 0 || 5000;
        if (elem.length != 0) {
            elem.remove();
        }

        $('
' + message + '
')
            .appendTo("body")
            .show()
            .fadeOut(duration, function () { $(this).remove(); });
    };

    $.fn.slides.help = function () {
        if (! $.fn.slides.settings.help)
            return;
        $.fn.slides.flash(
                "Keys: " +
                "↑, ←, k or space to go forward; " +
                "↓, →, or j to go backward.");
    };
})(jQuery);
<commit_msg>Zap debugging log.<commit_after>(function ($) {
    $.fn.slides = function (options) {
        $.extend($.fn.slides.settings, $.fn.slides.defaults, options);

        return this.each(function () {
            $.fn.slides.init(this);
        });
    };

    $.fn.slides.settings = {},
    $.fn.slides.slides = [];
    $.fn.slides.current = 0;

    $.fn.slides.defaults = {
        duration: 0,
        help: true,
        bindings: {
            37: "prev", // left
            38: "prev", // up
            75: "prev", // k
            39: "next", // right
            40: "next", // down
            74: "next", // j
            32: "next", // space
            72: "help", // h
        },
    };

    $.fn.slides.init = function (element) {
        $.fn.slides.root = root = $(element);
        $.fn.slides.header = header = root.find("> header");
        $.fn.slides.footer = footer = root.find("> footer");
        var slides = $.fn.slides.slides;

        /* Hide header, footer and (slides > 1). */
        root.addClass("slides").children("section").each(function () {
            slides.push($(this));
        });
        $.each(slides.slice(1), function () {
            $(this).hide();
        });
        $.fn.slides.gotohash();

        $(document).keydown(function (event) {
            var key = (event.keyCode ? event.keyCode : event.which);
            var fnname = $.fn.slides.settings.bindings[key],
                fn = $.fn.slides[fnname];
            if (fn) {
                fn();
                return false;
            };
        });

        if ("hashchange" in $(window)) {
            $(window).hashchange(function () {
                $.fn.slides.gotohash();
            });
        };

        $.fn.slides.flash("This webpage is a presentation! Press h for help.");
    };

    $.fn.slides.goto = function (index) {
        var slides = $.fn.slides.slides,
            current = $.fn.slides.current,
            settings = $.fn.slides.settings;
        if (index >= slides.length || index < 0 || (index > 1 && index == current))
            return;
        $.fn.slides.hide(slides[current]);
        $.fn.slides.show(slides[index]);
        $.fn.slides.current = index;
        location.hash = "#slide" + (index + 1);
    };

    $.fn.slides.next = function () {
        $.fn.slides.goto($.fn.slides.current + 1);
    }

    $.fn.slides.prev = function () {
        $.fn.slides.goto($.fn.slides.current - 1);
    }

    $.fn.slides.show = function (slide) {
        slide.show($.fn.slides.settings.duration);
    };

    $.fn.slides.hide = function (slide) {
        slide.hide($.fn.slides.settings.duration);
    };

    $.fn.slides.gotohash = function (hash) {
        var hash = hash;
        if (typeof hash == "undefined")
            hash = location.hash || "#slide1";
        var slide = hash.replace(/^#slide/, "");
        $.fn.slides.goto(parseInt(slide, 10) - 1);
    };

    $.fn.slides.flash = function (message, duration) {
        var elem = $("#flash");
        var duration = duration >= 0 || 5000;
        if (elem.length != 0) {
            elem.remove();
        }

        $('
' + message + '
')
            .appendTo("body")
            .show()
            .fadeOut(duration, function () { $(this).remove(); });
    };

    $.fn.slides.help = function () {
        if (! $.fn.slides.settings.help)
            return;
        $.fn.slides.flash(
                "Keys: " +
                "↑, ←, k or space to go forward; " +
                "↓, →, or j to go backward.");
    };
})(jQuery);
<|endoftext|>


<commit_before>var access_token = "";
var img_url = "";
var first_name = "";
var id = "";

function saveToken(accessToken) {
  access_token = accessToken;
}

// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {

  // Logged into your app and Facebook.
  if (response.status === 'connected') {
    saveToken(response.authResponse.accessToken);
    getProfileInfo();
    updateView();
  } else if (response.status === 'not_authorized') {
    /* TODO */
  } else {
    FB.login(function(response) {
      if (response.authResponse ) {
        saveToken(response.authResponse.accessToken);
        getProfileInfo();
        updateView();
      }
    }, {scope: 'user_about_me,user_location'});
  }
}

// This function is called when someone finishes with the Login
// Button.  See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
  FB.getLoginStatus(function(response) {
    statusChangeCallback(response);
  }, {scope: 'user_about_me,user_location'});
}

function getProfileInfo() {
  FB.api('/me?field=id,first_name,location', function(response) {
    first_name = response.first_name;
    id = response.id;
    $('#title').text("Hi " + first_name + ". Insert your health profile!");
  });

  FB.api("/me/picture?type=normal&height=120&width=120&redirect=false", function(response) {
    img_url = response.data.url;
    $('#fb-image').css('background-image', 'url(' + response.data.url + ')');
  });
}

function send_request(obj) {

  console.log(obj);

  var weight_obj = {"measureValue":"", "measureType":"weight"};
  var height_obj = {"measureValue":"", "measureType":"weight"};
  var url = "http://95.85.59.245:8086/dbservice/person/{id}/{measure}"

  // $.ajax({
  //     type: "POST",
  //     url: "/webservices/PodcastService.asmx/CreateMarkers",
  //     // The key needs to match your method's input parameter (case-sensitive).
  //     data: JSON.stringify({ Markers: markers }),
  //     contentType: "application/json; charset=utf-8",
  //     dataType: "json",
  //     success: function(data){alert(data);},
  //     failure: function(errMsg) {
  //         alert(errMsg);
  //     }
  // });

  $.getJSON("https://restindirectorservice.herokuapp.com/project-director/weather?callback=?&token=" + access_token, function(response_p1){

    console.log(response_p1);

    act1 = response_p1.result[0].activityplan;
    act2 = response_p1.result[1].activityplan;
    act3 = response_p1.result[2].activityplan;

    weather1 = response_p1.result[0].weather;
    weather2 = response_p1.result[1].weather;
    weather3 = response_p1.result[2].weather;

    $.getJSON("https://restindirectorservice.herokuapp.com/project-director/food?callback=?&token=" + access_token, function(response_p2){

      console.log(response_p2);

      bg = response_p2.result.foodPhoto.url;
      suggested_food = response_p2.result.suggestedFood.name;

      $('#form').hide();
      $('.shadow_overlay').show();
      $('#flickr_bg').css('background-image', 'url("'+ bg +'")');
      $('#quote').text(act1.phrase);
      $('.motivational_quote').show();
      $('#title').text(suggested_food);
      $('.subtitle').hide();
      $('.center').addClass('results');
      $('.scroll_down').show();

      $('#block-day-1 .wi').addClass('wi-'+weather1.weather.toLowerCase());
      $('#block-day-2 .wi').addClass('wi-'+weather2.weather.toLowerCase());
      $('#block-day-3 .wi').addClass('wi-'+weather3.weather.toLowerCase());

      $('#block-day-1 .calendar').text(act1.activity);
      $('#block-day-2 .calendar').text(act2.activity);
      $('#block-day-3 .calendar').text(act3.activity);
      $('#second').show();

    });
  });
}

function updateView() {
  $('.fb-login').hide();
  $('#fb-image').show();
  $('.subtitle').text("Height is in cm while Weight is in kg.");
  $('#form').show();
}
<commit_msg>post to REST db added<commit_after>var access_token = "";
var img_url = "";
var first_name = "";
var id = "";

function saveToken(accessToken) {
  access_token = accessToken;
}

// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {

  // Logged into your app and Facebook.
  if (response.status === 'connected') {
    saveToken(response.authResponse.accessToken);
    getProfileInfo();
    updateView();
  } else if (response.status === 'not_authorized') {
    /* TODO */
  } else {
    FB.login(function(response) {
      if (response.authResponse ) {
        saveToken(response.authResponse.accessToken);
        getProfileInfo();
        updateView();
      }
    }, {scope: 'user_about_me,user_location'});
  }
}

// This function is called when someone finishes with the Login
// Button.  See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
  FB.getLoginStatus(function(response) {
    statusChangeCallback(response);
  }, {scope: 'user_about_me,user_location'});
}

function getProfileInfo() {
  FB.api('/me?field=id,first_name,location', function(response) {
    first_name = response.first_name;
    id = response.id;
    $('#title').text("Hi " + first_name + ". Insert your health profile!");
  });

  FB.api("/me/picture?type=normal&height=120&width=120&redirect=false", function(response) {
    img_url = response.data.url;
    $('#fb-image').css('background-image', 'url(' + response.data.url + ')');
  });
}

function send_request(obj) {

  var weight_obj = {"measureValue": parseFloat(obj.weight), "measureType":"weight"};
  var height_obj = {"measureValue": parseFloat(obj.height), "measureType":"weight"};
  var url_w = "http://95.85.59.245:8086/dbservice/person/" + id + "/weight";
  var url_h = "http://95.85.59.245:8086/dbservice/person/" + id + "/height";

  $.ajax({
      type: "POST",
      url: url_w,
      data: JSON.stringify(weight_obj),
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(data) {
        console.log(data);
      },
      failure: function(errMsg) {
        console.log(errMsg);
      }
  });

  $.ajax({
      type: "POST",
      url: url_h,
      data: JSON.stringify(height_obj),
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(data) {
        console.log(data);
      },
      failure: function(errMsg) {
        console.log(errMsg);
      }
  });

  // $.getJSON("https://restindirectorservice.herokuapp.com/project-director/weather?callback=?&token=" + access_token, function(response_p1){

  //   console.log(response_p1);

  //   act1 = response_p1.result[0].activityplan;
  //   act2 = response_p1.result[1].activityplan;
  //   act3 = response_p1.result[2].activityplan;

  //   weather1 = response_p1.result[0].weather;
  //   weather2 = response_p1.result[1].weather;
  //   weather3 = response_p1.result[2].weather;

  //   $.getJSON("https://restindirectorservice.herokuapp.com/project-director/food?callback=?&token=" + access_token, function(response_p2){

  //     console.log(response_p2);

  //     bg = response_p2.result.foodPhoto.url;
  //     suggested_food = response_p2.result.suggestedFood.name;

  //     $('#form').hide();
  //     $('.shadow_overlay').show();
  //     $('#flickr_bg').css('background-image', 'url("'+ bg +'")');
  //     $('#quote').text(act1.phrase);
  //     $('.motivational_quote').show();
  //     $('#title').text(suggested_food);
  //     $('.subtitle').hide();
  //     $('.center').addClass('results');
  //     $('.scroll_down').show();

  //     $('#block-day-1 .wi').addClass('wi-'+weather1.weather.toLowerCase());
  //     $('#block-day-2 .wi').addClass('wi-'+weather2.weather.toLowerCase());
  //     $('#block-day-3 .wi').addClass('wi-'+weather3.weather.toLowerCase());

  //     $('#block-day-1 .calendar').text(act1.activity);
  //     $('#block-day-2 .calendar').text(act2.activity);
  //     $('#block-day-3 .calendar').text(act3.activity);
  //     $('#second').show();

  //   });
  // });
}

function updateView() {
  $('.fb-login').hide();
  $('#fb-image').show();
  $('.subtitle').text("Height is in cm while Weight is in kg.");
  $('#form').show();
}
<|endoftext|>