<commit_before>function LinearPerRatioModel(minRatio, perX){
  var start, target, epsilon = 0.01;
  return {
    setStartAttrs: function(_current, _target){
      if (target == _target) return;
      target = _target;
      start = _current;
    },
    getNextValue: function(current){
    //start    current             target
    //|-----------|------------------|
      var max = target - start + 0.0;
      var val = target - current;
      if (max == 0) return target;
      var per = val / max;
      var change = val * (minRatio + (1 - per) / perX);
      if (Math.abs(change) < epsilon) return current;
      return current + change;
    }
  };
}

function createPPBar(x, y, min, max, currentVal){
  var targetVal, animator = new LinearPerRatioModel(0.045, 8);
  var blood = sceneManager.getScene().spriteFactory.create('images/bar/blood.png', {
    attrs: {x: x + 6, y: y - 3, scale: 1, patternSpeed: 0, loopPattern: true, fixedPosition: true },
    callbacks: {
      getOx: function(s){ return 0; },
      getOy: function(s){ return 0; },
      onUpdate: function(){
        if (currentVal == targetVal) return;
        setCurrentVal(animator.getNextValue(currentVal));
      }
    }
  });
  var outlayer = sceneManager.getScene().spriteFactory.create('images/bar/outlayer.png', {
    attrs: {x: x, y: y, scale: 1, patternSpeed: 0, loopPattern: true, fixedPosition: true },
    callbacks: {
      getOx: function(s){ return 0; },
      getOy: function(s){ return 0; },
      onUpdate: function(){}
    }
  });
  function setValue(val){
    val = Math.max(Math.min(val, max), min);
    targetVal = val;
    if (currentVal == undefined) setCurrentVal(targetVal);
    if (currentVal != targetVal) animator.setStartAttrs(currentVal, targetVal);
  }
  function setCurrentVal(val){
    currentVal = val;
    blood.attrs.ratio = (currentVal - min) / (max - min);
  }
  setValue(currentVal == undefined ? min : currentVal);
  return {
    setValue: setValue,
    addValue: function(add){ setValue(currentVal + add); },
    destroy: function(){
      blood.destroy();
      outlayer.destroy();
      blood = undefined;
      outlayer = undefined;
    }
  }
}
function createPlayer(VIEWPORT_X, BASE_Y, callbacks){
  var player, vx = 0, vy = 0;
  var currentStatus, STATUSES = {};
  function changeStatus(status){
    if (currentStatus) currentStatus.onLeft();
    currentStatus = status;
    status.initialize();
  }
  IDLE_PATH = 'images/characters/wolf.png';
  JUMP_PATH = 'images/characters/wolf_jump.png';
  STATUSES.IDLE = new function(){
    var singCD = 0;
    return {
      initialize: function(){
        player.setPath(IDLE_PATH);
      },
      updateInput: function(character){
        if (singCD > 0) singCD -= 1;
        if (Input.pressed(Input.KEYS.SPACE) && singCD == 0){
          singCD = 15;
          return changeStatus(STATUSES.SING);
        }
        if (Input.pressed(Input.KEYS.RIGHT)) vx = 6;
        else if (Input.pressed(Input.KEYS.LEFT)) vx = 3;
        else vx = 4;
        if (Input.pressed(Input.KEYS.UP) && character.attrs.y == BASE_Y){
          player.setPath(JUMP_PATH);
          vy = 15;
        }
      },
      update: function(character){
        if (character.attrs.y > BASE_Y) vy -= 1; //gravity
      },
      onLeft: function(){

      }
    };
  };
  STATUSES.SING = new function(){
    var singCounter, ppbar;
    return {
      initialize: function(){
        ppbar = createPPBar(100, 300, 0, 80);
        player.setPath(JUMP_PATH);
        singCounter = 30;
        var singEffect = sceneManager.getScene().spriteFactory.create('images/characters/sing_effect.png', {
          attrs: {
            x: 0,
            y: 0,
            scale: 4,
            loopPattern: false,
            patternSpeed: 50
          },
          callbacks: {
            getOx: function(s){ return s / 2; },
            getOy: function(s){ return s / 2; },
            onUpdate: function(){
              singEffect.attrs.x = player.attrs.x;
              singEffect.attrs.y = player.attrs.y + 20;
            }
          }
        });
        vy = 6;
      },
      updateInput: function(character){
        if (Input.pressed(Input.KEYS.A)){ ppbar.setValue(45); }
        if (Input.pressed(Input.KEYS.S)){ ppbar.setValue(55); }
        if (Input.pressed(Input.KEYS.D)){ ppbar.setValue(65); }
        // if (Input.pressed(Input.KEYS.A)){ character.shoot('images/characters/magic_ball-01.png', 'water' ); changeStatus(STATUSES.IDLE); }
        // if (Input.pressed(Input.KEYS.S)){ character.shoot('images/characters/magic_ball-02.png', 'fire'  ); changeStatus(STATUSES.IDLE); }
        // if (Input.pressed(Input.KEYS.D)){ character.shoot('images/characters/magic_ball-03.png', 'ground'); changeStatus(STATUSES.IDLE); }
      },
      update: function(character){
        if ((singCounter -= 1) < 0) return changeStatus(STATUSES.IDLE);
        vy *= 0.9;
      },
      onLeft: function(){
        ppbar.destroy();
        ppbar = undefined;
      }
    };
  };
  player = sceneManager.getScene().characterFactory.create('images/characters/wolf.png', {
    attrs: {
      character: {
        race: 1,
        hp: 100,
        atk: 100,
        hitRange: 3 //not using
      },
      onKilled: callbacks.onKilled,
      onDestroy: callbacks.onDestroy,
      x: VIEWPORT_X,
      y: BASE_Y,
      scale: 0.5,
      loopPattern: true,
      patternSpeed: 12
    },
    callbacks: {
      getOx: function(s){ return s / 2; },
      getOy: function(s){ return s; },
      onUpdate: function(){
        if (player.image){ //allow control after image loaded
          currentStatus.updateInput(player);
          currentStatus.update(player);
        }
        player.attrs.x += vx;
        player.attrs.y += vy;
        if (player.attrs.y < BASE_Y){
          player.attrs.y = BASE_Y;
          vy = 0;
          player.setPath(IDLE_PATH);
        }
      }
    }
  });
  changeStatus(STATUSES.IDLE);
  return player;
}
<commit_msg>shoot according to bar<commit_after>function LinearPerRatioModel(minRatio, perX){
  var start, target, epsilon = 0.01;
  return {
    setStartAttrs: function(_current, _target){
      if (target == _target) return;
      target = _target;
      start = _current;
    },
    getNextValue: function(current){
    //start    current             target
    //|-----------|------------------|
      var max = target - start + 0.0;
      var val = target - current;
      if (max == 0) return target;
      var per = val / max;
      var change = val * (minRatio + (1 - per) / perX);
      if (Math.abs(change) < epsilon) return current;
      return current + change;
    }
  };
}

function createPPBar(x, y, min, max, currentVal){
  var targetVal, animator = new LinearPerRatioModel(0.1, 4);
  var blood = sceneManager.getScene().spriteFactory.create('images/bar/blood.png', {
    attrs: {x: x + 6, y: y - 3, scale: 1, patternSpeed: 0, loopPattern: true, fixedPosition: true },
    callbacks: {
      getOx: function(s){ return 0; },
      getOy: function(s){ return 0; },
      onUpdate: function(){
        if (currentVal == targetVal) return;
        setCurrentVal(animator.getNextValue(currentVal));
      }
    }
  });
  var outlayer = sceneManager.getScene().spriteFactory.create('images/bar/outlayer.png', {
    attrs: {x: x, y: y, scale: 1, patternSpeed: 0, loopPattern: true, fixedPosition: true },
    callbacks: {
      getOx: function(s){ return 0; },
      getOy: function(s){ return 0; },
      onUpdate: function(){}
    }
  });
  function setValue(val){
    val = Math.max(Math.min(val, max), min);
    targetVal = val;
    if (currentVal == undefined) setCurrentVal(targetVal);
    if (currentVal != targetVal) animator.setStartAttrs(currentVal, targetVal);
  }
  function setCurrentVal(val){
    currentVal = val;
    blood.attrs.ratio = (currentVal - min) / (max - min);
  }
  setValue(currentVal == undefined ? min : currentVal);
  return {
    setValue: setValue,
    getCurrentValue: function(){ return currentVal; },
    destroy: function(){
      blood.destroy();
      outlayer.destroy();
      blood = undefined;
      outlayer = undefined;
    }
  }
}
function createPlayer(VIEWPORT_X, BASE_Y, callbacks){
  var player, vx = 0, vy = 0;
  var currentStatus, STATUSES = {};
  function changeStatus(status){
    if (currentStatus) currentStatus.onLeft();
    currentStatus = status;
    status.initialize();
  }
  IDLE_PATH = 'images/characters/wolf.png';
  JUMP_PATH = 'images/characters/wolf_jump.png';
  STATUSES.IDLE = new function(){
    var singCD = 0;
    return {
      initialize: function(){
        player.setPath(IDLE_PATH);
      },
      updateInput: function(character){
        if (singCD > 0) singCD -= 1;
        if (Input.pressed(Input.KEYS.SPACE) && singCD == 0){
          singCD = 15;
          return changeStatus(STATUSES.SING);
        }
        if (Input.pressed(Input.KEYS.RIGHT)) vx = 6;
        else if (Input.pressed(Input.KEYS.LEFT)) vx = 3;
        else vx = 4;
        if (Input.pressed(Input.KEYS.UP) && character.attrs.y == BASE_Y){
          player.setPath(JUMP_PATH);
          vy = 15;
        }
      },
      update: function(character){
        if (character.attrs.y > BASE_Y) vy -= 1; //gravity
      },
      onLeft: function(){

      }
    };
  };
  STATUSES.SING = new function(){
    var singCounter, ppbar;
    return {
      initialize: function(){
        ppbar = createPPBar(100, 300, 0, 80);
        player.setPath(JUMP_PATH);
        singCounter = 30;
        var singEffect = sceneManager.getScene().spriteFactory.create('images/characters/sing_effect.png', {
          attrs: {
            x: 0,
            y: 0,
            scale: 4,
            loopPattern: false,
            patternSpeed: 50
          },
          callbacks: {
            getOx: function(s){ return s / 2; },
            getOy: function(s){ return s / 2; },
            onUpdate: function(){
              singEffect.attrs.x = player.attrs.x;
              singEffect.attrs.y = player.attrs.y + 20;
            }
          }
        });
        vy = 6;
      },
      updateInput: function(character){
        if (Input.pressed(Input.KEYS.A)){ ppbar.setValue(45); }
        if (Input.pressed(Input.KEYS.S)){ ppbar.setValue(55); }
        if (Input.pressed(Input.KEYS.D)){ ppbar.setValue(65); }
      },
      update: function(character){
        if ((singCounter -= 1) < 0){
          var val = ppbar.getCurrentValue();
          if (val >= 40 && val < 50) character.shoot('images/characters/magic_ball-01.png', 'water' );
          if (val >= 50 && val < 60) character.shoot('images/characters/magic_ball-02.png', 'fire'  );
          if (val >= 60 && val < 70) character.shoot('images/characters/magic_ball-03.png', 'ground');
          return changeStatus(STATUSES.IDLE);
        }
        vy *= 0.9;
      },
      onLeft: function(){
        ppbar.destroy();
        ppbar = undefined;
      }
    };
  };
  player = sceneManager.getScene().characterFactory.create('images/characters/wolf.png', {
    attrs: {
      character: {
        race: 1,
        hp: 100,
        atk: 100,
        hitRange: 3 //not using
      },
      onKilled: callbacks.onKilled,
      onDestroy: callbacks.onDestroy,
      x: VIEWPORT_X,
      y: BASE_Y,
      scale: 0.5,
      loopPattern: true,
      patternSpeed: 12
    },
    callbacks: {
      getOx: function(s){ return s / 2; },
      getOy: function(s){ return s; },
      onUpdate: function(){
        if (player.image){ //allow control after image loaded
          currentStatus.updateInput(player);
          currentStatus.update(player);
        }
        player.attrs.x += vx;
        player.attrs.y += vy;
        if (player.attrs.y < BASE_Y){
          player.attrs.y = BASE_Y;
          vy = 0;
          player.setPath(IDLE_PATH);
        }
      }
    }
  });
  changeStatus(STATUSES.IDLE);
  return player;
}
<|endoftext|>


<commit_before>var player = {
    health: 25, maxhealth: 25,
    atk: 3, def: 2, luck: 0.7,
    level: 1, exp: 0, nextExp: 4, totalExp: 0,
    monies: 1000, playTime: 0,
    clearedEntities: [], questsCleared: [], activeQuests: {},
    lastInn: "start",
    equipment: {
        weapon: "!babySickle",
        compost: "!weakCompost",
        gloves: null,
        soil: null,
        armor: null
    },
    getPlayTimeString: function() {
        var time = this.playTime;
        var hours = Math.floor(time / 3600);
        time -= hours * 3600;
        var minutes = Math.floor(time / 60);
        time -= minutes * 60;
        return (hours < 10 ? "0" : "") + hours + ":" + (minutes < 10 ? "0" : "") + minutes + ":" + (time < 10 ? "0" : "") + time;
    },
    inventory: [
        ["specialgrapes", 1], ["carrot", 6], ["beet", 4], ["!weakCompost", 1], ["!babySickle", 1] // ACTUAL STARTING INVENTORY
        ["_shooter", 2], ["_hotspot", 1], ["_modulator", 1], ["battery", 4], ["spear", 5],
        ["!baseSickle", 1], ["!goodSickle", 1], ["!weakCompost", 1], ["!strongCompost", 1], ["!weakGloves", 1], ["!pairGloves", 1],
        ["!weakSoil", 1], ["!fortSoil", 1], ["!balancedGreenhouse", 1], ["!amplifyingGreenhouse", 1]
        ,["shiitake", 1], ["milkcap", 1], ["portobello", 1], ["egg", 3], ["_lake", 9], ["net", 3], ["rod", 5], ["goodrod", 5], ["metalrod", 5],
        ["_paddy", 6], ["rice", 2], ["arborio", 2], ["blackrice", 2]
        , ["pineapple", 5], ["leek", 2]
        ,["apple", 20], ["lemon", 1], ["rhubarb", 8],  ["grapes", 3]*/
        //["carrot", 69], ["pineapple", 4],["leek", 2],
    ],
    gridWidth: 3, gridHeight: 3, gridLevel: "n",
    itemGrid: null,
    hasQuest: function(q) { return player.activeQuests[q] !== undefined; },
    completedQuest: function(q) { return player.questsCleared.indexOf(q) >= 0; },
    hasItem: function(item, amount) {
        amount = amount || 1;
        for(var i = 0; i < player.inventory.length; i++) {
            if(player.inventory[i][0] === item && player.inventory[i][1] >= amount) { return true; }
        }
        return false;
    },
    isEquipped: function(item) {
        return this.equipment.weapon === item || this.equipment.compost === item || this.equipment.gloves === item || this.equipment.soil === item || this.equipment.armor === item;
    },
    expandGrid: function (newwidth, newheight, newLevel) {
        var oldwidth = this.gridWidth, oldheight = this.gridHeight;
        if(this.itemGrid === null) {
            this.itemGrid = [];
            oldwidth = 0; oldheight = 0;
        }
        for(var x = 0; x < newwidth; x++) {
            if(x < oldwidth) {
                for(var y = oldheight; y < newheight; y++) {
                    this.itemGrid[x].push(null);
                }
            } else {
                var row = [];
                for(var y = 0; y < newheight; y++) { row.push(null); }
                this.itemGrid.push(row);
            }
        }
        this.gridWidth = newwidth;
        this.gridHeight = newheight;
        this.gridLevel = newLevel;
    },
    getRandomLuckyNumber: function(inverse) {
        var num = (Math.random() * player.luck);
        if(inverse) { num = 1 - num; }
        return num;
    },
    initGridDimensions: function() { if(this.itemGrid === null) { this.itemGrid = combat.getGrid(this.gridWidth, this.gridHeight); } },
    addExp: function(n) { this.totalExp += n; if(this.level < 50) { this.exp += n; } },
    levelUp: function() {
        this.level++;
        this.exp -= this.nextExp;
        this.maxhealth = Math.floor(this.maxhealth * 1.1);
        this.health = this.maxhealth;
        this.atk = Math.ceil(this.atk + Math.log10(this.level));
        this.def = Math.ceil(this.def + Math.log10(this.level));
        this.luck = 0.7 - (this.level / 400);
        this.nextExp = Math.floor(this.level * this.level * 5 * Math.pow(1.02, this.level - 2));
        this.getLevelUpItemBonuses();
    },
    canMelee: function(numEnemyCrops) {
        if(player.equipment.weapon === null) { return false; }
        if(GetEquipment(player.equipment.weapon).noEnemies && numEnemyCrops === 0) { return false; }
        return true;
    },
    getLevelUpItemBonuses: function() {
        switch(this.level) {
            case 2:
                this.increaseItem("carrot", 3);
                this.increaseItem("beet", 3);
                break;
            case 3:
                this.increaseItem("carrot", 4);
                this.increaseItem("beet", 2);
                this.increaseItem("ginger");
                break;
        }
    },
    canAttackAfterPlanting: function() {
        if(this.equipment.gloves === null) { return 0; }
        var equipInfo = GetEquipment(this.equipment.gloves);
        return equipInfo.canAttack;
    },
    getCompostMax: function() {
        if(this.equipment.compost === null) { return 0; }
        var equipInfo = GetEquipment(this.equipment.compost);
        return equipInfo.amount;
    },
    getCropSpeedMultiplier: function() {
        if(this.equipment.soil === null) { return 1; }
        var equipInfo = GetEquipment(this.equipment.soil);
        return (equipInfo.speed + 1);
    },
    getPlantingTurns: function() {
        if(this.equipment.gloves === null) { return 1; }
        var equipInfo = GetEquipment(this.equipment.gloves);
        return equipInfo.amount;
    },
    canAttackWithCompost: function() {
        if(this.equipment.compost === null) { return false; }
        var equipInfo = GetEquipment(this.equipment.compost);
        return equipInfo.canAttack;
    },
    canSickleCrops: function() {
        if(this.equipment.weapon === null) { return false; }
        var equipInfo = GetEquipment(this.equipment.weapon);
        return equipInfo.targetCrops;
    },
    canAttackPeople: function() {
        if(this.equipment.weapon === null) { return true; }
        var equipInfo = GetEquipment(this.equipment.weapon);
        return !equipInfo.noEnemies;
    },
    getSickleAttackBonus: function(season) {
        if(this.equipment.weapon === null) { return 0; }
        var equipInfo = GetEquipment(this.equipment.weapon);
        var bonus = equipInfo.power;
        if(season === 0 && equipInfo.sp) { bonus += equipInfo.sp; }
        else if(season === 1 && equipInfo.su) { bonus += equipInfo.su; }
        else if(season === 2 && equipInfo.au) { bonus += equipInfo.au; }
        else if(season === 3 && equipInfo.wi) { bonus += equipInfo.wi; }
        return bonus;
    },
    decreaseItem: function(name) {
        var idx = -1;
        for(var i = 0; i < player.inventory.length; i++) {
            if(player.inventory[i][0] === name) {
                player.inventory[i][1] -= 1;
                idx = i;
                break;
            }
        }
        if(player.inventory[idx][1] == 0) {
            player.inventory.splice(idx, 1);
            return false;
        }
        return true;
    },
    increaseItem: function(name, amount) {
        for(var i = 0; i < player.inventory.length; i++) {
            if(player.inventory[i][0] === name) {
                player.inventory[i][1] += (amount || 1);
                return;
            }
        }
        player.inventory.push([name, (amount || 1)]);
    }
};<commit_msg>fixed melee check<commit_after>var player = {
    health: 25, maxhealth: 25,
    atk: 3, def: 2, luck: 0.7,
    level: 1, exp: 0, nextExp: 4, totalExp: 0,
    monies: 1000, playTime: 0,
    clearedEntities: [], questsCleared: [], activeQuests: {},
    lastInn: "start",
    equipment: {
        weapon: "!babySickle",
        compost: "!weakCompost",
        gloves: null,
        soil: null,
        armor: null
    },
    getPlayTimeString: function() {
        var time = this.playTime;
        var hours = Math.floor(time / 3600);
        time -= hours * 3600;
        var minutes = Math.floor(time / 60);
        time -= minutes * 60;
        return (hours < 10 ? "0" : "") + hours + ":" + (minutes < 10 ? "0" : "") + minutes + ":" + (time < 10 ? "0" : "") + time;
    },
    inventory: [
        ["specialgrapes", 1], ["carrot", 6], ["beet", 4], ["!weakCompost", 1], ["!babySickle", 1] // ACTUAL STARTING INVENTORY
        ["_shooter", 2], ["_hotspot", 1], ["_modulator", 1], ["battery", 4], ["spear", 5],
        ["!baseSickle", 1], ["!goodSickle", 1], ["!weakCompost", 1], ["!strongCompost", 1], ["!weakGloves", 1], ["!pairGloves", 1],
        ["!weakSoil", 1], ["!fortSoil", 1], ["!balancedGreenhouse", 1], ["!amplifyingGreenhouse", 1]
        ,["shiitake", 1], ["milkcap", 1], ["portobello", 1], ["egg", 3], ["_lake", 9], ["net", 3], ["rod", 5], ["goodrod", 5], ["metalrod", 5],
        ["_paddy", 6], ["rice", 2], ["arborio", 2], ["blackrice", 2]
        , ["pineapple", 5], ["leek", 2]
        ,["apple", 20], ["lemon", 1], ["rhubarb", 8],  ["grapes", 3]*/
        //["carrot", 69], ["pineapple", 4],["leek", 2],
    ],
    gridWidth: 3, gridHeight: 3, gridLevel: "n",
    itemGrid: null,
    hasQuest: function(q) { return player.activeQuests[q] !== undefined; },
    completedQuest: function(q) { return player.questsCleared.indexOf(q) >= 0; },
    hasItem: function(item, amount) {
        amount = amount || 1;
        for(var i = 0; i < player.inventory.length; i++) {
            if(player.inventory[i][0] === item && player.inventory[i][1] >= amount) { return true; }
        }
        return false;
    },
    isEquipped: function(item) {
        return this.equipment.weapon === item || this.equipment.compost === item || this.equipment.gloves === item || this.equipment.soil === item || this.equipment.armor === item;
    },
    expandGrid: function (newwidth, newheight, newLevel) {
        var oldwidth = this.gridWidth, oldheight = this.gridHeight;
        if(this.itemGrid === null) {
            this.itemGrid = [];
            oldwidth = 0; oldheight = 0;
        }
        for(var x = 0; x < newwidth; x++) {
            if(x < oldwidth) {
                for(var y = oldheight; y < newheight; y++) {
                    this.itemGrid[x].push(null);
                }
            } else {
                var row = [];
                for(var y = 0; y < newheight; y++) { row.push(null); }
                this.itemGrid.push(row);
            }
        }
        this.gridWidth = newwidth;
        this.gridHeight = newheight;
        this.gridLevel = newLevel;
    },
    getRandomLuckyNumber: function(inverse) {
        var num = (Math.random() * player.luck);
        if(inverse) { num = 1 - num; }
        return num;
    },
    initGridDimensions: function() { if(this.itemGrid === null) { this.itemGrid = combat.getGrid(this.gridWidth, this.gridHeight); } },
    addExp: function(n) { this.totalExp += n; if(this.level < 50) { this.exp += n; } },
    levelUp: function() {
        this.level++;
        this.exp -= this.nextExp;
        this.maxhealth = Math.floor(this.maxhealth * 1.1);
        this.health = this.maxhealth;
        this.atk = Math.ceil(this.atk + Math.log10(this.level));
        this.def = Math.ceil(this.def + Math.log10(this.level));
        this.luck = 0.7 - (this.level / 400);
        this.nextExp = Math.floor(this.level * this.level * 5 * Math.pow(1.02, this.level - 2));
        this.getLevelUpItemBonuses();
    },
    canMelee: function(numEnemyCrops) {
        if(player.equipment.weapon === null) { return false; }
        var weapon = GetEquipment(player.equipment.weapon);
        if(numEnemyCrops === 0) {
            return !weapon.noEnemies;
        } else {
            return weapon.targetCrops;
        }
    },
    getLevelUpItemBonuses: function() {
        switch(this.level) {
            case 2:
                this.increaseItem("carrot", 3);
                this.increaseItem("beet", 3);
                break;
            case 3:
                this.increaseItem("carrot", 4);
                this.increaseItem("beet", 2);
                this.increaseItem("ginger");
                break;
        }
    },
    canAttackAfterPlanting: function() {
        if(this.equipment.gloves === null) { return 0; }
        var equipInfo = GetEquipment(this.equipment.gloves);
        return equipInfo.canAttack;
    },
    getCompostMax: function() {
        if(this.equipment.compost === null) { return 0; }
        var equipInfo = GetEquipment(this.equipment.compost);
        return equipInfo.amount;
    },
    getCropSpeedMultiplier: function() {
        if(this.equipment.soil === null) { return 1; }
        var equipInfo = GetEquipment(this.equipment.soil);
        return (equipInfo.speed + 1);
    },
    getPlantingTurns: function() {
        if(this.equipment.gloves === null) { return 1; }
        var equipInfo = GetEquipment(this.equipment.gloves);
        return equipInfo.amount;
    },
    canAttackWithCompost: function() {
        if(this.equipment.compost === null) { return false; }
        var equipInfo = GetEquipment(this.equipment.compost);
        return equipInfo.canAttack;
    },
    canSickleCrops: function() {
        if(this.equipment.weapon === null) { return false; }
        var equipInfo = GetEquipment(this.equipment.weapon);
        return equipInfo.targetCrops;
    },
    canAttackPeople: function() {
        if(this.equipment.weapon === null) { return true; }
        var equipInfo = GetEquipment(this.equipment.weapon);
        return !equipInfo.noEnemies;
    },
    getSickleAttackBonus: function(season) {
        if(this.equipment.weapon === null) { return 0; }
        var equipInfo = GetEquipment(this.equipment.weapon);
        var bonus = equipInfo.power;
        if(season === 0 && equipInfo.sp) { bonus += equipInfo.sp; }
        else if(season === 1 && equipInfo.su) { bonus += equipInfo.su; }
        else if(season === 2 && equipInfo.au) { bonus += equipInfo.au; }
        else if(season === 3 && equipInfo.wi) { bonus += equipInfo.wi; }
        return bonus;
    },
    decreaseItem: function(name) {
        var idx = -1;
        for(var i = 0; i < player.inventory.length; i++) {
            if(player.inventory[i][0] === name) {
                player.inventory[i][1] -= 1;
                idx = i;
                break;
            }
        }
        if(player.inventory[idx][1] == 0) {
            player.inventory.splice(idx, 1);
            return false;
        }
        return true;
    },
    increaseItem: function(name, amount) {
        for(var i = 0; i < player.inventory.length; i++) {
            if(player.inventory[i][0] === name) {
                player.inventory[i][1] += (amount || 1);
                return;
            }
        }
        player.inventory.push([name, (amount || 1)]);
    }
};<|endoftext|>


<commit_before>var popups = [];
var mousein = false;
function setup() {
	var w = document.width;
	var size = 300;
	var height = 500;
	var settings = {'z-index': 999999999,
					'width': size,
					'height': height,
					'position': 'fixed',
					'left': w-size,
					'top': 0};
	var tray = $(document.createElement("div")).css(settings).attr('id', 'tray');

	$(document.body).append(tray);
}

function popup(t) {
	var h = popups.length;
	var tray = $('#tray');
	var imgUrl = chrome.extension.getURL("/img/bg-nav.png");
	console.log("URL: " + imgUrl);
	var settings = {'border': 'solid 3px white',
			'border-radius': 20,
			'background-image': 'url("' + imgUrl + '")',
			'opacity': .7,
			'width': 200,
			'height': 100,
			'top': h*120,
			'position': 'absolute',
			'left': 50};
	var newDiv = $(document.createElement("div")).css(settings);

	var innerSet = {'color': 'black',
					'top': 25,
					'display': 'block',
					'position': 'absolute',
					'text-align': 'center'
					};

	var innerDiv = $(document.createElement("div")).css(innerSet).text("Can we track activity from \n" + t + "?");
	var table = $(document.createElement('table')).css({'margin-left': 'auto',
					'margin-right': 'auto'});
	var tr = $(document.createElement('tr'));
	var td1 = $(document.createElement('td'));
	var td2 = $(document.createElement('td'));
	function passMessage(action,url,el){
		return function(){
			if (el != undefined) {
				console.log("HERE");
				$(el).remove();
			}
			var message = {"action": action,
							"url": url};
			chrome.extension.sendMessage(JSON.stringify(message));
		}
	}
	$(td1).append(addButton("Allow").click(passMessage('whitelist', t, newDiv)));
	$(td2).append(addButton("No").click(passMessage('blacklist', t, newDiv)));
	$(tr).append(td1);
	$(tr).append(td2);
	$(table).append(tr);
	$(innerDiv).append(table);
	$(newDiv).append(innerDiv);
	$(tray).append(newDiv);
	var t = setTimeout(function() {fade(newDiv)}, 2000);
	$(newDiv).hover(function() {
		console.log("CLEARED");
		mousein = true;
		clearInterval(t);
		$(newDiv).stop();
		$(newDiv).css('opacity', 1.0);
		//$(newDiv).css('border', 'solid 2px white');
	})
	$(newDiv).mouseleave(function() {
		mousein = false;
		t = setTimeout(function() {fade(newDiv)}, 2000);
	})
	popups.push(newDiv);
}

function addButton(t) {
	var b = $(document.createElement('input')).attr({'type':'button','value': t});
	$(b).click(function() {

	});
	return b
}

function fade(el) {
	$(el).fadeOut(1000,function() {
		$(popups.shift()).remove();
		for (var i = 0; i < popups.length; i++) {
			h = parseInt($(popups[i]).css('top'))-120;
			$(popups[i]).animate({'top': h},500);
		};
	});
}

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
	var action = request['action'];
	if (action == 'prompt') {
		setup();
		var uri = new URI(document.location)
		var hostname = uri.hostname();
		console.log(hostname);
		popup(hostname);
	}
})<commit_msg>fixed bug where prompts would not be fired<commit_after>var popups = [];
var mousein = false;
function setup() {
	var w = document.width;
	var size = 300;
	var height = 500;
	var settings = {'z-index': 999999999,
					'width': size,
					'height': height,
					'position': 'fixed',
					'left': w-size,
					'top': 0};
	var tray = $(document.createElement("div")).css(settings).attr('id', 'tray');

	$(document.body).append(tray);
}

function popup(t) {
	var h = popups.length;
	var tray = $('#tray');
	var imgUrl = chrome.extension.getURL("/img/bg-nav.png");
	console.log("URL: " + imgUrl);
	var settings = {'border': 'solid 3px white',
			'border-radius': 20,
			'background-image': 'url("' + imgUrl + '")',
			'opacity': .7,
			'width': 200,
			'height': 100,
			'top': h*120,
			'position': 'absolute',
			'left': 50};
	var newDiv = $(document.createElement("div")).css(settings);

	var innerSet = {'color': 'black',
					'top': 25,
					'display': 'block',
					'position': 'absolute',
					'text-align': 'center'
					};

	var innerDiv = $(document.createElement("div")).css(innerSet).text("Can we track activity from \n" + t + "?");
	var table = $(document.createElement('table')).css({'margin-left': 'auto',
					'margin-right': 'auto'});
	var tr = $(document.createElement('tr'));
	var td1 = $(document.createElement('td'));
	var td2 = $(document.createElement('td'));
	function passMessage(action,url,el){
		return function(){
			if (el != undefined) {
				console.log("HERE");
				$(el).remove();
				popups.shift();
			}
			var message = {"action": action,
							"url": url};
			chrome.extension.sendMessage(JSON.stringify(message));
		}
	}
	$(td1).append(addButton("Allow").click(passMessage('whitelist', t, newDiv)));
	$(td2).append(addButton("No").click(passMessage('blacklist', t, newDiv)));
	$(tr).append(td1);
	$(tr).append(td2);
	$(table).append(tr);
	$(innerDiv).append(table);
	$(newDiv).append(innerDiv);
	$(tray).append(newDiv);
	var t = setTimeout(function() {fade(newDiv)}, 2000);
	$(newDiv).hover(function() {
		console.log("CLEARED");
		mousein = true;
		clearInterval(t);
		$(newDiv).stop();
		$(newDiv).css('opacity', 1.0);
		//$(newDiv).css('border', 'solid 2px white');
	})
	$(newDiv).mouseleave(function() {
		mousein = false;
		t = setTimeout(function() {fade(newDiv)}, 2000);
	})
	popups.push(newDiv);
}

function addButton(t) {
	var b = $(document.createElement('input')).attr({'type':'button','value': t});
	$(b).click(function() {

	});
	return b
}

function fade(el) {
	$(el).fadeOut(1000,function() {
		$(popups.shift()).remove();
		for (var i = 0; i < popups.length; i++) {
			h = parseInt($(popups[i]).css('top'))-120;
			$(popups[i]).animate({'top': h},500);
		};
	});
}

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
	var action = request['action'];
	if (action == 'prompt') {
		console.log("RECEIVED");
		setup();
		var uri = new URI(document.location)
		var hostname = uri.hostname();
		console.log(hostname);
		popup(hostname);
	}
})<|endoftext|>


<commit_before>/** @fileOverview Routing functionality */

/**
 * @constructor
 * @class The main routing class. Used by {@link ConnectionManager} instances to route
 * messages through the user network.
 *
 * @param id ID of the local peer
 * @param fallbackSignaling
 */
Router = function(id, fallbackSignaling, connectionManager) {
    if(!(this instanceof Router)) {
        return new Router();
    }

    this._peerTable = {};
    this._fallbackSignaling = fallbackSignaling;
    this._fallbackSignaling.onmessage = this.onmessage.bind(this);
    this._connectionManager = connectionManager;
    this._id = id;
    this._messageCallbacks = {};
    this._monitorCallback = null;
    this.registerDeliveryCallback('discovery-answer', this.onDiscoveryAnswerMessage.bind(this));
    this.registerDeliveryCallback('discovery-request', this.onDiscoveryRequestMessage.bind(this));

    return this;
};

Router.prototype = {

    /**
     * Add a peer to the peer table.
     *
     * @param peer {Peer} The peer to add.
     * @todo add test for onclosedconnection behaviour
     */
    addPeer: function(peer) {
        this._peerTable[peer.id] = peer;
        peer.dataChannel.onmessage = this.onmessage.bind(this);
        peer.peerConnection.onclosedconnection = this.removePeer.bind(this, peer);
        if(Object.keys(this._peerTable).length === 1) {
            // ask first peer for its neighbours
            this.discoverNeighbours(peer);
        }
    },

    /**
     * Remove a peer from the peer table.
     *
     * @param peer {Peer} The peer to remove.
     * @todo disconnect peerConnection before removal
     */
    removePeer: function(peer) {
        delete this._peerTable[peer.id];
    },

    /**
     * Return a list of all peer ids currently in the routing table.
     *
     * @returns {Array}
     */
    getPeerIds: function() {
        var peers = [];
        var peer;
        for (peer in this._peerTable) {
            if (this._peerTable.hasOwnProperty(peer)) {
                peers.push(peer);
            }
        }
        return peers;
    },

    onmessage: function(msg) {
        try {
            this.forward(JSON.parse(msg.data));
        } catch(e) {
            throw Error('Unable to parse incoming message ' + JSON.stringify(msg.data) + ': ' + e);
        }
    },

    /**
     * Encapsulates message in router format and forwards them.
     *
     * @param to recipient
     * @param type the message type
     * @param payload the message payload
    */
    route: function(to, type, payload) {
        this.forward({to: to,
                      from: this._id,
                      type: type,
                      payload: payload
        });
    },

    /**
     * Forward message or deliver if recipient is me. This implementation
     * implies that we are using a fully meshed network where every peer
     * is connected to all other peers.
     *
     * @param msg {String} The message to route.
     */
    forward: function(msg) {
        if (typeof(this._monitorCallback) === 'function') {
            this._monitorCallback(msg);
        }
        if (this._id === msg.to) {
            this.deliver(msg);
            return;
        }
        var receiver = this._peerTable[msg.to];
        if (!(receiver instanceof Peer)) {
            this._fallbackSignaling.send(JSON.stringify(msg));
            return;
        }
        try {
            receiver.dataChannel.send(JSON.stringify(msg));
        } catch(e) {
            throw Error('Unable to route message to ' + msg.to + ' because the DataChannel connection failed.');
        }
    },

    /**
     * Deliver a message to this peer. Is called when the `to` field of
     * the message contains the id of this peer. Decides where to deliver
     * the message to by calling the registered callback using the `type`
     * field (e.g. webrtc connection/ neighbour discovery/ application) of
     * the message.
     *
     * @param msg {String}
     */
    deliver: function(msg) {
        if (!this._messageCallbacks[msg.type]) {
            throw Error('Unable to handle message of type ' + msg.type + ' from ' + msg.from + ' because no callback is registered.');
        } else {
            this._messageCallbacks[msg.type](msg.payload, msg.from);
        }
    },

    /**
     * Register a delivery callback. The registered callback gets
     * called when a specific type of message arrives with the `from`
     * field set to this peers' id.
     *
     * @param msgType {String} refers to the `type`-field of the message
     * this callback should respond to
     * @param callback {Function} The callback to call when a message of
     * the given type arrives
     */
    registerDeliveryCallback: function(msgType, callback) {
        this._messageCallbacks[msgType] = callback;
    },

    /**
     * Register a monitor callback. The registered callback gets
     * called when a message arrives with the `from` field set to
     * this peers' id.
     *
     * @param callback {Function} The callback to call when a message is delivered
     */
    registerMonitorCallback: function(callback) {
        this._monitorCallback = callback;
    },

    /**
     * Kick off neighbour discovery mechanism by sending a `discovery-request' message to
     * a connected peer.
     *
     * @param peer {Peer}
     * @todo implement
     */
    discoverNeighbours: function(peer) {
        this.route(peer.id, 'discovery-request', '');
    },

    /**
     * Gets called when a neighbour discovery answer message is received.
     *
     * @param msg {String} Message containing ids of another peers peer table.
     * @todo should this call the connection manager?
     */
    onDiscoveryAnswerMessage: function(msg, from) {
        var remoteIds = msg.payload;
        var i;
        for(i = 0; i < msg.length; i++) {
            if(msg[i] !== this._id) {
                this._connectionManager.connect(msg[i]);
            }
        }
    },

    /**
     * Answer a received neighbour discovery message. Respond with
     * known ids of all peers in the peerTable.
     *
     * @param msg {String} Message containing the discovery request from another peer.
     * @todo discovery message format
     */
    onDiscoveryRequestMessage: function(msg, from) {
        var peerIds = [],
        peer;
        for (peer in this._peerTable) {
            if (this._peerTable.hasOwnProperty(peer) && this._peerTable[peer] instanceof Peer) {
                peerIds.push(peer);
            }
        }
        this.route(from, 'discovery-answer', peerIds);
    }
};

if(typeof(module) !== 'undefined') {
    module.exports = Router;
}
<commit_msg>removed unused variable declaration<commit_after>/** @fileOverview Routing functionality */

/**
 * @constructor
 * @class The main routing class. Used by {@link ConnectionManager} instances to route
 * messages through the user network.
 *
 * @param id ID of the local peer
 * @param fallbackSignaling
 */
Router = function(id, fallbackSignaling, connectionManager) {
    if(!(this instanceof Router)) {
        return new Router();
    }

    this._peerTable = {};
    this._fallbackSignaling = fallbackSignaling;
    this._fallbackSignaling.onmessage = this.onmessage.bind(this);
    this._connectionManager = connectionManager;
    this._id = id;
    this._messageCallbacks = {};
    this._monitorCallback = null;
    this.registerDeliveryCallback('discovery-answer', this.onDiscoveryAnswerMessage.bind(this));
    this.registerDeliveryCallback('discovery-request', this.onDiscoveryRequestMessage.bind(this));

    return this;
};

Router.prototype = {

    /**
     * Add a peer to the peer table.
     *
     * @param peer {Peer} The peer to add.
     * @todo add test for onclosedconnection behaviour
     */
    addPeer: function(peer) {
        this._peerTable[peer.id] = peer;
        peer.dataChannel.onmessage = this.onmessage.bind(this);
        peer.peerConnection.onclosedconnection = this.removePeer.bind(this, peer);
        if(Object.keys(this._peerTable).length === 1) {
            // ask first peer for its neighbours
            this.discoverNeighbours(peer);
        }
    },

    /**
     * Remove a peer from the peer table.
     *
     * @param peer {Peer} The peer to remove.
     * @todo disconnect peerConnection before removal
     */
    removePeer: function(peer) {
        delete this._peerTable[peer.id];
    },

    /**
     * Return a list of all peer ids currently in the routing table.
     *
     * @returns {Array}
     */
    getPeerIds: function() {
        var peers = [];
        var peer;
        for (peer in this._peerTable) {
            if (this._peerTable.hasOwnProperty(peer)) {
                peers.push(peer);
            }
        }
        return peers;
    },

    onmessage: function(msg) {
        try {
            this.forward(JSON.parse(msg.data));
        } catch(e) {
            throw Error('Unable to parse incoming message ' + JSON.stringify(msg.data) + ': ' + e);
        }
    },

    /**
     * Encapsulates message in router format and forwards them.
     *
     * @param to recipient
     * @param type the message type
     * @param payload the message payload
    */
    route: function(to, type, payload) {
        this.forward({to: to,
                      from: this._id,
                      type: type,
                      payload: payload
        });
    },

    /**
     * Forward message or deliver if recipient is me. This implementation
     * implies that we are using a fully meshed network where every peer
     * is connected to all other peers.
     *
     * @param msg {String} The message to route.
     */
    forward: function(msg) {
        if (typeof(this._monitorCallback) === 'function') {
            this._monitorCallback(msg);
        }
        if (this._id === msg.to) {
            this.deliver(msg);
            return;
        }
        var receiver = this._peerTable[msg.to];
        if (!(receiver instanceof Peer)) {
            this._fallbackSignaling.send(JSON.stringify(msg));
            return;
        }
        try {
            receiver.dataChannel.send(JSON.stringify(msg));
        } catch(e) {
            throw Error('Unable to route message to ' + msg.to + ' because the DataChannel connection failed.');
        }
    },

    /**
     * Deliver a message to this peer. Is called when the `to` field of
     * the message contains the id of this peer. Decides where to deliver
     * the message to by calling the registered callback using the `type`
     * field (e.g. webrtc connection/ neighbour discovery/ application) of
     * the message.
     *
     * @param msg {String}
     */
    deliver: function(msg) {
        if (!this._messageCallbacks[msg.type]) {
            throw Error('Unable to handle message of type ' + msg.type + ' from ' + msg.from + ' because no callback is registered.');
        } else {
            this._messageCallbacks[msg.type](msg.payload, msg.from);
        }
    },

    /**
     * Register a delivery callback. The registered callback gets
     * called when a specific type of message arrives with the `from`
     * field set to this peers' id.
     *
     * @param msgType {String} refers to the `type`-field of the message
     * this callback should respond to
     * @param callback {Function} The callback to call when a message of
     * the given type arrives
     */
    registerDeliveryCallback: function(msgType, callback) {
        this._messageCallbacks[msgType] = callback;
    },

    /**
     * Register a monitor callback. The registered callback gets
     * called when a message arrives with the `from` field set to
     * this peers' id.
     *
     * @param callback {Function} The callback to call when a message is delivered
     */
    registerMonitorCallback: function(callback) {
        this._monitorCallback = callback;
    },

    /**
     * Kick off neighbour discovery mechanism by sending a `discovery-request' message to
     * a connected peer.
     *
     * @param peer {Peer}
     * @todo implement
     */
    discoverNeighbours: function(peer) {
        this.route(peer.id, 'discovery-request', '');
    },

    /**
     * Gets called when a neighbour discovery answer message is received.
     *
     * @param msg {String} Message containing ids of another peers peer table.
     * @todo should this call the connection manager?
     */
    onDiscoveryAnswerMessage: function(msg, from) {
        var i;
        for(i = 0; i < msg.length; i++) {
            if(msg[i] !== this._id) {
                this._connectionManager.connect(msg[i]);
            }
        }
    },

    /**
     * Answer a received neighbour discovery message. Respond with
     * known ids of all peers in the peerTable.
     *
     * @param msg {String} Message containing the discovery request from another peer.
     * @todo discovery message format
     */
    onDiscoveryRequestMessage: function(msg, from) {
        var peerIds = [],
        peer;
        for (peer in this._peerTable) {
            if (this._peerTable.hasOwnProperty(peer) && this._peerTable[peer] instanceof Peer) {
                peerIds.push(peer);
            }
        }
        this.route(from, 'discovery-answer', peerIds);
    }
};

if(typeof(module) !== 'undefined') {
    module.exports = Router;
}
<|endoftext|>


<commit_before>/*global createjs, kz*/
/**
 * @module KillZoombies
 */

// namespace:
this.kz = this.kz || {};

(function () {
    "use strict";

    kz.scenes = {};
    kz.sounds = {
        main_sound: null,
        level_sound: null,
        player_death: null,
        player_shoot: null,
        zombie: null,
    };

    // Main ====================================================================
    kz.scn_main = function () {
        /*
        if(createjs.Sound.loadComplete('main_sound')) {
            createjs.Sound.play('main_sound');
        }
        */
        //createjs.Sound.removeAllSounds();
        //|| kz.sounds.main_sound.playState !== createjs.Sound.PLAY_SUCCEEDED

        if (!kz.sounds.main_sound) {
            kz.sounds.main_sound = createjs.Sound.play('main_sound'. {loop:1});
        }

        kz.scenes.main = new kz.Scene({
            background: ['bg_main_menu'],
            buttons: [
                {
                    image: 'btn_play',
                    type: 'mousedown',
                    func: kz.scn_characters,
                    posX: 40,
                    posY: 15
                },
                {
                    image: 'btn_options',
                    type: 'mousedown',
                    func: kz.scn_options,
                    posX: 40,
                    posY: 45
                },
                {
                    image: 'btn_credits',
                    type: 'mousedown',
                    func: kz.scn_credits,
                    posX: 40,
                    posY: 75
                }
            ],
            removeScenes: [
                kz.scenes.credits,
                kz.scenes.game,
                kz.scenes.options
            ]
        });
    }

    // Options =================================================================
    kz.scn_options = function () {
        kz.scenes.options = new kz.Scene({
            background: ['bg_options_menu'],
            buttons: [
                {
                    image: 'btn_back',
                    type: 'mousedown',
                    func: kz.scn_main,
                    posX: 5,
                    posY: 75
                }
            ],
            removeScenes: [
                kz.scenes.credits,
                kz.scenes.main
            ]
        });
    }

    // Credits =================================================================
    kz.scn_credits = function () {
        kz.scenes.credits = new kz.Scene({
            background: ['bg_credits_menu'],
            buttons: [
                {
                    image: 'btn_back',
                    type: 'mousedown',
                    func: kz.scn_main,
                    posX: 40,
                    posY: 75
                }
            ],
            removeScenes: [
                kz.scenes.main,
                kz.scenes.options
            ]
        });
    }

    // Characteres =============================================================
    kz.scn_characters = function () {
        kz.scenes.characters = new kz.Scene({
            background: ['bg_main_menu'],
            buttons: [
                {
                    image: 'btn_play',
                    type: 'mousedown',
                    func: kz.scn_game,
                    posX: 40,
                    posY: 75
                }
            ],
            removeScenes: [
                kz.scenes.main,
                kz.scenes.options
            ]
        });

        (function () {
            var character,
                file,
                i = 0;

            for (i; i < kz.config.characters.length; i++) {
                file = kz.queue.getResult('character_' + kz.config.characters[i]);
                character = new createjs.Bitmap(file);
                character.name = kz.config.characters[i];
                character.scaleX = 0.4;
                character.scaleY = 0.4;
                character.x = 40 + 100 * i;
                character.y = 200;

                character.addEventListener('mousedown', function (event) {
                    kz.character = event.target.name;
                });

                kz.scenes.characters.addChild(character);
            }

            kz.stage.addChild(kz.scenes.characters);
            kz.stage.update();
        }());
    }

    // Game ====================================================================
    kz.scn_game = function () {
        console.log("GAME");
        //createjs.Sound.stop('main_sound');
        //createjs.Sound.stop('jenison');
        //if(createjs.Sound.loadComplete(mySound) {
        //createjs.Sound.play('jenison');

        if (kz.config.level_previous != kz.config.level_current) {
            kz.config.level_previous = kz.config.level_current;
            kz.queue.loadFile({id: "level", src: "js/levels/level" + kz.config.level_current + ".js"});
            //kz.queue.loadFile({id: "level", src: "js/levels/level" + kz.config.level_current + ".json", type: createjs.AbstractLoader.JSON});
            return true;
        }

        //kz.level = kz.queue.getResult('level');

        kz.level.weapon = kz.config.weapons.shotgun;
        kz.zoombies_deads = 0;

        createjs.Sound.stop();

        if (!kz.sounds.level_sound) {
            //createjs.Sound.play("music", {interrupt: createjs.Sound.INTERRUPT_NONE, loop: -1, volume: 0.4});
            kz.sounds.level_sound = createjs.Sound.play('level_sound');//, {interrupt: createjs.Sound.INTERRUPT_NONE, loop: 0, volume: 0.4});
            //kz.sounds.level_sound = createjs.Sound.play('kaikai');
        }

        kz.scenes.game = new kz.Scene({
            //background: ['bg_credits_menu'],
            removeScenes: [
                kz.scenes.main,
                kz.scenes.characters
            ]
        });

        createjs.Ticker.paused = false;

        kz.addWorld();
        kz.addPlayer();
        kz.addZoombie();
        kz.addHUD();
    };

    // Game Win ================================================================
    kz.scn_game_win = function () {
        kz.scenes.game_win = new kz.Scene({
            background: ['bg_win'],
            buttons: [
                {
                    image: 'btn_menu',
                    type: 'mousedown',
                    func: kz.scn_main,
                    posX: 40,
                    posY: 75
                }
            ],
            removeScenes: [
                kz.scenes.game,
                kz.scenes.mnu_level_complete
            ]
        });
    };

    // Game Over ===============================================================
    kz.scn_game_over = function () {
        kz.scenes.game_over = new kz.Scene({
            background: ['bg_over'],
            buttons: [
                {
                    image: 'btn_menu',
                    type: 'mousedown',
                    func: kz.scn_main,
                    posX: 40,
                    posY: 75
                },
                {
                    image: 'btn_play',
                    type: 'mousedown',
                    func: function () {
                        kz.stage.removeChild(kz.scenes.game_over);
                        kz.stage.removeChild(kz.scenes.game);
                        kz.scn_game();
                        console.log('RESTART');
                    },
                    posX: 20,
                    posY: 45
                },
            ],
            removeScenes: [
                kz.scenes.game,
                kz.scenes.mnu_level_complete
            ]
        });
    };

    // Pop-up menus ============================================================
    kz.mnu_pause = function () {
    	console.log("PAUSE MENU");
        kz.scenes.mnu_pause = new kz.Scene({
            background: ['bg_pause_menu', 20, 15],
            buttons: [
                {
                    image: 'btn_continue',
                    type: 'mousedown',
                    func: function () {
                		kz.stage.removeChild(kz.scenes.mnu_pause);
                		createjs.Ticker.paused = false;
                	},
                    posX: 20,
                    posY: 15
                },
                {
                    image: 'btn_options',
                    type: 'mousedown',
                    func: function () {
                		console.log('MENU OPCOES GAME');
                	},
                    posX: 20,
                    posY: 45
                },
                {
                    image: 'btn_menu',
                    type: 'mousedown',
                    func: function () {
                		kz.stage.removeChild(kz.scenes.mnu_pause);
                		console.log('REMOVE GAME');
                        createjs.Sound.stop();
                        kz.sounds.main_sound.play();
                		kz.scn_main();
                	},
                    posX: 20,
                    posY: 75
                }
            ]
        });
    }

    // Pop-up level complete ===================================================
    kz.mnu_level_complete = function () {
        console.log("LEVEL COMPLETE MENU");
        createjs.Ticker.paused = true;
        kz.config.level_current++;

        if (kz.config.level_current> 2) {
            kz.scn_game_win();
            return;
        }

        kz.scenes.mnu_level_complete = new kz.Scene({
            background: ['bg_pause_menu', 20, 15],
            buttons: [
                {
                    image: 'btn_menu',
                    type: 'mousedown',
                    func: function () {
                        kz.stage.removeChild(kz.scenes.mnu_level_complete);
                        createjs.Sound.stop();
                        kz.sounds.main_sound.play();
                        kz.scn_main();
                    },
                    posX: 20,
                    posY: 15
                },
                {
                    image: 'btn_play',
                    type: 'mousedown',
                    func: function () {
                        kz.stage.removeChild(kz.scenes.mnu_level_complete);
                        kz.stage.removeChild(kz.scenes.game);
                        kz.scn_game();
                        console.log('RESTART');
                    },
                    posX: 20,
                    posY: 45
                },
                {
                    image: 'btn_continue',
                    type: 'mousedown',
                    func: function () {
                        kz.stage.removeChild(kz.scenes.mnu_level_complete);
                        kz.scn_game();
                        //createjs.Ticker.paused = false;
                        console.log('CONTINUE');
                    },
                    posX: 20,
                    posY: 75
                }
            ]
        });
    };

        // Pop-up level complete ===================================================
    kz.mnu_game_over = function () {
        console.log("GAME OVER MENU");
        createjs.Ticker.paused = false;

        kz.scenes.mnu_game_over = new kz.Scene({
            background: ['bg_pause_menu', 20, 15],
            buttons: [
                {
                    // retry
                    image: 'btn_play',
                    type: 'mousedown',
                    func: function () {
                        kz.stage.removeChild(kz.scenes.mnu_game_over);
                        kz.stage.removeChild(kz.scenes.game);
                        kz.scn_game();
                        console.log('RESTART');
                    },
                    posX: 20,
                    posY: 15
                },
                {
                    image: 'btn_menu',
                    type: 'mousedown',
                    func: function () {
                        kz.stage.removeChild(kz.scenes.mnu_game_over);
                        createjs.Sound.stop();
                        kz.sounds.main_sound.play();
                        kz.scn_main();
                    },
                    posX: 20,
                    posY: 45
                }
            ]
        });
    };

    function pop_buyer() {

    }

    // HUD =========================================================================
    kz.addHUD = function () {
    	console.log("PAUSE MENU");
        kz.game_hud = new kz.HUD({
            buttons: [
                {
                    image: 'btn_pause',
                    type: 'mousedown',
                    func: function () {
                		if ( !createjs.Ticker.paused ) {
                            createjs.Ticker.paused = true;
                			kz.mnu_pause();
                		}
                	},
                    pos: {rx: true, ty: true, rm: 80, tm: 20},
                    posX: 90,
                    posY: 5
                },
                // Button left
                {
                    image: 'btn_move',
                    funcs: [
                        {
                            type: 'mousedown',
                            func: function () {
                        		if ( kz.player.display.life > 0 && kz.player.display.visible && !createjs.Ticker.paused ) {
                        			kz.player.display.direction = -1;
                        			kz.player.display.scaleX = -kz.player.scale;
                                    kz.player.display.mobile = true;
                                    kz.player.display.status = 'walk';
                        			kz.player.animation.gotoAndPlay('walk');
                        		}
                        	}
                        },
                        {
                            type: 'pressup',
                            func: function () {
                        		if ( kz.player.display.life > 0 && !createjs.Ticker.paused ) {
                        			//kz.player.display.direction = 0;
                                    kz.player.display.mobile = false;
                        			kz.player.display.status = 'idle';
                        			kz.player.animation.gotoAndPlay('idle');
                        		}
                        	}
                        }
                    ],
                    pos: {lx: true, by: true, lm: 20, bm: 80},
                    posX: 5,
                    posY: 85
                },
                // Button right
                {
                    image: 'btn_move',
                    funcs: [
                        {
                            type: 'mousedown',
                            func: function () {
                        		if ( kz.player.display.life > 0 && kz.player.display.visible && !createjs.Ticker.paused ) {
                        			kz.player.display.direction = 1;
                        			kz.player.display.scaleX = kz.player.scale;
                                    kz.player.display.mobile = true;
                                    kz.player.display.status = 'walk';
                        			kz.player.animation.gotoAndPlay('walk');
                        		}
                        	}
                        },
                        {
                            type: 'pressup',
                            func: function () {
                        		if ( kz.player.display.life > 0 && !createjs.Ticker.paused ) {
                        			//kz.player.display.direction = 0;
                                    kz.player.display.mobile = false;
                                    kz.player.display.status = 'idle';
                        			kz.player.animation.gotoAndPlay('idle');
                        		}
                    	    }
                        }
                    ],
                    pos: {lx: true, by: true, lm: 120, bm: 80},
                    posX: 15,
                    posY: 85
                },
                {
                    image: 'btn_shoot',
                    type: 'mousedown',
                    func: function () {
                		if ( kz.player.display.life > 0 && !createjs.Ticker.paused ) {
                            kz.player.display.shoot();
                		}
                	},
                    pos: {rx: true, by: true, rm: 80, bm: 80},
                    posX: 85,
                    posY: 85
                }
            ]
        });

        kz.scenes.game.addChild(kz.game_hud);
    }
}());
<commit_msg>Improviements in the control movement player<commit_after>/*global createjs, kz*/
/**
 * @module KillZoombies
 */

// namespace:
this.kz = this.kz || {};

(function () {
    "use strict";

    kz.scenes = {};
    kz.sounds = {
        main_sound: null,
        level_sound: null,
        player_death: null,
        player_shoot: null,
        zombie: null,
    };

    // Main ====================================================================
    kz.scn_main = function () {
        /*
        if(createjs.Sound.loadComplete('main_sound')) {
            createjs.Sound.play('main_sound');
        }
        */
        //createjs.Sound.removeAllSounds();
        //|| kz.sounds.main_sound.playState !== createjs.Sound.PLAY_SUCCEEDED

        if (!kz.sounds.main_sound) {
            //#kz.sounds.main_sound = createjs.Sound.play('main_sound', {loop:1});
        }

        kz.scenes.main = new kz.Scene({
            background: ['bg_main_menu'],
            buttons: [
                {
                    image: 'btn_play',
                    type: 'mousedown',
                    func: kz.scn_characters,
                    posX: 40,
                    posY: 15
                },
                {
                    image: 'btn_options',
                    type: 'mousedown',
                    func: kz.scn_options,
                    posX: 40,
                    posY: 45
                },
                {
                    image: 'btn_credits',
                    type: 'mousedown',
                    func: kz.scn_credits,
                    posX: 40,
                    posY: 75
                }
            ],
            removeScenes: [
                kz.scenes.credits,
                kz.scenes.game,
                kz.scenes.options
            ]
        });
    }

    // Options =================================================================
    kz.scn_options = function () {
        kz.scenes.options = new kz.Scene({
            background: ['bg_options_menu'],
            buttons: [
                {
                    image: 'btn_back',
                    type: 'mousedown',
                    func: kz.scn_main,
                    posX: 5,
                    posY: 75
                }
            ],
            removeScenes: [
                kz.scenes.credits,
                kz.scenes.main
            ]
        });
    }

    // Credits =================================================================
    kz.scn_credits = function () {
        kz.scenes.credits = new kz.Scene({
            background: ['bg_credits_menu'],
            buttons: [
                {
                    image: 'btn_back',
                    type: 'mousedown',
                    func: kz.scn_main,
                    posX: 40,
                    posY: 75
                }
            ],
            removeScenes: [
                kz.scenes.main,
                kz.scenes.options
            ]
        });
    }

    // Characteres =============================================================
    kz.scn_characters = function () {
        kz.scenes.characters = new kz.Scene({
            background: ['bg_main_menu'],
            buttons: [
                {
                    image: 'btn_play',
                    type: 'mousedown',
                    func: kz.scn_game,
                    posX: 40,
                    posY: 75
                }
            ],
            removeScenes: [
                kz.scenes.main,
                kz.scenes.options
            ]
        });

        (function () {
            var character,
                file,
                i = 0;

            for (i; i < kz.config.characters.length; i++) {
                file = kz.queue.getResult('character_' + kz.config.characters[i]);
                character = new createjs.Bitmap(file);
                character.name = kz.config.characters[i];
                character.scaleX = 0.4;
                character.scaleY = 0.4;
                character.x = 40 + 100 * i;
                character.y = 200;

                character.addEventListener('mousedown', function (event) {
                    kz.character = event.target.name;
                });

                kz.scenes.characters.addChild(character);
            }

            kz.stage.addChild(kz.scenes.characters);
            kz.stage.update();
        }());
    }

    // Game ====================================================================
    kz.scn_game = function () {
        console.log("GAME");
        //createjs.Sound.stop('main_sound');
        //createjs.Sound.stop('jenison');
        //if(createjs.Sound.loadComplete(mySound) {
        //createjs.Sound.play('jenison');

        if (kz.config.level_previous != kz.config.level_current) {
            kz.config.level_previous = kz.config.level_current;
            kz.queue.loadFile({id: "level", src: "js/levels/level" + kz.config.level_current + ".js"});
            //kz.queue.loadFile({id: "level", src: "js/levels/level" + kz.config.level_current + ".json", type: createjs.AbstractLoader.JSON});
            return true;
        }

        //kz.level = kz.queue.getResult('level');

        kz.level.weapon = kz.config.weapons.shotgun;
        kz.zoombies_deads = 0;

        createjs.Sound.stop();

        if (!kz.sounds.level_sound) {
            //createjs.Sound.play("music", {interrupt: createjs.Sound.INTERRUPT_NONE, loop: -1, volume: 0.4});
            kz.sounds.level_sound = createjs.Sound.play('level_sound');//, {interrupt: createjs.Sound.INTERRUPT_NONE, loop: 0, volume: 0.4});
            //kz.sounds.level_sound = createjs.Sound.play('kaikai');
        }

        kz.scenes.game = new kz.Scene({
            //background: ['bg_credits_menu'],
            removeScenes: [
                kz.scenes.main,
                kz.scenes.characters
            ]
        });

        createjs.Ticker.paused = false;

        kz.addWorld();
        kz.addPlayer();
        kz.addZoombie();
        kz.addHUD();
    };

    // Game Win ================================================================
    kz.scn_game_win = function () {
        kz.scenes.game_win = new kz.Scene({
            background: ['bg_win'],
            buttons: [
                {
                    image: 'btn_menu',
                    type: 'mousedown',
                    func: kz.scn_main,
                    posX: 40,
                    posY: 75
                }
            ],
            removeScenes: [
                kz.scenes.game,
                kz.scenes.mnu_level_complete
            ]
        });
    };

    // Game Over ===============================================================
    kz.scn_game_over = function () {
        kz.scenes.game_over = new kz.Scene({
            background: ['bg_over'],
            buttons: [
                {
                    image: 'btn_menu',
                    type: 'mousedown',
                    func: kz.scn_main,
                    posX: 40,
                    posY: 75
                },
                {
                    image: 'btn_play',
                    type: 'mousedown',
                    func: function () {
                        kz.stage.removeChild(kz.scenes.game_over);
                        kz.stage.removeChild(kz.scenes.game);
                        kz.scn_game();
                        console.log('RESTART');
                    },
                    posX: 20,
                    posY: 45
                },
            ],
            removeScenes: [
                kz.scenes.game,
                kz.scenes.mnu_level_complete
            ]
        });
    };

    // Pop-up menus ============================================================
    kz.mnu_pause = function () {
    	console.log("PAUSE MENU");
        kz.scenes.mnu_pause = new kz.Scene({
            background: ['bg_pause_menu', 20, 15],
            buttons: [
                {
                    image: 'btn_continue',
                    type: 'mousedown',
                    func: function () {
                		kz.stage.removeChild(kz.scenes.mnu_pause);
                		createjs.Ticker.paused = false;
                	},
                    posX: 20,
                    posY: 15
                },
                {
                    image: 'btn_options',
                    type: 'mousedown',
                    func: function () {
                		console.log('MENU OPCOES GAME');
                	},
                    posX: 20,
                    posY: 45
                },
                {
                    image: 'btn_menu',
                    type: 'mousedown',
                    func: function () {
                		kz.stage.removeChild(kz.scenes.mnu_pause);
                		console.log('REMOVE GAME');
                        createjs.Sound.stop();
                        kz.sounds.main_sound.play();
                		kz.scn_main();
                	},
                    posX: 20,
                    posY: 75
                }
            ]
        });
    }

    // Pop-up level complete ===================================================
    kz.mnu_level_complete = function () {
        console.log("LEVEL COMPLETE MENU");
        createjs.Ticker.paused = true;
        kz.config.level_current++;

        if (kz.config.level_current> 2) {
            kz.scn_game_win();
            return;
        }

        kz.scenes.mnu_level_complete = new kz.Scene({
            background: ['bg_pause_menu', 20, 15],
            buttons: [
                {
                    image: 'btn_menu',
                    type: 'mousedown',
                    func: function () {
                        kz.stage.removeChild(kz.scenes.mnu_level_complete);
                        createjs.Sound.stop();
                        kz.sounds.main_sound.play();
                        kz.scn_main();
                    },
                    posX: 20,
                    posY: 15
                },
                {
                    image: 'btn_play',
                    type: 'mousedown',
                    func: function () {
                        kz.stage.removeChild(kz.scenes.mnu_level_complete);
                        kz.stage.removeChild(kz.scenes.game);
                        kz.scn_game();
                        console.log('RESTART');
                    },
                    posX: 20,
                    posY: 45
                },
                {
                    image: 'btn_continue',
                    type: 'mousedown',
                    func: function () {
                        kz.stage.removeChild(kz.scenes.mnu_level_complete);
                        kz.scn_game();
                        //createjs.Ticker.paused = false;
                        console.log('CONTINUE');
                    },
                    posX: 20,
                    posY: 75
                }
            ]
        });
    };

        // Pop-up level complete ===================================================
    kz.mnu_game_over = function () {
        console.log("GAME OVER MENU");
        createjs.Ticker.paused = false;

        kz.scenes.mnu_game_over = new kz.Scene({
            background: ['bg_pause_menu', 20, 15],
            buttons: [
                {
                    // retry
                    image: 'btn_play',
                    type: 'mousedown',
                    func: function () {
                        kz.stage.removeChild(kz.scenes.mnu_game_over);
                        kz.stage.removeChild(kz.scenes.game);
                        kz.scn_game();
                        console.log('RESTART');
                    },
                    posX: 20,
                    posY: 15
                },
                {
                    image: 'btn_menu',
                    type: 'mousedown',
                    func: function () {
                        kz.stage.removeChild(kz.scenes.mnu_game_over);
                        createjs.Sound.stop();
                        kz.sounds.main_sound.play();
                        kz.scn_main();
                    },
                    posX: 20,
                    posY: 45
                }
            ]
        });
    };

    function pop_buyer() {

    }

    // HUD =========================================================================
    //GIT ADD time to move player
    kz.addHUD = function () {
    	console.log("PAUSE MENU");
        kz.game_hud = new kz.HUD({
            buttons: [
                {
                    image: 'btn_pause',
                    type: 'mousedown',
                    func: function () {
                		if ( !createjs.Ticker.paused ) {
                            createjs.Ticker.paused = true;
                			kz.mnu_pause();
                		}
                	},
                    pos: {rx: true, ty: true, rm: 80, tm: 20},
                    posX: 90,
                    posY: 5
                },
                // Button left
                {
                    image: 'btn_move',
                    funcs: [
                        {
                            type: 'mousedown',
                            func: function () {
                                if (!createjs.Ticker.paused) {
                                    kz.lastKey = {time: createjs.Ticker.getTime(), key: 'BUTTONDOWN'};
                                    kz.player.display.direction = -1;
                                    //kz.player.display.mobile = true;
                                    //kz.player.display.move(true);
                                }
                        	}
                        },
                        {
                            type: 'pressup',
                            func: function () {
                        		if ( kz.player.display.life > 0 && !createjs.Ticker.paused ) {
                                    kz.lastKey = {time: createjs.Ticker.getTime(), key: 'BUTTONUP'};
                        			//kz.player.display.direction = 0;
                                    kz.player.display.idle();
                        		}
                        	}
                        }
                    ],
                    pos: {lx: true, by: true, lm: 20, bm: 80},
                    posX: 5,
                    posY: 85
                },
                // Button right
                {
                    image: 'btn_move',
                    funcs: [
                        {
                            type: 'mousedown',
                            func: function () {
                                if (!createjs.Ticker.paused) {
                                    kz.lastKey = {time: createjs.Ticker.getTime(), key: 'BUTTONDOWN'};
                                    kz.player.display.direction = 1;
                                    //kz.player.display.mobile = true;
                                    //kz.player.display.move(true);
                                }
                        	}
                        },
                        {
                            type: 'pressup',
                            func: function () {
                        		if ( kz.player.display.life > 0 && !createjs.Ticker.paused ) {
                                    kz.lastKey = {time: createjs.Ticker.getTime(), key: 'BUTTONUP'};
                        			//kz.player.display.direction = 0;
                                    kz.player.display.idle();
                        		}
                    	    }
                        }
                    ],
                    pos: {lx: true, by: true, lm: 120, bm: 80},
                    posX: 15,
                    posY: 85
                },
                {
                    image: 'btn_shoot',
                    type: 'mousedown',
                    func: function () {
                		if ( kz.player.display.life > 0 && !createjs.Ticker.paused ) {
                            kz.player.display.shoot();
                		}
                	},
                    pos: {rx: true, by: true, rm: 80, bm: 80},
                    posX: 85,
                    posY: 85
                }
            ]
        });

        kz.scenes.game.addChild(kz.game_hud);
    }
}());
<|endoftext|>


<commit_before>/*
 * Created by marekfort on 13/04/16.
 */

$(document).ready(function(){
    // Setting summary to be centered to the iphone mockup
    $('.section-swipe .summary').css('margin-top', ($('.section-swipe img').height() / 2 - $('.section-swipe .summary').height() / 2 ));
    $('.section-supl .summary').css('margin-top', ($('.section-supl img').height() / 2 - $('.section-supl .summary').height() / 2 ));
});

lastScroll = 0;
shouldAnimate = true;
9
lastColor = "#3C9BFF";
shouldSlide = true;
$(window).on('scroll', function(){
    scrollTop = $('body').scrollTop();
    scrollingUp = scrollTop < lastScroll;
    lastScroll = scrollTop;
    heightOfTransition = $('.section-supl').height();

    /*
     suplTop = (scrollTop - $('.section-supl').offset().top) / 14;
     $('.section-supl img').css('top', (suplTop));
     swipeTop = (scrollTop - $('.section-swipe').offset().top) / 14;
     $('.section-swipe img').css('top', (swipeTop));
     */

    if  ($('.section-supl').offset().top + heightOfTransition - heightOfTransition / 3 - scrollTop < 0 && lastColor != "#FF3D97" && scrollingUp == false && shouldAnimate ) {
        lastColor = "#FF3D97";
        shouldAnimate = false;
        jQuery(".content").animate({
            backgroundColor: "#FF3D97"
        }, 1500 );
        setTimeout(function(){
            shouldAnimate = true
        },1500);
    }
    else if ($('.section-supl').offset().top + heightOfTransition + heightOfTransition / 3 - scrollTop > 0 && lastColor != "#3C9BFF" && scrollingUp && shouldAnimate) {
        lastColor = "#3C9BFF";
        shouldAnimate = false;
        jQuery(".content").animate({
            backgroundColor: "#3C9BFF"
        }, 1500 );
        setTimeout(function(){
            shouldAnimate = true
        },1500);
    }

    if (scrollTop >= $('.section-me').offset().top - $('.section-me').height() && shouldSlide) {
        $('.slide').addClass('animated fadeInUp');
        shouldSlide = false;
    }

});

$('.portfolio-link').click(function() {
    body = $('body');
    scrollTop = body.scrollTop();
    body.animate({scrollTop : $('.section-supl').offset().top}, 600);
});

$('#about-link').click(function() {
    body = $('body');
    scrollTop = body.scrollTop();
    body.animate({scrollTop : $('.section-me').offset().top}, 600);
});

<commit_msg>script<commit_after>/*
 * Created by marekfort on 13/04/16.
 */

$(document).ready(function(){
    // Setting summary to be centered to the iphone mockup
    $('.section-swipe .summary').css('margin-top', ($('.section-swipe img').height() / 2 - $('.section-swipe .summary').height() / 2 ));
    $('.section-supl .summary').css('margin-top', ($('.section-supl img').height() / 2 - $('.section-supl .summary').height() / 2 ));
});

lastScroll = 0;
<<<<<<< HEAD
shouldAnimate = true;
9
=======
shouldAnimat = true;
10
>>>>>>> feature
lastColor = "#3C9BFF";
shouldSlide = true;
$(window).on('scroll', function(){
    scrollTop = $('body').scrollTop();
    scrollingUp = scrollTop < lastScroll;
    lastScroll = scrollTop;
    heightOfTransition = $('.section-supl').height();

    /*
     suplTop = (scrollTop - $('.section-supl').offset().top) / 14;
     $('.section-supl img').css('top', (suplTop));
     swipeTop = (scrollTop - $('.section-swipe').offset().top) / 14;
     $('.section-swipe img').css('top', (swipeTop));
     */

    if  ($('.section-supl').offset().top + heightOfTransition - heightOfTransition / 3 - scrollTop < 0 && lastColor != "#FF3D97" && scrollingUp == false && shouldAnimate ) {
        lastColor = "#FF3D97";
        shouldAnimate = false;
        jQuery(".content").animate({
            backgroundColor: "#FF3D97"
        }, 1500 );
        setTimeout(function(){
            shouldAnimate = true
        },1500);
    }
    else if ($('.section-supl').offset().top + heightOfTransition + heightOfTransition / 3 - scrollTop > 0 && lastColor != "#3C9BFF" && scrollingUp && shouldAnimate) {
        lastColor = "#3C9BFF";
        shouldAnimate = false;
        jQuery(".content").animate({
            backgroundColor: "#3C9BFF"
        }, 1500 );
        setTimeout(function(){
            shouldAnimate = true
        },1500);
    }

    if (scrollTop >= $('.section-me').offset().top - $('.section-me').height() && shouldSlide) {
        $('.slide').addClass('animated fadeInUp');
        shouldSlide = false;
    }

});

$('.portfolio-link').click(function() {
    body = $('body');
    scrollTop = body.scrollTop();
    body.animate({scrollTop : $('.section-supl').offset().top}, 600);
});

$('#about-link').click(function() {
    body = $('body');
    scrollTop = body.scrollTop();
    body.animate({scrollTop : $('.section-me').offset().top}, 600);
});

<|endoftext|>