<commit_before>
/* global soundModule */
var yAxis = p2.vec2.fromValues(0, 1);
const DEADLINE_HEIGHT = 160;
const PLATFORM_WIDTH = 100;
const PLAYER_INIT_LIFE_COUNT = 4;
const PLAYER_CHEAT_LIFE_COUNT = 4000;
const NUMBER_OF_PITCH = 12;
const SUPER_COOL_DOWN = 2;
const KNIFE_COOL_DOWN = 5000;

function indexToGameHeight(index) {
  var total = game.height - 160;
  return index * total / NUMBER_OF_PITCH;
}

let stageID = 0;
const stageList = [
  'setup_level_1',
  'setup_level_2',
  'setup_level_3',
];

const stage3List = [
  'setup_level_3_stage_1',
  'setup_level_3_stage_2',
  'setup_level_3_stage_3',
];

class State extends Phaser.State {
  preload() {
    game.load.image('character', 'assets/sprites/character.png');
    game.load.image('wall', 'assets/sprites/platform.png');
    game.load.image('background', 'assets/sprites/dayBG.png');
    game.load.image('spears', 'assets/sprites/spikes.png');
    game.load.image('scroll', 'assets/sprites/scroll.png');
    game.load.image('knife', 'assets/sprites/knife.png');
  }

  create() {
    game.add.tileSprite(0, 0, 1280, 720, 'background');

    this.lifeText = game.add.text(20, 20, "4", {
      font: "30px Arial black",
      fill: "#ff0044",
      align: "center"
    });

    this.lifeText.anchor.setTo(0, 0);

    this.gotScrollText = game.add.text(game.width - 20, 20, "0", {
      font: "30px Arial black",
      fill: "#00ff44",
      align: "center"
    });
    this.gotScrollText.anchor.setTo(1, 0);

    this.winlText = game.add.text(game.width / 2, game.height / 2, "You Win!", {
      font: "60px Arial black",
      fill: "#00ff44",
      stroke: "#00ff44",
      align: "center"
    });
    this.winlText.anchor.setTo(0.5);
    this.winlText.visible = false;

    game.stage.backgroundColor = "#4488AA";

    this.cursors = game.input.keyboard.createCursorKeys();

    this.jumpTimer = 0;
    this.scrollGoal = 0;

    //  Enable p2 physics
    game.physics.startSystem(Phaser.Physics.P2JS);

    game.physics.p2.gravity.y = 200;
    game.physics.p2.world.defaultContactMaterial.friction = 0.3;
    game.physics.p2.world.setGlobalStiffness(1e5);

    //  Create our collision groups. One for the player, one for the music floors
    this.playerCollisionGroup = game.physics.p2.createCollisionGroup();
    this.musicFloorCollisionGroup = game.physics.p2.createCollisionGroup();
    this.deadCollisionGroup = game.physics.p2.createCollisionGroup();
    this.scrollCollisionGroup = game.physics.p2.createCollisionGroup();

    // to still collide with the world bounds
    game.physics.p2.updateBoundsCollisionGroup();

    // for (let i = 0; i < 100; i++) {
    //   const wall = this.createWall(100 * i, 500);
    // }
    this.musicFloors = [];
    const wall = this.createWall(PLATFORM_WIDTH / 2, 500);
    var currentMusicX = PLATFORM_WIDTH * 1.5;
    while (currentMusicX < game.width) {
      const musicFloor = this.createMusicFloor(currentMusicX, 500);
      this.musicFloors.push(musicFloor);
      currentMusicX += PLATFORM_WIDTH;
    }

    this.player = game.add.sprite(PLATFORM_WIDTH / 2, 300, 'character');
    this.player.lifeCount = PLAYER_INIT_LIFE_COUNT;
    if (window.location.href.split('?')[1]=='c'){ this.player.lifeCount = PLAYER_CHEAT_LIFE_COUNT; }

    //  Enable if for physics. This creates a default rectangular body.
    game.physics.p2.enable(this.player);

    this.player.body.setCollisionGroup(this.playerCollisionGroup);
    this.player.body.collides([this.playerCollisionGroup, this.musicFloorCollisionGroup]);
    this.player.body.collides([this.deadCollisionGroup, this.scrollCollisionGroup]);

    //  Check for the block hitting another object
    this.player.body.onBeginContact.add(this.touchPlayer, this);
    this.deadzones = this.setupDeadZones();
    this.scrolls = this.setup_level_1();
    this.player.scollGot = 0;
    this.scrollGoal = this.scrolls.length;

    this.knifeIsCooldown = false;

    soundModule.signal.add((...params) => { this.onSound(...params); });
  }

  setPlayerSuper() {
    var that = this;
    this.playerSuper = true;
    this.superTimer = setTimeout(function () { that.playerSuper = false; }, SUPER_COOL_DOWN);
  }

  setKnifeTimeout() {
    var that = this;
    this.knifeIsCooldown = true;
    this.knife = null;
    this.knifeTimer = setTimeout(function () { that.knifeIsCooldown = false; }, KNIFE_COOL_DOWN);
  }

  setup_level_1() {
    console.log('setup_level_1');
    var output = [];
    var scroll = game.add.sprite(1130, 150, 'scroll');
    //  Enable if for physics. This creates a default rectangular body.
    game.physics.p2.enable(scroll);
    scroll.body.static = true;

    scroll.body.setCollisionGroup(this.scrollCollisionGroup);
    scroll.body.collides([this.playerCollisionGroup]);
    output.push(scroll);
    this.knifeEnabled = true;
    return output
  }

  setup_level_2() {
    console.log('setup_level_2');
    var output = [];

    var scrollCoord = [[1250, 150], [830, 400], [430, 320]]

    for (var i = 0; i < scrollCoord.length; i++) {
      var scroll = game.add.sprite(scrollCoord[i][0], scrollCoord[i][1], 'scroll');
      //  Enable if for physics. This creates a default rectangular body.
      game.physics.p2.enable(scroll);
      scroll.body.static = true;

      scroll.body.setCollisionGroup(this.scrollCollisionGroup);
      scroll.body.collides([this.playerCollisionGroup, this.scrollCollisionGroup]);
      output.push(scroll);
    }
    return output
  }

  setup_level_3() {
    console.log('setup_level_3');

  }

  setup_level_3_stage_1() {
    console.log('setup_level_3_stage_1');
    var output = [];
    var scroll = game.add.sprite(230, 150, 'scroll');
    //  Enable if for physics. This creates a default rectangular body.
    game.physics.p2.enable(scroll);
    scroll.body.static = true;

    scroll.body.setCollisionGroup(this.scrollCollisionGroup);
    scroll.body.collides([this.playerCollisionGroup, this.scrollCollisionGroup]);
    output.push(scroll);
    return output
  }

  setup_level_3_stage_2() {
    console.log('setup_level_3_stage_2');
    var output = [];
    var scroll = game.add.sprite(430, 280, 'scroll');
    //  Enable if for physics. This creates a default rectangular body.
    game.physics.p2.enable(scroll);
    scroll.body.static = true;

    scroll.body.setCollisionGroup(this.scrollCollisionGroup);
    scroll.body.collides([this.playerCollisionGroup, this.scrollCollisionGroup]);
    output.push(scroll);
    return output
  }

  setup_level_3_stage_3() {
    console.log('setup_level_3_stage_3');
    var output = [];
    var scroll = game.add.sprite(830, 380, 'scroll');
    //  Enable if for physics. This creates a default rectangular body.
    game.physics.p2.enable(scroll);
    scroll.body.static = true;

    scroll.body.setCollisionGroup(this.scrollCollisionGroup);
    scroll.body.collides([this.playerCollisionGroup, this.scrollCollisionGroup]);
    output.push(scroll);
    return output
  }

  createKnife(y_index) {
    const knife = game.add.sprite(game.width, indexToGameHeight(y_index), 'knife');
    game.physics.p2.enable(knife);
    knife.body.kinematic = true;
    knife.body.setCollisionGroup(this.deadCollisionGroup);
    knife.body.collides(this.playerCollisionGroup);
    knife.body.moveLeft(256);
    this.knife = knife;
  }

  moveKnife(y_index) {
    if (this.knife) {
      this.knife.body.y = (this.knife.body.y + indexToGameHeight(y_index)) / 2;
    }
  }

  setupDeadZones() {
    var currentX = 0;
    var output = [];
    const deadline_y = game.height - DEADLINE_HEIGHT / 2;
    while (currentX < game.width) {
      var deadzone = game.add.sprite(currentX, deadline_y, 'spears');
      deadzone.anchor.setTo(0, 0);
      game.physics.p2.enable(deadzone);
      deadzone.body.y = game.height - DEADLINE_HEIGHT / 2;
      deadzone.body.static = true;
      deadzone.body.setCollisionGroup(this.deadCollisionGroup);

      deadzone.body.collides(this.playerCollisionGroup);
      output.push(deadzone);
      currentX += deadzone.width;
    }
    return output;
  }

  update() {

    if (this.cursors.left.isDown) {
      this.player.body.moveLeft(200);

      // if (player.facing != 'left') {
      //   player.facing = 'left';
      // }
    }
    else if (this.cursors.right.isDown) {
      this.player.body.moveRight(200);

      // if (player.facing != 'right') {
      //   player.facing = 'right';
      // }
    } else {
      this.player.body.velocity.x = 0;

      // if (player.facing != 'idle') {

      //   if (player.facing == 'left') {
      //   }
      //   else {
      //   }

      //   player.facing = 'idle';
      // }
    }

    if (this.cursors.up.isDown && game.time.now > this.jumpTimer && this.checkIfCanJump()) {
      this.player.body.moveUp(300);
      this.jumpTimer = game.time.now + 750;
    }
    if (this.knife && this.knife.x < 0) {
      this.knife.destroy();
      this.setKnifeTimeout();
    }
  }

  checkIfCanJump() {

    var result = false;

    for (var i = 0; i < game.physics.p2.world.narrowphase.contactEquations.length; i++) {
      var c = game.physics.p2.world.narrowphase.contactEquations[i];

      if (c.bodyA === this.player.body.data || c.bodyB === this.player.body.data) {
        var d = p2.vec2.dot(c.normalA, yAxis);

        if (c.bodyA === this.player.body.data) {
          d *= -1;
        }

        if (d > 0.5) {
          result = true;
        }
      }
    }

    return result;

  }

  touchPlayer(body, bodyB, shapeA, shapeB, equation) {
    // console.log("touchPlayer");
    if (body && body.sprite && (body.sprite.key === 'spears' || body.sprite.key === 'knife') && !this.playerSuper) {
      console.log("spears or knife");
      this.player.lifeCount--;
      this.lifeText.setText(this.player.lifeCount);
      this.player.body.y = 30;
      this.checkLose();
    } else if (body && body.sprite && body.sprite.key === 'scroll') {
      console.log("scroll");
      this.getScroll();
      body.sprite.destroy();
    }
  }

  getScroll(sprite1, sprite2) {
    this.player.scollGot++;
    this.gotScrollText.setText(this.player.scollGot);
    console.log('getScroll', this.player.scollGot, this.scrollGoal);

    if (this.player.scollGot >= this.scrollGoal) {
      this.win();
    }
  }

  win() {
    console.log('win');
    this.winlText.visible = true;

    setTimeout(() => {
      this.winlText.visible = false;

      this.cleanUp();

      this.nextRoom();
    }, 2000);
  }

  lose() {
    console.log('lose');
    this.cleanUp();
  }

  cleanUp() {
    console.log('cleanUp');
    this.player.scollGot = 0;
  }

  nextRoom() {
    console.log('nextRoom');
    stageID++;
    this.scrolls = this[stageList[stageID]]();
    this.scrollGoal = this.scrolls.length;
  }

  checkLose() {
    if (this.player.lifeCount <= 0) {
      this.lose();
    }
  }

  onSound(y0Pitch, y1Pitch, y0Amplitude, y1Amplitude) {
    // console.log(y0Pitch + " " + y1Pitch);
    const normalized0 = y0Pitch ;
    const normalized1 = y1Pitch ;
    var index = Math.round(normalized0 * NUMBER_OF_PITCH) % NUMBER_OF_PITCH;
    var index1 = Math.round(normalized1 * NUMBER_OF_PITCH) % NUMBER_OF_PITCH;
    //var singIndex = Math.round(normalized0 * 11);
    // console.log('noteStrings', soundModule.noteStrings[index]);
    //console.log('onSound',
    // normalized0, soundModule.noteStrings[singIndex],
    // normalized1, '');
    this.musicFloors.forEach((elem, id) => {
      if (Math.abs(id - index) < 3) {
        // const heightLimit = 500 - y0Amplitude * 70;
        const heightLimit = 500 - 400;
        if (elem.y > heightLimit) {
          elem.body.moveUp(300);
        } else {
          elem.body.y = heightLimit;
          elem.body.setZeroVelocity();
        }
        elem.loadTexture('wall');
      } else {
        elem.loadTexture('wall');

        if (elem.y < game.height - DEADLINE_HEIGHT) {
          elem.body.moveDown(80);
        } else if (elem.y < game.height) {
          elem.body.moveDown(40);
        } else {
          elem.body.y = game.height;
          elem.body.setZeroVelocity();
        }

        // elem.y = Phaser.Math.linear(elem.y, 500, 0.01);
      }
    });

    if (normalized1 > 0 && this.knifeEnabled) {
      if (!this.knife && !this.knifeIsCooldown) {
        this.createKnife(index1);
      } else {
        this.moveKnife(index1);
      }
    }
  }

  createWall(x, y) {
    var wall = game.add.sprite(x, y, 'wall');
    game.physics.p2.enable(wall);
    wall.body.static = true;

    wall.body.setCollisionGroup(this.playerCollisionGroup);
    wall.body.collides([this.playerCollisionGroup]);
    return wall;
  }

  createMusicFloor(x, y) {
    var wall = game.add.sprite(x, y, 'wall');
    game.physics.p2.enable(wall);
    wall.body.kinematic = true;

    wall.body.setCollisionGroup(this.musicFloorCollisionGroup);
    wall.body.collides([this.playerCollisionGroup, this.musicFloorCollisionGroup]);
    return wall;
  }
}

var game = new Phaser.Game(
  1280, 720, Phaser.AUTO, 'wrapper', new State());
<commit_msg>Change platform height to 400<commit_after>
/* global soundModule */
var yAxis = p2.vec2.fromValues(0, 1);
const DEADLINE_HEIGHT = 160;
const PLATFORM_WIDTH = 100;
const PLAYER_INIT_LIFE_COUNT = 4;
const PLAYER_CHEAT_LIFE_COUNT = 4000;
const NUMBER_OF_PITCH = 12;
const SUPER_COOL_DOWN = 2;
const KNIFE_COOL_DOWN = 5000;

function indexToGameHeight(index) {
  var total = game.height - 160;
  return index * total / NUMBER_OF_PITCH;
}

let stageID = 0;
const stageList = [
  'setup_level_1',
  'setup_level_2',
  'setup_level_3',
];

const stage3List = [
  'setup_level_3_stage_1',
  'setup_level_3_stage_2',
  'setup_level_3_stage_3',
];

class State extends Phaser.State {
  preload() {
    game.load.image('character', 'assets/sprites/character.png');
    game.load.image('wall', 'assets/sprites/platform.png');
    game.load.image('background', 'assets/sprites/dayBG.png');
    game.load.image('spears', 'assets/sprites/spikes.png');
    game.load.image('scroll', 'assets/sprites/scroll.png');
    game.load.image('knife', 'assets/sprites/knife.png');
  }

  create() {
    game.add.tileSprite(0, 0, 1280, 720, 'background');

    this.lifeText = game.add.text(20, 20, "4", {
      font: "30px Arial black",
      fill: "#ff0044",
      align: "center"
    });

    this.lifeText.anchor.setTo(0, 0);

    this.gotScrollText = game.add.text(game.width - 20, 20, "0", {
      font: "30px Arial black",
      fill: "#00ff44",
      align: "center"
    });
    this.gotScrollText.anchor.setTo(1, 0);

    this.winlText = game.add.text(game.width / 2, game.height / 2, "You Win!", {
      font: "60px Arial black",
      fill: "#00ff44",
      stroke: "#00ff44",
      align: "center"
    });
    this.winlText.anchor.setTo(0.5);
    this.winlText.visible = false;

    game.stage.backgroundColor = "#4488AA";

    this.cursors = game.input.keyboard.createCursorKeys();

    this.jumpTimer = 0;
    this.scrollGoal = 0;

    //  Enable p2 physics
    game.physics.startSystem(Phaser.Physics.P2JS);

    game.physics.p2.gravity.y = 200;
    game.physics.p2.world.defaultContactMaterial.friction = 0.3;
    game.physics.p2.world.setGlobalStiffness(1e5);

    //  Create our collision groups. One for the player, one for the music floors
    this.playerCollisionGroup = game.physics.p2.createCollisionGroup();
    this.musicFloorCollisionGroup = game.physics.p2.createCollisionGroup();
    this.deadCollisionGroup = game.physics.p2.createCollisionGroup();
    this.scrollCollisionGroup = game.physics.p2.createCollisionGroup();

    // to still collide with the world bounds
    game.physics.p2.updateBoundsCollisionGroup();

    // for (let i = 0; i < 100; i++) {
    //   const wall = this.createWall(100 * i, 500);
    // }
    this.musicFloors = [];
    const wall = this.createWall(PLATFORM_WIDTH / 2, 400);
    var currentMusicX = PLATFORM_WIDTH * 1.5;
    while (currentMusicX < game.width) {
      const musicFloor = this.createMusicFloor(currentMusicX, 500);
      this.musicFloors.push(musicFloor);
      currentMusicX += PLATFORM_WIDTH;
    }

    this.player = game.add.sprite(PLATFORM_WIDTH / 2, 300, 'character');
    this.player.lifeCount = PLAYER_INIT_LIFE_COUNT;
    if (window.location.href.split('?')[1]=='c'){ this.player.lifeCount = PLAYER_CHEAT_LIFE_COUNT; }

    //  Enable if for physics. This creates a default rectangular body.
    game.physics.p2.enable(this.player);

    this.player.body.setCollisionGroup(this.playerCollisionGroup);
    this.player.body.collides([this.playerCollisionGroup, this.musicFloorCollisionGroup]);
    this.player.body.collides([this.deadCollisionGroup, this.scrollCollisionGroup]);

    //  Check for the block hitting another object
    this.player.body.onBeginContact.add(this.touchPlayer, this);
    this.deadzones = this.setupDeadZones();
    this.scrolls = this.setup_level_1();
    this.player.scollGot = 0;
    this.scrollGoal = this.scrolls.length;

    this.knifeIsCooldown = false;

    soundModule.signal.add((...params) => { this.onSound(...params); });
  }

  setPlayerSuper() {
    var that = this;
    this.playerSuper = true;
    this.superTimer = setTimeout(function () { that.playerSuper = false; }, SUPER_COOL_DOWN);
  }

  setKnifeTimeout() {
    var that = this;
    this.knifeIsCooldown = true;
    this.knife = null;
    this.knifeTimer = setTimeout(function () { that.knifeIsCooldown = false; }, KNIFE_COOL_DOWN);
  }

  setup_level_1() {
    console.log('setup_level_1');
    var output = [];
    var scroll = game.add.sprite(1130, 150, 'scroll');
    //  Enable if for physics. This creates a default rectangular body.
    game.physics.p2.enable(scroll);
    scroll.body.static = true;

    scroll.body.setCollisionGroup(this.scrollCollisionGroup);
    scroll.body.collides([this.playerCollisionGroup]);
    output.push(scroll);
    this.knifeEnabled = true;
    return output
  }

  setup_level_2() {
    console.log('setup_level_2');
    var output = [];

    var scrollCoord = [[1250, 150], [830, 400], [430, 320]]

    for (var i = 0; i < scrollCoord.length; i++) {
      var scroll = game.add.sprite(scrollCoord[i][0], scrollCoord[i][1], 'scroll');
      //  Enable if for physics. This creates a default rectangular body.
      game.physics.p2.enable(scroll);
      scroll.body.static = true;

      scroll.body.setCollisionGroup(this.scrollCollisionGroup);
      scroll.body.collides([this.playerCollisionGroup, this.scrollCollisionGroup]);
      output.push(scroll);
    }
    return output
  }

  setup_level_3() {
    console.log('setup_level_3');

  }

  setup_level_3_stage_1() {
    console.log('setup_level_3_stage_1');
    var output = [];
    var scroll = game.add.sprite(230, 150, 'scroll');
    //  Enable if for physics. This creates a default rectangular body.
    game.physics.p2.enable(scroll);
    scroll.body.static = true;

    scroll.body.setCollisionGroup(this.scrollCollisionGroup);
    scroll.body.collides([this.playerCollisionGroup, this.scrollCollisionGroup]);
    output.push(scroll);
    return output
  }

  setup_level_3_stage_2() {
    console.log('setup_level_3_stage_2');
    var output = [];
    var scroll = game.add.sprite(430, 280, 'scroll');
    //  Enable if for physics. This creates a default rectangular body.
    game.physics.p2.enable(scroll);
    scroll.body.static = true;

    scroll.body.setCollisionGroup(this.scrollCollisionGroup);
    scroll.body.collides([this.playerCollisionGroup, this.scrollCollisionGroup]);
    output.push(scroll);
    return output
  }

  setup_level_3_stage_3() {
    console.log('setup_level_3_stage_3');
    var output = [];
    var scroll = game.add.sprite(830, 380, 'scroll');
    //  Enable if for physics. This creates a default rectangular body.
    game.physics.p2.enable(scroll);
    scroll.body.static = true;

    scroll.body.setCollisionGroup(this.scrollCollisionGroup);
    scroll.body.collides([this.playerCollisionGroup, this.scrollCollisionGroup]);
    output.push(scroll);
    return output
  }

  createKnife(y_index) {
    const knife = game.add.sprite(game.width, indexToGameHeight(y_index), 'knife');
    game.physics.p2.enable(knife);
    knife.body.kinematic = true;
    knife.body.setCollisionGroup(this.deadCollisionGroup);
    knife.body.collides(this.playerCollisionGroup);
    knife.body.moveLeft(256);
    this.knife = knife;
  }

  moveKnife(y_index) {
    if (this.knife) {
      this.knife.body.y = (this.knife.body.y + indexToGameHeight(y_index)) / 2;
    }
  }

  setupDeadZones() {
    var currentX = 0;
    var output = [];
    const deadline_y = game.height - DEADLINE_HEIGHT / 2;
    while (currentX < game.width) {
      var deadzone = game.add.sprite(currentX, deadline_y, 'spears');
      deadzone.anchor.setTo(0, 0);
      game.physics.p2.enable(deadzone);
      deadzone.body.y = game.height - DEADLINE_HEIGHT / 2;
      deadzone.body.static = true;
      deadzone.body.setCollisionGroup(this.deadCollisionGroup);

      deadzone.body.collides(this.playerCollisionGroup);
      output.push(deadzone);
      currentX += deadzone.width;
    }
    return output;
  }

  update() {

    if (this.cursors.left.isDown) {
      this.player.body.moveLeft(200);

      // if (player.facing != 'left') {
      //   player.facing = 'left';
      // }
    }
    else if (this.cursors.right.isDown) {
      this.player.body.moveRight(200);

      // if (player.facing != 'right') {
      //   player.facing = 'right';
      // }
    } else {
      this.player.body.velocity.x = 0;

      // if (player.facing != 'idle') {

      //   if (player.facing == 'left') {
      //   }
      //   else {
      //   }

      //   player.facing = 'idle';
      // }
    }

    if (this.cursors.up.isDown && game.time.now > this.jumpTimer && this.checkIfCanJump()) {
      this.player.body.moveUp(300);
      this.jumpTimer = game.time.now + 750;
    }
    if (this.knife && this.knife.x < 0) {
      this.knife.destroy();
      this.setKnifeTimeout();
    }
  }

  checkIfCanJump() {

    var result = false;

    for (var i = 0; i < game.physics.p2.world.narrowphase.contactEquations.length; i++) {
      var c = game.physics.p2.world.narrowphase.contactEquations[i];

      if (c.bodyA === this.player.body.data || c.bodyB === this.player.body.data) {
        var d = p2.vec2.dot(c.normalA, yAxis);

        if (c.bodyA === this.player.body.data) {
          d *= -1;
        }

        if (d > 0.5) {
          result = true;
        }
      }
    }

    return result;

  }

  touchPlayer(body, bodyB, shapeA, shapeB, equation) {
    // console.log("touchPlayer");
    if (body && body.sprite && (body.sprite.key === 'spears' || body.sprite.key === 'knife') && !this.playerSuper) {
      console.log("spears or knife");
      this.player.lifeCount--;
      this.lifeText.setText(this.player.lifeCount);
      this.player.body.y = 30;
      this.checkLose();
    } else if (body && body.sprite && body.sprite.key === 'scroll') {
      console.log("scroll");
      this.getScroll();
      body.sprite.destroy();
    }
  }

  getScroll(sprite1, sprite2) {
    this.player.scollGot++;
    this.gotScrollText.setText(this.player.scollGot);
    console.log('getScroll', this.player.scollGot, this.scrollGoal);

    if (this.player.scollGot >= this.scrollGoal) {
      this.win();
    }
  }

  win() {
    console.log('win');
    this.winlText.visible = true;

    setTimeout(() => {
      this.winlText.visible = false;

      this.cleanUp();

      this.nextRoom();
    }, 2000);
  }

  lose() {
    console.log('lose');
    this.cleanUp();
  }

  cleanUp() {
    console.log('cleanUp');
    this.player.scollGot = 0;
  }

  nextRoom() {
    console.log('nextRoom');
    stageID++;
    this.scrolls = this[stageList[stageID]]();
    this.scrollGoal = this.scrolls.length;
  }

  checkLose() {
    if (this.player.lifeCount <= 0) {
      this.lose();
    }
  }

  onSound(y0Pitch, y1Pitch, y0Amplitude, y1Amplitude) {
    // console.log(y0Pitch + " " + y1Pitch);
    const normalized0 = y0Pitch ;
    const normalized1 = y1Pitch ;
    var index = Math.round(normalized0 * NUMBER_OF_PITCH) % NUMBER_OF_PITCH;
    var index1 = Math.round(normalized1 * NUMBER_OF_PITCH) % NUMBER_OF_PITCH;
    //var singIndex = Math.round(normalized0 * 11);
    // console.log('noteStrings', soundModule.noteStrings[index]);
    //console.log('onSound',
    // normalized0, soundModule.noteStrings[singIndex],
    // normalized1, '');
    this.musicFloors.forEach((elem, id) => {
      if (Math.abs(id - index) < 3) {
        // const heightLimit = 500 - y0Amplitude * 70;
        const heightLimit = 500 - 400;
        if (elem.y > heightLimit) {
          elem.body.moveUp(300);
        } else {
          elem.body.y = heightLimit;
          elem.body.setZeroVelocity();
        }
        elem.loadTexture('wall');
      } else {
        elem.loadTexture('wall');

        if (elem.y < game.height - DEADLINE_HEIGHT) {
          elem.body.moveDown(80);
        } else if (elem.y < game.height) {
          elem.body.moveDown(40);
        } else {
          elem.body.y = game.height;
          elem.body.setZeroVelocity();
        }

        // elem.y = Phaser.Math.linear(elem.y, 500, 0.01);
      }
    });

    if (normalized1 > 0 && this.knifeEnabled) {
      if (!this.knife && !this.knifeIsCooldown) {
        this.createKnife(index1);
      } else {
        this.moveKnife(index1);
      }
    }
  }

  createWall(x, y) {
    var wall = game.add.sprite(x, y, 'wall');
    game.physics.p2.enable(wall);
    wall.body.static = true;

    wall.body.setCollisionGroup(this.playerCollisionGroup);
    wall.body.collides([this.playerCollisionGroup]);
    return wall;
  }

  createMusicFloor(x, y) {
    var wall = game.add.sprite(x, y, 'wall');
    game.physics.p2.enable(wall);
    wall.body.kinematic = true;

    wall.body.setCollisionGroup(this.musicFloorCollisionGroup);
    wall.body.collides([this.playerCollisionGroup, this.musicFloorCollisionGroup]);
    return wall;
  }
}

var game = new Phaser.Game(
  1280, 720, Phaser.AUTO, 'wrapper', new State());
<|endoftext|>


<commit_before>var chromosomes_ev=[];
var initial = '1111000011110000';
for ( var i = 0; i < 10; i++ ) {
    var this_one = initial;
    for ( var j = 0; j < 10; j ++ ) {
	this_one = mutate(this_one);
    }
    chromosomes_ev.push( this_one );
    $('#gen1').append("
"+this_one+"
");
}

$("#eval").submit(function(){
    for ( var j in chromosomes_ev) {
	console.log(chromosomes_ev[j]);
	$('#gen2').append("
"+chromosomes_ev[j]+"->"+max_ones(chromosomes_ev[j])+"
");
//	$('#gen2').append("
"+ JSON.stringify( chromosomes_ev[j] : max_ones(chromosomes_ev[j]) }+"
");
    }
    return false;
});<commit_msg>wrap up<commit_after>var chromosomes_ev=[];
var initial = '1111000011110000';
for ( var i = 0; i < 10; i++ ) {
    var this_one = initial;
    for ( var j = 0; j < 10; j ++ ) {
	this_one = mutate(this_one);
    }
    chromosomes_ev.push( this_one );
    $('#gen1').append("
"+this_one+"
");
}

$("#eval").submit(function(){
    for ( var j in chromosomes_ev) {
	console.log(chromosomes_ev[j]);
	$('#gen2').append("
"+chromosomes_ev[j]+"->"+max_ones(chromosomes_ev[j])+"
");
//	$('#gen2').append("
"+ JSON.stringify( { chromosomes_ev[j] : max_ones(chromosomes_ev[j]) } )+"
");
    }
    return false;
});<|endoftext|>


<commit_before>var Game = {};
var light = false;
var timerset = false;
var timersetflash = false;
var fading = false;
var currContext = "#1F3D5C";
Game.fps = 50;

Game.initialize = function() {
  this.entities = [];
  this.context = document.getElementById("viewport").getContext("2d");

  for(i =0; i< 17; i++){
    Game.addRect(i*32);
  }

  for(i =0; i< 800; i++){
    Game.addRain();
  }

};

Game.draw = function() {

  this.context.clearRect(0, 0, 512, 288);

  this.context.fillStyle = currContext;
  this.context.fillRect(0, 0, 512, 288);

  if(light == true && fading == false){
    fading = true; // we're starting to fade, so don't run this function more than once
    var r = 255, g = 255, b = 255; // starting color (white)
    var steps = 50;
    var dr = (31 - r) / steps; // how much red should be added each time
    var dg = (61 - g) / steps; // green
    var db = (92 - b) / steps; // blue
    var count = 0; // step counter
    var interval = setInterval(function() {
      currContext = 'rgb(' + Math.round(r + dr * count) + ','
                  + Math.round(g + dg * count) + ','
                  + Math.round(b + db * count) + ')';
      count++;
      if(count === steps) { // stop if done
          clearInterval(interval);
          fading = false; // we're done fading
          light = false; // light is now off
      }
    }, 30);
  }

  var lightTime = Math.floor(Math.random() * (7000 - 1000 + 1)) + 1000; // random amount of time between 3 and 7 seconds
  if(light == false && timerset == false){ //if the light is off, set a timer to light it after 5 sec
    setTimeout(function(){
      light = true;
      timerset = false;
    }, lightTime);
    timerset = true;
  }

  for (var i=0; i < this.entities.length; i++) {
    this.entities[i].draw(this.context);
  }
};

Game.update = function() {
  for (var i=0; i < this.entities.length; i++) {
    this.entities[i].update();
  }
  //update blocks in a repeating pattern
  for(var i = 0; i< 17; i++){
    if (this.entities[i].x < -32) {
      if(i == 0){
        this.entities[i].x = this.entities[16].tail;
      }else{
        this.entities[i].x = this.entities[i-1].tail;
      }
      this.entities[i].level = 0; //rand between 1 and 8;
    } else if (this.entities[i].x > 512) {
      if(i == 16){
        this.entities[i].x = this.entities[0].tail - 64;
      }else{
        this.entities[i].x = this.entities[i+1].tail - 64;
      }
      this.entities[i].level = this.entites[i].prevLevel; //return to prev.
    }
  }
};

Game.addRect = function(initX) {
  Game.entities.push(new Rect(initX));
};
Game.addRain = function() {
  Game.entities.push(new Rain());
};

Game.addPlayer = function(){
  Game.entites.push(new Player());
};
<commit_msg>Update game.js<commit_after>var Game = {};
var light = false;
var timerset = false;
var timersetflash = false;
var fading = false;
var currContext = "#1F3D5C";
Game.fps = 50;

Game.initialize = function() {
  this.entities = [];
  this.context = document.getElementById("viewport").getContext("2d");

  for(i =0; i< 17; i++){
    Game.addRect(i*32);
  }

  for(i =0; i< 800; i++){
    Game.addRain();
  }

};

Game.draw = function() {

  this.context.clearRect(0, 0, 512, 288);

  this.context.fillStyle = currContext;
  this.context.fillRect(0, 0, 512, 288);

  if(light == true && fading == false){
    fading = true; // we're starting to fade, so don't run this function more than once
    var r = 255, g = 255, b = 255; // starting color (white)
    var steps = 50;
    var dr = (31 - r) / steps; // how much red should be added each time
    var dg = (61 - g) / steps; // green
    var db = (92 - b) / steps; // blue
    var count = 0; // step counter
    var interval = setInterval(function() {
      currContext = 'rgb(' + Math.round(r + dr * count) + ','
                  + Math.round(g + dg * count) + ','
                  + Math.round(b + db * count) + ')';
      count++;
      if(count === steps) { // stop if done
          clearInterval(interval);
          fading = false; // we're done fading
          light = false; // light is now off
      }
    }, 30);
  }

  var lightTime = Math.floor(Math.random() * (7000 - 1000 + 1)) + 1000; // random amount of time between 3 and 7 seconds
  if(light == false && timerset == false){ //if the light is off, set a timer to light it after 5 sec
    setTimeout(function(){
      light = true;
      timerset = false;
    }, lightTime);
    timerset = true;
  }

  for (var i=0; i < this.entities.length; i++) {
    this.entities[i].draw(this.context);
  }
};

Game.update = function() {
  for (var i=0; i < this.entities.length; i++) {
    this.entities[i].update();
  }
  //update blocks in a repeating pattern
  for(var i = 0; i< 17; i++){
    if (this.entities[i].x < -32) {
      if(i == 0){
        this.entities[i].x = this.entities[16].tail;
      }else{
        this.entities[i].x = this.entities[i-1].tail;
      }
      this.entities[i].level = 0; //rand between 1 and 8;
    } else if (this.entities[i].x > 512) {
      if(i == 16){
        this.entities[i].x = this.entities[0].tail - 64;
      }else{
        this.entities[i].x = this.entities[i+1].tail - 64;
      }
      this.entities[i].level = this.entities[i].prevLevel; //return to prev.
    }
  }
};

Game.addRect = function(initX) {
  Game.entities.push(new Rect(initX));
};
Game.addRain = function() {
  Game.entities.push(new Rain());
};

Game.addPlayer = function(){
  Game.entites.push(new Player());
};
<|endoftext|>


<commit_before>/*
	Striped 2.5 by HTML5 Up!
	html5up.net | @n33co
	Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
*/

skel.init(
	{
		prefix: 'css/style',
		resetCSS: true,
		useOrientation: true,
		breakpoints: {
			'mobile': {
				range: '-640',
				lockViewport: true,
				containers: 'fluid',
				grid: {
					collapse: true
				}
			},
			'desktop': {
				range: '641-',
				containers: 1200
			},
			'wide': {
				range: '1201-'
			},
			'narrow': {
				range: '641-1200',
				containers: 960
			},
			'narrower': {
				range: '641-1000'
			}
		}
	},
	{
		panels: {
			panels: {
				sidePanel: {
					breakpoints: 'mobile',
					position: 'left',
					style: 'reveal',
					size: '250px',
					html: '

'
				},
				sidePanelNarrower: {
					breakpoints: 'narrower',
					position: 'left',
					style: 'reveal',
					size: '300px',
					html: '

'
				}
			},
			overlays: {
				titleBar: {
					breakpoints: 'mobile',
					position: 'top-left',
					width: '100%',
					height: 44,
					html: '

' +
						  '

'
				},
				titleBarNarrower: {
					breakpoints: 'narrower',
					position: 'top-left',
					width: '100%',
					height: 60,
					html: '

' +
						  '

'
				}
			}
		}
	}
);

$(function() {

	var $window = $(window), $document = $(document), $sc = $('#sidebar, #content'), tid;

	$window.load(function() {

		$window.resize(function() {
			window.clearTimeout(tid);
			tid = window.setTimeout(function() {
				if (skel.isActive('mobile') || skel.isActive('narrower'))
					$sc.css('min-height', '0').css('height', 'auto');
				else
					$sc.css('min-height', $window.height()).css('height', $document.height());
			}, 100);
		}).trigger('resize');

	});

});<commit_msg>Update init.js<commit_after>/*
	Striped 2.5 by HTML5 Up!
	html5up.net | @n33co
	Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
*/

skel.init(
	{
		prefix: '/css/style',
		resetCSS: true,
		useOrientation: true,
		breakpoints: {
			'mobile': {
				range: '-640',
				lockViewport: true,
				containers: 'fluid',
				grid: {
					collapse: true
				}
			},
			'desktop': {
				range: '641-',
				containers: 1200
			},
			'wide': {
				range: '1201-'
			},
			'narrow': {
				range: '641-1200',
				containers: 960
			},
			'narrower': {
				range: '641-1000'
			}
		}
	},
	{
		panels: {
			panels: {
				sidePanel: {
					breakpoints: 'mobile',
					position: 'left',
					style: 'reveal',
					size: '250px',
					html: '

'
				},
				sidePanelNarrower: {
					breakpoints: 'narrower',
					position: 'left',
					style: 'reveal',
					size: '300px',
					html: '

'
				}
			},
			overlays: {
				titleBar: {
					breakpoints: 'mobile',
					position: 'top-left',
					width: '100%',
					height: 44,
					html: '

' +
						  '

'
				},
				titleBarNarrower: {
					breakpoints: 'narrower',
					position: 'top-left',
					width: '100%',
					height: 60,
					html: '

' +
						  '

'
				}
			}
		}
	}
);

$(function() {

	var $window = $(window), $document = $(document), $sc = $('#sidebar, #content'), tid;

	$window.load(function() {

		$window.resize(function() {
			window.clearTimeout(tid);
			tid = window.setTimeout(function() {
				if (skel.isActive('mobile') || skel.isActive('narrower'))
					$sc.css('min-height', '0').css('height', 'auto');
				else
					$sc.css('min-height', $window.height()).css('height', $document.height());
			}, 100);
		}).trigger('resize');

	});

});
<|endoftext|>


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

	// an object where to store game information
	data : {
		// score
		score : 0
	},

	// Run on page load.
	"onload" : function () {
	// Initialize the video.
	if (!me.video.init("screen",  me.video.CANVAS, 1067, 600, true, '1.0')) {
		alert("Your browser does not support HTML5 canvas.");
		return;
	}

	// add "#debug" to the URL to enable the debug Panel
	if (document.location.hash === "#debug") {
		window.onReady(function () {
			me.plugin.register.defer(this, debugPanel, "debug");
		});
	}

	// Initialize the audio.
	me.audio.init("mp3,ogg");

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

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

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

	// Run on game resources loaded.
	"loaded" : function () {
		me.pool.register("player", game.PlayerEntity, true);

		me.state.set(me.state.MENU, new game.TitleScreen());
		me.state.set(me.state.PLAY, new game.PlayScreen());

		// Start the game.
		me.state.change(me.state.PLAY);
	}
};
<commit_msg>push 1 (2/3):comments<commit_after>
/* Game namespace */
var game = {

	// an object where to store game information
	data : {
		// score
		score : 0
	},

	// Run on page load.
	"onload" : function () {
	// Initialize the video.
	if (!me.video.init("screen",  me.video.CANVAS, 1067, 600, true, '1.0')) {
		alert("Your browser does not support HTML5 canvas.");
		return;
	}

	// add "#debug" to the URL to enable the debug Panel
	if (document.location.hash === "#debug") {
		window.onReady(function () {
			me.plugin.register.defer(this, debugPanel, "debug");
		});
	}

	// Initialize the audio.
	me.audio.init("mp3,ogg");

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

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

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

	// Run on game resources loaded.
	"loaded" : function () {
		me.pool.register("player", game.PlayerEntity, true);
		// player has been added to the "pool" of objects we can use
		me.state.set(me.state.MENU, new game.TitleScreen());
		me.state.set(me.state.PLAY, new game.PlayScreen());

		// Start the game.
		me.state.change(me.state.PLAY);
	}
};
<|endoftext|>


<commit_before>(function () {
    var inBrowser = typeof amber !== "undefined" && typeof amber.load === "function";
    function init() {
        smalltalk.initialize();

        /* Similar to jQuery(document).ready() */

        if (inBrowser && amber.smalltalkReady) {
            amber.smalltalkReady();
        }
    }

    if (inBrowser) {
        setTimeout(init, 0);
    } else {
        init();
    }
})();<commit_msg>init.js commented<commit_after>(function () {
    var inBrowser = typeof amber !== "undefined" && typeof amber.load === "function";
    function init() {
        smalltalk.initialize();

        /* Similar to jQuery(document).ready() */

        if (inBrowser && amber.smalltalkReady) {
            amber.smalltalkReady();
        }
    }

    if (inBrowser) {
        // init is lengthy process done in JavaScript.
        // setTimeout here postpones it, so DOM ready
        // event can occur sooner, thus load process
        // may appear optically faster.
        setTimeout(init, 0);
    } else {
        // In certain configurations, setTimeout is not feasible.
        // It is mainly for `amberc`-produced concatenated
        // node.js programs. There, the actual "main" appears
        // immediately after init, so it must happens synchronously.
        init();
    }
})();<|endoftext|>


<commit_before>import {React, Component, PropTypes} from '../imports';

/**
 * Renders a list of clickable buttons. The amount of initial visible buttons can be controlled with
 * the initialVisible property. The user is able to show more than these defined amount by clicking the "more" button.
 *
 * @props {Array} items List of items like {label: "Button 1", value: 1}
 * @props {number} initialVisible Number of items visible without expanding the list
 * @props {number} maxSelected Amount of maximum selectable buttons at once
 * @props {string} buttonClass Additional css classes for each button
 */
export class WSOptionButtons extends Component {
  static propTypes = {
    items: PropTypes.array,
    initialVisible: PropTypes.number,
    value: PropTypes.string,
    buttonClass: PropTypes.string,
    onChange: PropTypes.func
  };

  static defaultProps = {
    items: [],
    initialVisible: 3,
    value: null,
    buttonClass: '',
    onChange: () => {}
  };

  /**
   * @param {Object} props React props
   */
  constructor(props) {
    super(props);
    this.buttons = [];
    this.state = this.createState(props);
  }

  /**
   * Binds event listeners when element is attached to dom
   * @returns {void}
   */
  componentDidMount() {
    this.buttons.forEach(button => button.addEventListener('click', this.onClickButton));
    if (this.moreAnchor) {
      this.moreAnchor.addEventListener('click', this.onClickToggle);
    }
  }

  /**
   * Updates the state if props changes from outside
   * @param {Object} props React props
   * @returns {void}
   */
  componentWillReceiveProps(props) {
    this.setState(this.createState(props));
  }

  /**
   * Bind to new elements
   * @returns {void}
   */
  componentDidUpdate() {
    this.buttons.forEach(button => button.addEventListener('click', this.onClickButton));
    if (this.moreAnchor) {
      this.moreAnchor.addEventListener('click', this.onClickToggle);
    }
  }

  /**
   * Removes event listeners before element is detached from dom
   * @returns {void}
   */
  componentWillUnmount() {
    this.buttons.forEach(button => button.removeEventListener('click', this.onClickButton));
    if (this.moreAnchor) {
      this.moreAnchor.removeEventListener('click', this.onClickToggle);
    }
  }

  /**
   * Handles toggling visible amount
   * @param {MouseEvent} event JavaScript event object
   * @returns {void}
   */
  onClickToggle = event => {
    event.stopPropagation();

    if (this.state.visible === this.state.items.length) {
      this.setState({visible: this.props.initialVisible});
    } else {
      this.setState({visible: this.state.items.length});
    }
  };

  /**
   * Handles button selection
   * @param {MouseEvent} event JavaScript event object
   * @returns {void}
   */
  onClickButton = event => {
    event.stopPropagation();
    const clickedIndex = this.buttons.indexOf(event.currentTarget);
    // Mark other items as de-selected and toggle selection of clicked one
    this.state.items[clickedIndex].selected = !this.state.items[clickedIndex].selected;
    const value = this.state.items.filter(item => item.selected).map(item => item.value);
    // disabling no-unused-state as due to our createState method it seems that eslint can't recognize initial state
    // eslint-disable-next-line
    this.setState({items: this.state.items, value});
    // Notify html parents
    this.dispatchEvent('change', value);
    // Notify react and preact parents
    if (typeof this.props.onChange === 'function') {
      this.props.onChange(value);
    }
  };

  /**
   * Creates a state object from React props
   * @param {Object} props React props
   * @returns {Object}
   */
  createState(props) {
    const items = this.enrichItems(props.items);
    // If value is set mark related item as selected
    if (props.value) {
      if (!Array.isArray(props.value)) {
        props.value = [props.value];
      }
      props.value.forEach(value => {
        items.find(item => item.value === value).selected = true;
      });
    }
    return {
      items,
      visible: props.initialVisible,
      value: props.value
    };
  }

  /**
   * Used to convert the items if they are strings into the required object structure
   * @param {Array<String|Object>} items List of items represented as string or object
   * @returns {Array<Object>}
   */
  enrichItems(items) {
    return items.map(item => {
      if (typeof item === 'object') {
        return item;
      }
      return {label: item, value: item};
    });
  }

  /**
   * Renders the component
   * @returns {JSX}
   */
  render() {
    return (

 { this.element = element; }}>
        {this.state.items.map((item, index) =>
          (
            <div className={`option-button ${index < this.state.visible ? '' : 'is-hidden'}`}>
              <a
                href="#void"
                className={`${this.props.buttonClass} ${item.selected ? 'is-active' : ''}`}
                data-index=""
                ref={element => { this.buttons[index] = element; }}
              >
                {item.label || item.value}

))}
        <a
          href="#void"
          className={`show-more ${this.props.initialVisible < this.state.items.length ? 'is-hidden' : ''}`}
          ref={element => { this.moreAnchor = element; }}
        >
          {this.state.visible === this.state.items.length ? 'less' : 'more'}

    );
  }
}
<commit_msg>review: updating eslint disable line<commit_after>import {React, Component, PropTypes} from '../imports';

/**
 * Renders a list of clickable buttons. The amount of initial visible buttons can be controlled with
 * the initialVisible property. The user is able to show more than these defined amount by clicking the "more" button.
 *
 * @props {Array} items List of items like {label: "Button 1", value: 1}
 * @props {number} initialVisible Number of items visible without expanding the list
 * @props {number} maxSelected Amount of maximum selectable buttons at once
 * @props {string} buttonClass Additional css classes for each button
 */
export class WSOptionButtons extends Component {
  static propTypes = {
    items: PropTypes.array,
    initialVisible: PropTypes.number,
    value: PropTypes.string,
    buttonClass: PropTypes.string,
    onChange: PropTypes.func
  };

  static defaultProps = {
    items: [],
    initialVisible: 3,
    value: null,
    buttonClass: '',
    onChange: () => {}
  };

  /**
   * @param {Object} props React props
   */
  constructor(props) {
    super(props);
    this.buttons = [];
    this.state = this.createState(props);
  }

  /**
   * Binds event listeners when element is attached to dom
   * @returns {void}
   */
  componentDidMount() {
    this.buttons.forEach(button => button.addEventListener('click', this.onClickButton));
    if (this.moreAnchor) {
      this.moreAnchor.addEventListener('click', this.onClickToggle);
    }
  }

  /**
   * Updates the state if props changes from outside
   * @param {Object} props React props
   * @returns {void}
   */
  componentWillReceiveProps(props) {
    this.setState(this.createState(props));
  }

  /**
   * Bind to new elements
   * @returns {void}
   */
  componentDidUpdate() {
    this.buttons.forEach(button => button.addEventListener('click', this.onClickButton));
    if (this.moreAnchor) {
      this.moreAnchor.addEventListener('click', this.onClickToggle);
    }
  }

  /**
   * Removes event listeners before element is detached from dom
   * @returns {void}
   */
  componentWillUnmount() {
    this.buttons.forEach(button => button.removeEventListener('click', this.onClickButton));
    if (this.moreAnchor) {
      this.moreAnchor.removeEventListener('click', this.onClickToggle);
    }
  }

  /**
   * Handles toggling visible amount
   * @param {MouseEvent} event JavaScript event object
   * @returns {void}
   */
  onClickToggle = event => {
    event.stopPropagation();

    if (this.state.visible === this.state.items.length) {
      this.setState({visible: this.props.initialVisible});
    } else {
      this.setState({visible: this.state.items.length});
    }
  };

  /**
   * Handles button selection
   * @param {MouseEvent} event JavaScript event object
   * @returns {void}
   */
  onClickButton = event => {
    event.stopPropagation();
    const clickedIndex = this.buttons.indexOf(event.currentTarget);
    // Mark other items as de-selected and toggle selection of clicked one
    this.state.items[clickedIndex].selected = !this.state.items[clickedIndex].selected;
    const value = this.state.items.filter(item => item.selected).map(item => item.value);
    // eslint-disable-next-line react/no-unused-state
    this.setState({items: this.state.items, value});
    // Notify html parents
    this.dispatchEvent('change', value);
    // Notify react and preact parents
    if (typeof this.props.onChange === 'function') {
      this.props.onChange(value);
    }
  };

  /**
   * Creates a state object from React props
   * @param {Object} props React props
   * @returns {Object}
   */
  createState(props) {
    const items = this.enrichItems(props.items);
    // If value is set mark related item as selected
    if (props.value) {
      if (!Array.isArray(props.value)) {
        props.value = [props.value];
      }
      props.value.forEach(value => {
        items.find(item => item.value === value).selected = true;
      });
    }
    return {
      items,
      visible: props.initialVisible,
      value: props.value
    };
  }

  /**
   * Used to convert the items if they are strings into the required object structure
   * @param {Array<String|Object>} items List of items represented as string or object
   * @returns {Array<Object>}
   */
  enrichItems(items) {
    return items.map(item => {
      if (typeof item === 'object') {
        return item;
      }
      return {label: item, value: item};
    });
  }

  /**
   * Renders the component
   * @returns {JSX}
   */
  render() {
    return (

 { this.element = element; }}>
        {this.state.items.map((item, index) =>
          (
            <div className={`option-button ${index < this.state.visible ? '' : 'is-hidden'}`}>
              <a
                href="#void"
                className={`${this.props.buttonClass} ${item.selected ? 'is-active' : ''}`}
                data-index=""
                ref={element => { this.buttons[index] = element; }}
              >
                {item.label || item.value}

))}
        <a
          href="#void"
          className={`show-more ${this.props.initialVisible < this.state.items.length ? 'is-hidden' : ''}`}
          ref={element => { this.moreAnchor = element; }}
        >
          {this.state.visible === this.state.items.length ? 'less' : 'more'}

    );
  }
}
<|endoftext|>


<commit_before>function Pong() {
    "use strict"
    var version = 'v0.0.1';

    var WIDTH = 800, HEIGHT = 600, PI = Math.PI;
    var upArrow = 38, downArrow = 40;
    var canvas, context, keystate;
    var player, ai, ball;

    var bgImageReady = false;
    var bgImageSrc = 'img/background.png';
    var bgImage;

    player = {
        x: null,
        y: null,
        width: 20,
        height: 100,

        imageReady: false,
        imageSrc: 'img/paddle.png',
        image: null,

        update: function() {
            if (keystate[upArrow])
                this.y -= 7;
            if (keystate[downArrow])
                this.y += 7;

            this.y = Math.max(Math.min(this.y, HEIGHT - this.height), 0);
        },

        draw: function() {
            if (this.imageReady) {
                context.drawImage(this.image, this.x, this.y);
            }
        }
    }

    ai = {
        x: null,
        y: null,
        width: 20,
        height: 100,

        imageReady: false,
        imageSrc: 'img/paddle.png',
        image: null,

        update: function() {
            var dest_y = ball.y - (this.height + ball.side) * 0.5;
            this.y += (dest_y - this.y) * 0.1;

            this.y = Math.max(Math.min(this.y, HEIGHT - this.height), 0);
        },

        draw: function() {
            if (this.imageReady) {
                context.drawImage(this.image, this.x, this.y);
            }
        }
    }

    ball = {
        x: null,
        y: null,
        side: 20,
        speed: 5,
        velocity: null,

        imageReady: false,
        imageSrc: 'img/ball.png',
        image: null,

        serve: function(side) {
            var r = Math.random();
            this.x = side === 1 ? player.x + player.width: ai.x - this.side;
            this.y = (HEIGHT - this.side) * r;

            var phi = 0.1 * PI * (1 - 2 * r);
            this.velocity = {
                x: side * this.speed * Math.cos(phi),
                y: this.speed * Math.sin(phi)
            }
        },

        update: function() {
            this.x += this.velocity.x;
            this.y += this.velocity.y;

            if (this.y < 0 || this.y + this.side > HEIGHT) {
                var offset = this.velocity.y < 0 ? 0 - this.y : HEIGHT - (this.y + this.side);

                this.y += 2 * offset;
                this.velocity.y *= -1;
            }

            var intersect = function(ax, ay, aw, ah, bx, by, bw, bh) {
                var result =
                    ax < bx + bw &&
                    ay < by + bh &&
                    bx < ax + aw &&
                    by < ay + ah;
                return result;
            }

            var paddle = this.velocity.x < 0 ? player : ai;

            if (intersect(paddle.x, paddle.y, paddle.width, paddle.height, this.x, this.y, this.side, this.side)) {
                this.x = paddle === player ? player.x + player.width : ai.x - this.side;
                var n = (this.y + this.side - paddle.y) / (paddle.height + this.side); //Normalized value for location on the paddle where the ball hits
                var phi = (PI / 4) * (2 * n - 1);

                var smash = Math.abs(phi) > 0.2 * PI ? 1.5 : 1;
                this.velocity.x = smash * (paddle === player ? 1 : -1) * this.speed * Math.cos(phi);
                this.velocity.y = smash * this.speed * Math.sin(phi);
            }

            if (this.x + this.side < 0 || this.x > WIDTH) {
                this.serve(paddle === player ? 1 : -1);
            }
        },

        draw: function() {
            if (this.imageReady) {
                context.drawImage(this.image, this.x, this.y);
            }
        }
    }

    function init() {
        bgImage = new Image();
        bgImage.onload = function() {
            bgImageReady = true;
        }
        bgImage.src = bgImageSrc;

        player.image = new Image();
        player.image.onload = function() {
            player.imageReady = true;
            player.width = player.image.width;
            player.height = player.image.height;

            player.x = player.width;
            player.y = (HEIGHT - player.height) / 2;
        }
        player.image.src = player.imageSrc;

        ai.image = new Image();
        ai.image.onload = function() {
            ai.imageReady = true;
            ai.width = ai.image.width;
            ai.height = ai.image.height;

            ai.x = WIDTH - 2 * ai.width;
            ai.y = (HEIGHT - player.height) / 2;
        }
        ai.image.src = ai.imageSrc;

        ball.image = new Image();
        ball.image.onload = function() {
            ball.imageReady = true;
            ball.side = ball.image.width;
        }
        ball.image.src = ball.imageSrc;

        ball.serve(1);
    }

    function update() {
        ball.update();
        player.update();
        ai.update();
    }

    function draw() {
        if (bgImageReady) {
            context.drawImage(bgImage, 0, 0);
        }

        context.save();

        ball.draw();
        player.draw();
        ai.draw();

        context.restore();
    }

    this.startGame = function(elementId, directory) {
        canvas = document.getElementById(elementId);
        canvas.width = WIDTH;
        canvas.height = HEIGHT;
        context = canvas.getContext("2d");

        keystate = {};
        document.addEventListener("keydown", function(evt) {
            keystate[evt.keyCode] = true;
        });
        document.addEventListener("keyup", function(evt) {
            delete keystate[evt.keyCode];
        });

        init();

        bgImageSrc = directory + bgImageSrc;
        player.imageSrc = directory + player.imageSrc;
        ai.imageSrc = directory + ai.imageSrc;
        ball.imageSrc = directory + ball.imageSrc;

        var loop = function() {
            update();
            draw();

            window.requestAnimationFrame(loop, canvas);
        };
        window.requestAnimationFrame(loop, canvas);
    }
};
<commit_msg>Bumped version to v0.0.2<commit_after>function Pong() {
    "use strict"
    var version = 'v0.0.2';

    var WIDTH = 800, HEIGHT = 600, PI = Math.PI;
    var upArrow = 38, downArrow = 40;
    var canvas, context, keystate;
    var player, ai, ball;

    var bgImageReady = false;
    var bgImageSrc = 'img/background.png';
    var bgImage;

    player = {
        x: null,
        y: null,
        width: 20,
        height: 100,

        imageReady: false,
        imageSrc: 'img/paddle.png',
        image: null,

        update: function() {
            if (keystate[upArrow])
                this.y -= 7;
            if (keystate[downArrow])
                this.y += 7;

            this.y = Math.max(Math.min(this.y, HEIGHT - this.height), 0);
        },

        draw: function() {
            if (this.imageReady) {
                context.drawImage(this.image, this.x, this.y);
            }
        }
    }

    ai = {
        x: null,
        y: null,
        width: 20,
        height: 100,

        imageReady: false,
        imageSrc: 'img/paddle.png',
        image: null,

        update: function() {
            var dest_y = ball.y - (this.height + ball.side) * 0.5;
            this.y += (dest_y - this.y) * 0.1;

            this.y = Math.max(Math.min(this.y, HEIGHT - this.height), 0);
        },

        draw: function() {
            if (this.imageReady) {
                context.drawImage(this.image, this.x, this.y);
            }
        }
    }

    ball = {
        x: null,
        y: null,
        side: 20,
        speed: 5,
        velocity: null,

        imageReady: false,
        imageSrc: 'img/ball.png',
        image: null,

        serve: function(side) {
            var r = Math.random();
            this.x = side === 1 ? player.x + player.width: ai.x - this.side;
            this.y = (HEIGHT - this.side) * r;

            var phi = 0.1 * PI * (1 - 2 * r);
            this.velocity = {
                x: side * this.speed * Math.cos(phi),
                y: this.speed * Math.sin(phi)
            }
        },

        update: function() {
            this.x += this.velocity.x;
            this.y += this.velocity.y;

            if (this.y < 0 || this.y + this.side > HEIGHT) {
                var offset = this.velocity.y < 0 ? 0 - this.y : HEIGHT - (this.y + this.side);

                this.y += 2 * offset;
                this.velocity.y *= -1;
            }

            var intersect = function(ax, ay, aw, ah, bx, by, bw, bh) {
                var result =
                    ax < bx + bw &&
                    ay < by + bh &&
                    bx < ax + aw &&
                    by < ay + ah;
                return result;
            }

            var paddle = this.velocity.x < 0 ? player : ai;

            if (intersect(paddle.x, paddle.y, paddle.width, paddle.height, this.x, this.y, this.side, this.side)) {
                this.x = paddle === player ? player.x + player.width : ai.x - this.side;
                var n = (this.y + this.side - paddle.y) / (paddle.height + this.side); //Normalized value for location on the paddle where the ball hits
                var phi = (PI / 4) * (2 * n - 1);

                var smash = Math.abs(phi) > 0.2 * PI ? 1.5 : 1;
                this.velocity.x = smash * (paddle === player ? 1 : -1) * this.speed * Math.cos(phi);
                this.velocity.y = smash * this.speed * Math.sin(phi);
            }

            if (this.x + this.side < 0 || this.x > WIDTH) {
                this.serve(paddle === player ? 1 : -1);
            }
        },

        draw: function() {
            if (this.imageReady) {
                context.drawImage(this.image, this.x, this.y);
            }
        }
    }

    function init() {
        bgImage = new Image();
        bgImage.onload = function() {
            bgImageReady = true;
        }
        bgImage.src = bgImageSrc;

        player.image = new Image();
        player.image.onload = function() {
            player.imageReady = true;
            player.width = player.image.width;
            player.height = player.image.height;

            player.x = player.width;
            player.y = (HEIGHT - player.height) / 2;
        }
        player.image.src = player.imageSrc;

        ai.image = new Image();
        ai.image.onload = function() {
            ai.imageReady = true;
            ai.width = ai.image.width;
            ai.height = ai.image.height;

            ai.x = WIDTH - 2 * ai.width;
            ai.y = (HEIGHT - player.height) / 2;
        }
        ai.image.src = ai.imageSrc;

        ball.image = new Image();
        ball.image.onload = function() {
            ball.imageReady = true;
            ball.side = ball.image.width;
        }
        ball.image.src = ball.imageSrc;

        ball.serve(1);
    }

    function update() {
        ball.update();
        player.update();
        ai.update();
    }

    function draw() {
        if (bgImageReady) {
            context.drawImage(bgImage, 0, 0);
        }

        context.save();

        ball.draw();
        player.draw();
        ai.draw();

        context.restore();
    }

    this.startGame = function(elementId, directory) {
        canvas = document.getElementById(elementId);
        canvas.width = WIDTH;
        canvas.height = HEIGHT;
        context = canvas.getContext("2d");

        keystate = {};
        document.addEventListener("keydown", function(evt) {
            keystate[evt.keyCode] = true;
        });
        document.addEventListener("keyup", function(evt) {
            delete keystate[evt.keyCode];
        });

        init();

        bgImageSrc = directory + bgImageSrc;
        player.imageSrc = directory + player.imageSrc;
        ai.imageSrc = directory + ai.imageSrc;
        ball.imageSrc = directory + ball.imageSrc;

        var loop = function() {
            update();
            draw();

            window.requestAnimationFrame(loop, canvas);
        };
        window.requestAnimationFrame(loop, canvas);
    }
};
<|endoftext|>


<commit_before>/*global window:false*/
import _ from 'lodash';
import d3 from 'd3';

import * as tile from './tile';
import * as level from './level';
import * as board from './board';
import * as title_manager from './title_manager';

export class View {
  constructor(game) {
    this.game = game;
  }
  initialize () {}
}

export class LevelSelectorView extends View {
  get title() {
    return 'Quantum game';
  }
  get subtitle() {
    return '';
  }
  get className() {
    return 'view--level-selector';
  }
  initialize() {
    d3.select('.level-selector > ul')
      .selectAll('li')
      .data(level.levels)
      .enter()
      .append('li')
      .attr('class', 'level-item')
      .text((d) => `[${d.group}] ${d.i}. ${d.name}`)
      .on('click', (d) => {
        this.game.gameBoard.loadLevel(d);
        this.game.setView('game');
      });
  }
}

export class GameView extends View {
  get title() {
    return this.game.gameBoard.title;
  }
  get subtitle() {
    return this.game.gameBoard.subtitle;
  }
  get className() {
    return 'view--game';
  }
  initialize() {
    this.game.createGameBoard();
    this.game.bindMenuEvents();
  }

}

export class EncyclopediaSelectorView extends View {
  get title() {
    return 'Encyclopedia';
  }
  get subtitle() {
    return '';
  }
  get className() {
    return 'view--encyclopedia-selector';
  }
  initialize() {
    this.createSelectorEntries();
    this.bindMenuEvents();
  }
  createSelectorEntries() {
    const items = d3.select('.encyclopedia-selector > ul')
      .selectAll('li')
      .data(tile.nonVacuumTiles)
      .enter()
      .append('li')
      .append('button')
      .on('click', (d) => {
        this.game.setEncyclopediaItem(d);
        this.game.setView('encyclopediaItem');
      });
    items
      .append('svg')
      .attr('viewBox', '0 0 100 100')
      .append('use')
      .attr('xlink:href', (d) => `#${tile[d].svgName}`)
      .attr('transform', 'translate(50, 50)');
    items
      .append('h4')
      .text((d) => tile[d].desc.name);
  }
  bindMenuEvents() {
    d3.select('.bottom-bar__back-to-game-button').on('click', () => {
      this.game.setView('game');
    });
  }
}

export class EncyclopediaItemView extends View {
  get title() {
    return tile[this.game.currentEncyclopediaItem].desc.name;
  }
  get subtitle() {
    return '';
  }
  get className() {
    return 'view--encyclopedia-item';
  }
  initialize() {
    this.bindMenuEvents();
  }
  resetContent() {
    if (!this.game.currentEncyclopediaItem) {
      return;
    }
    const container = d3.select('.encyclopedia-item')
      .datum(this.game.currentEncyclopediaItem);
    container
      .html(null);
    const article = container.append('article');
    article
      .append('svg')
      .attr('viewBox', '0 0 100 100')
      .append('use')
      .attr('xlink:href', (d) => `#${tile[d].svgName}`)
      .attr('transform', 'translate(50, 50)');
    article
      .append('h4')
      .text((d) => tile[d].desc.name);
    article
      .append('div')
      .classed('content', true)
      .text((d) => tile[d].desc.summary);
  }
  bindMenuEvents() {
    d3.select('.bottom-bar__back-to-encyclopedia-selector-button').on('click', () => {
      this.game.setView('encyclopediaSelector');
    });
  }
}

export class Game {
  constructor() {
    // Outer dependencies and controllers
    this.titleManager = null;
    this.storage = localStorage;
    // View definitions
    this.views = this.createViews();
    // State
    this.gameBoard = null;
    this.currentEncyclopediaItem = null;
  }

  createViews() {
    return {
      levelSelector: new LevelSelectorView(this),
      game: new GameView(this),
      encyclopediaSelector: new EncyclopediaSelectorView(this),
      encyclopediaItem: new EncyclopediaItemView(this),
    }
  }

  setView(viewName) {
    if (!_.has(this.views, viewName)) {
      window.console.error(`Invalid view: ${viewName}`);
      return;
    }
    this.currentView = this.views[viewName];
    // Set titles
    this.titleManager.setTitle(this.currentView.title);
    this.titleManager.setDescription(this.currentView.subtitle);
    this.titleManager.displayMessage('', 'success');
    // Switch visible content
    d3.selectAll(`.${this.currentView.className}`).classed('view--hidden', false);
    d3.selectAll(`.view:not(.${this.currentView.className})`).classed('view--hidden', true);
  }

  setEncyclopediaItem(item) {
    this.currentEncyclopediaItem = item;
    // Reset the encyclopedia item view
    this.views.encyclopediaItem.resetContent();
  }

  htmlReady() {
    // Initialize views' controllers
    for (let view in this.views) {
      this.views[view].initialize();
    }
    this.setView('game');

    // for debugging purposes
    window.gameBoard = this.gameBoard;
    window.tile = tile;
  }

  createGameBoard() {
    const demoLevel = new level.Level(level.levels[1]);
    this.titleManager = new title_manager.TitleManager(
      d3.select('.top-bar__title'),
      d3.select('.top-bar__subtitle'));
    this.gameBoard = new board.Board(
      demoLevel,
      d3.select('#game svg'),
      d3.select('#helper'),
      this.titleManager,
      level.levels,
      this.storage);
    this.gameBoard.reset();
    this.gameBoard.setAnimationControls(
      d3.select('.bottom-bar__animation-controls'));
  }

  bindMenuEvents() {
    d3.select('.top-bar__menu-button').on('click', () => {
      this.gameBoard.stop();
      this.setView('levelSelector');
    });
    d3.select('.bottom-bar__help-button').on('click', () => {
      this.gameBoard.stop();
      this.setView('encyclopediaSelector');
    });
  }
}
<commit_msg>feat(encyclopedia) flavour text<commit_after>/*global window:false*/
import _ from 'lodash';
import d3 from 'd3';

import * as tile from './tile';
import * as level from './level';
import * as board from './board';
import * as title_manager from './title_manager';

export class View {
  constructor(game) {
    this.game = game;
  }
  initialize () {}
}

export class LevelSelectorView extends View {
  get title() {
    return 'Quantum game';
  }
  get subtitle() {
    return '';
  }
  get className() {
    return 'view--level-selector';
  }
  initialize() {
    d3.select('.level-selector > ul')
      .selectAll('li')
      .data(level.levels)
      .enter()
      .append('li')
      .attr('class', 'level-item')
      .text((d) => `[${d.group}] ${d.i}. ${d.name}`)
      .on('click', (d) => {
        this.game.gameBoard.loadLevel(d);
        this.game.setView('game');
      });
  }
}

export class GameView extends View {
  get title() {
    return this.game.gameBoard.title;
  }
  get subtitle() {
    return this.game.gameBoard.subtitle;
  }
  get className() {
    return 'view--game';
  }
  initialize() {
    this.game.createGameBoard();
    this.game.bindMenuEvents();
  }

}

export class EncyclopediaSelectorView extends View {
  get title() {
    return 'Encyclopedia';
  }
  get subtitle() {
    return '';
  }
  get className() {
    return 'view--encyclopedia-selector';
  }
  initialize() {
    this.createSelectorEntries();
    this.bindMenuEvents();
  }
  createSelectorEntries() {
    const items = d3.select('.encyclopedia-selector > ul')
      .selectAll('li')
      .data(tile.nonVacuumTiles)
      .enter()
      .append('li')
      .append('button')
      .on('click', (d) => {
        this.game.setEncyclopediaItem(d);
        this.game.setView('encyclopediaItem');
      });
    items
      .append('svg')
      .attr('viewBox', '0 0 100 100')
      .append('use')
      .attr('xlink:href', (d) => `#${tile[d].svgName}`)
      .attr('transform', 'translate(50, 50)');
    items
      .append('h4')
      .text((d) => tile[d].desc.name);
  }
  bindMenuEvents() {
    d3.select('.bottom-bar__back-to-game-button').on('click', () => {
      this.game.setView('game');
    });
  }
}

export class EncyclopediaItemView extends View {
  get title() {
    return tile[this.game.currentEncyclopediaItem].desc.name;
  }
  get subtitle() {
    return '';
  }
  get className() {
    return 'view--encyclopedia-item';
  }
  initialize() {
    this.bindMenuEvents();
  }
  resetContent() {
    if (!this.game.currentEncyclopediaItem) {
      return;
    }
    const container = d3.select('.encyclopedia-item')
      .datum(tile[this.game.currentEncyclopediaItem]);
    container
      .html(null);
    const article = container.append('article');
    article
      .append('svg')
      .attr('viewBox', '0 0 100 100')
      .append('use')
      .attr('xlink:href', (d) => `#${d.svgName}`)
      .attr('transform', 'translate(50, 50)');
    article
      .append('h4')
      .text((d) => d.desc.name);
    article
      .append('div')
      .classed('content', true)
      .text((d) => d.desc.summary);

    article
      .append('div')
      .classed('content', true)
      .append('i')
      .text((d) => `"${d.desc.flavour}"`);
  }
  bindMenuEvents() {
    d3.select('.bottom-bar__back-to-encyclopedia-selector-button').on('click', () => {
      this.game.setView('encyclopediaSelector');
    });
  }
}

export class Game {
  constructor() {
    // Outer dependencies and controllers
    this.titleManager = null;
    this.storage = localStorage;
    // View definitions
    this.views = this.createViews();
    // State
    this.gameBoard = null;
    this.currentEncyclopediaItem = null;
  }

  createViews() {
    return {
      levelSelector: new LevelSelectorView(this),
      game: new GameView(this),
      encyclopediaSelector: new EncyclopediaSelectorView(this),
      encyclopediaItem: new EncyclopediaItemView(this),
    }
  }

  setView(viewName) {
    if (!_.has(this.views, viewName)) {
      window.console.error(`Invalid view: ${viewName}`);
      return;
    }
    this.currentView = this.views[viewName];
    // Set titles
    this.titleManager.setTitle(this.currentView.title);
    this.titleManager.setDescription(this.currentView.subtitle);
    this.titleManager.displayMessage('', 'success');
    // Switch visible content
    d3.selectAll(`.${this.currentView.className}`).classed('view--hidden', false);
    d3.selectAll(`.view:not(.${this.currentView.className})`).classed('view--hidden', true);
  }

  setEncyclopediaItem(item) {
    this.currentEncyclopediaItem = item;
    // Reset the encyclopedia item view
    this.views.encyclopediaItem.resetContent();
  }

  htmlReady() {
    // Initialize views' controllers
    for (let view in this.views) {
      this.views[view].initialize();
    }
    this.setView('game');

    // for debugging purposes
    window.gameBoard = this.gameBoard;
    window.tile = tile;
  }

  createGameBoard() {
    const demoLevel = new level.Level(level.levels[1]);
    this.titleManager = new title_manager.TitleManager(
      d3.select('.top-bar__title'),
      d3.select('.top-bar__subtitle'));
    this.gameBoard = new board.Board(
      demoLevel,
      d3.select('#game svg'),
      d3.select('#helper'),
      this.titleManager,
      level.levels,
      this.storage);
    this.gameBoard.reset();
    this.gameBoard.setAnimationControls(
      d3.select('.bottom-bar__animation-controls'));
  }

  bindMenuEvents() {
    d3.select('.top-bar__menu-button').on('click', () => {
      this.gameBoard.stop();
      this.setView('levelSelector');
    });
    d3.select('.bottom-bar__help-button').on('click', () => {
      this.gameBoard.stop();
      this.setView('encyclopediaSelector');
    });
  }
}
<|endoftext|>


<commit_before>/*
 *    game.js
 *    All of the magic happens here
 */

YINS.Game = function(game) {

};<commit_msg>Add create and update functions to game state<commit_after>/*
 *    game.js
 *    All of the magic happens here
 */

YINS.Game = function(game) {

};

YINS.Game.prototype = {

	create: function() {

	},

	update: function() {

	}
};<|endoftext|>


<commit_before>'use strict';
(function () {
  var loadJsonFile = function(filename) {
    var res;
    $.ajax({
            async: false,
            url : filename,
            success : function(data) {
              res = data;
            }
    });
    return res;
  }

  var lab = {
    name: 'My Awesome Lab',
    detector: {
      rate: 1
    },
    data: 0,
    reputation: 0,
    money: 0,
    researchHistogram: new Histogram('#ResearchHist'),
    getGrant: function () {
      this.money += this.reputation * 5;  // TODO: adjust factor, 5
    },
    acquire: function (amount) {
      this.data += amount;
      this.researchHistogram.add_events(amount);
    },
    research: function (cost, reputation) {
      if (this.data >= cost) {
        this.data -= cost;
        this.reputation += reputation;
        return true;
      }
      return false;
    },
    buy: function(cost) {
      if (this.money >= cost) {
        this.money -= cost;
        return true;
      }
      return false;
    },
    sell: function(cost) {
      this.money += cost;
    }
  };

  var research = loadJsonFile('json/research.json');
  research.map(function (item) {  // define additional stuff on the objects
    item.level = 0;
    item.is_visible = function () {
      return this.level > 0 || lab.data >= this.cost * .7;
    };
    item.is_available = function () {
      return lab.data >= this.cost;
    };
    item.research = function () {
      if (lab.research(this.cost, this.reputation)) {
        this.level++;
        this.cost = Math.round(this.cost * this.cost_increase);
      }
    };
  });

  var workers = loadJsonFile('json/workers.json');
  workers.map(function (worker) {
    worker.hired = 0;
    worker.is_visible = function () {
      return this.hired > 0 || lab.money >= this.cost * .7;
    };
    worker.is_available = function () {
      return lab.money >= this.cost;
    };
    worker.hire = function() {
      if (lab.buy(this.cost)) {
        this.hired++;
        this.cost = Math.round(this.cost * this.cost_increase);
      }
    };
  });

  var upgrades = loadJsonFile('json/upgrades.json');
  upgrades.map(function (upgrade) {
    upgrade.getReceiver = function() {
      if (this.type === "detector") {
        return lab.detector;
      } else {
        var context;
        if (this.type === "research") { context = research; }
        else if (this.type === "hr") { context = workers; }
        else { return null; }
        for (var i = 0; i < context.length; i++) {
          if (context[i].name === this.receiver) {
            return context[i];
          }
        }
        return null;
      }
    };
    upgrade.hasReceiver = function () {
      if (this.type === "detector") {
        return true;
      }
      var rec = this.getReceiver();
      if (this.type === "research") {
        return rec.level > 0;
      } else if (this.type === "hr") {
        return rec.hired > 0;
      }
      return false;
    };
    upgrade.is_visible = function () {
      return !this.used && this.hasReceiver() && lab.money >= this.cost * .7;
    };
    upgrade.is_available = function () {
      return !this.used && this.hasReceiver() && lab.money >= this.cost;
    };
    upgrade.buy = function () {
      if (!this.used && lab.buy(this.cost)) {
        this.used = true;
        var rec = this.getReceiver();
        if (rec) {
          rec[this.property] = rec[this.property] * this.factor + this.constant;
        }
      }
    };
  });

  var app = angular.module('particleClicker', []);

  app.filter('currency', ['$filter', function ($filter) {
    return function (input) {
      return 'JTN ' + $filter('niceNumber')(input);
    };
  }]);

  app.filter('niceNumber', ['$filter', function ($filter) {
    return function (number) {
      var abs = Math.abs(number);
      if (abs >= Math.pow(10, 12)) {
        number = (number / Math.pow(10, 12)).toFixed(3) + "T";
      } else if (abs >= Math.pow(10, 9)) {
        number = (number / Math.pow(10, 9)).toFixed(3) + "B";
      } else if (abs >= Math.pow(10, 6)) {
        number = (number / Math.pow(10, 6)).toFixed(3) + "M";
      } else if (abs >= Math.pow(10, 3)) {
        number = (number / Math.pow(10, 3)).toFixed(3) + "k";
      } else {
        number = number.toFixed(0);
      }
      return number;
    };
  }]);

  app.controller('DetectorController', function () {
    this.click = function () {
      lab.acquire(lab.detector.rate);
      detector.addEvent();
      return false;
    };
  });

  app.controller('LabController', ['$interval', function ($interval) {
    this.lab = lab;
    $interval(function () {  // one tick
      lab.getGrant();
      var sum = 0;
      for (var i = 0; i < workers.length; i++) {
        sum += workers[i].hired * workers[i].rate;
      }
      lab.acquire(sum);
    }, 1000);
  }]);

  app.controller('ResearchController', function () {
    this.research = research;
  });

  app.controller('HRController', function () {
    this.workers = workers;
  });

  app.controller('UpgradesController', function () {
    this.upgrades = upgrades;
  });
})();

<commit_msg>Consistency.<commit_after>'use strict';
(function() {
  var loadJsonFile = function(filename) {
    var res;
    $.ajax({
      async: false,
      url : filename,
      success : function(data) {
        res = data;
      }
    });
    return res;
  }

  var lab = {
    name: 'My Awesome Lab',
    detector: {
      rate: 1
    },
    data: 0,
    reputation: 0,
    money: 0,
    researchHistogram: new Histogram('#ResearchHist'),
    getGrant: function() {
      this.money += this.reputation * 5;  // TODO: adjust factor, 5
    },
    acquire: function(amount) {
      this.data += amount;
      this.researchHistogram.add_events(amount);
    },
    research: function(cost, reputation) {
      if (this.data >= cost) {
        this.data -= cost;
        this.reputation += reputation;
        return true;
      }
      return false;
    },
    buy: function(cost) {
      if (this.money >= cost) {
        this.money -= cost;
        return true;
      }
      return false;
    },
    sell: function(cost) {
      this.money += cost;
    }
  };

  var research = loadJsonFile('json/research.json');
  research.map(function(item) {  // define additional stuff on the objects
    item.level = 0;
    item.is_visible = function() {
      return this.level > 0 || lab.data >= this.cost * .7;
    };
    item.is_available = function() {
      return lab.data >= this.cost;
    };
    item.research = function() {
      if (lab.research(this.cost, this.reputation)) {
        this.level++;
        this.cost = Math.round(this.cost * this.cost_increase);
      }
    };
  });

  var workers = loadJsonFile('json/workers.json');
  workers.map(function(worker) {
    worker.hired = 0;
    worker.is_visible = function() {
      return this.hired > 0 || lab.money >= this.cost * .7;
    };
    worker.is_available = function() {
      return lab.money >= this.cost;
    };
    worker.hire = function() {
      if (lab.buy(this.cost)) {
        this.hired++;
        this.cost = Math.round(this.cost * this.cost_increase);
      }
    };
  });

  var upgrades = loadJsonFile('json/upgrades.json');
  upgrades.map(function(upgrade) {
    upgrade.getReceiver = function() {
      if (this.type === "detector") {
        return lab.detector;
      } else {
        var context;
        if (this.type === "research") { context = research; }
        else if (this.type === "hr") { context = workers; }
        else { return null; }
        for (var i = 0; i < context.length; i++) {
          if (context[i].name === this.receiver) {
            return context[i];
          }
        }
        return null;
      }
    };
    upgrade.hasReceiver = function() {
      if (this.type === "detector") {
        return true;
      }
      var rec = this.getReceiver();
      if (this.type === "research") {
        return rec.level > 0;
      } else if (this.type === "hr") {
        return rec.hired > 0;
      }
      return false;
    };
    upgrade.is_visible = function() {
      return !this.used && this.hasReceiver() && lab.money >= this.cost * .7;
    };
    upgrade.is_available = function() {
      return !this.used && this.hasReceiver() && lab.money >= this.cost;
    };
    upgrade.buy = function() {
      if (!this.used && lab.buy(this.cost)) {
        this.used = true;
        var rec = this.getReceiver();
        if (rec) {
          rec[this.property] = rec[this.property] * this.factor + this.constant;
        }
      }
    };
  });

  var app = angular.module('particleClicker', []);

  app.filter('currency', ['$filter', function($filter) {
    return function(input) {
      return 'JTN ' + $filter('niceNumber')(input);
    };
  }]);

  app.filter('niceNumber', ['$filter', function($filter) {
    return function(number) {
      var abs = Math.abs(number);
      if (abs >= Math.pow(10, 12)) {
        number = (number / Math.pow(10, 12)).toFixed(3) + "T";
      } else if (abs >= Math.pow(10, 9)) {
        number = (number / Math.pow(10, 9)).toFixed(3) + "B";
      } else if (abs >= Math.pow(10, 6)) {
        number = (number / Math.pow(10, 6)).toFixed(3) + "M";
      } else if (abs >= Math.pow(10, 3)) {
        number = (number / Math.pow(10, 3)).toFixed(3) + "k";
      } else {
        number = number.toFixed(0);
      }
      return number;
    };
  }]);

  app.controller('DetectorController', function() {
    this.click = function() {
      lab.acquire(lab.detector.rate);
      detector.addEvent();
      return false;
    };
  });

  app.controller('LabController', ['$interval', function($interval) {
    this.lab = lab;
    $interval(function() {  // one tick
      lab.getGrant();
      var sum = 0;
      for (var i = 0; i < workers.length; i++) {
        sum += workers[i].hired * workers[i].rate;
      }
      lab.acquire(sum);
    }, 1000);
  }]);

  app.controller('ResearchController', function() {
    this.research = research;
  });

  app.controller('HRController', function() {
    this.workers = workers;
  });

  app.controller('UpgradesController', function() {
    this.upgrades = upgrades;
  });
})();

<|endoftext|>


<commit_before>$(function(){
  $.getJSON("/api/rsvp", function(data) {
    $.each(data, function(key, val) {
      var items = [];

      $.each(val.names, function(key, val) {
        if(val){
          items.push('
' + val + '
');
        }
      });
      $('RSVP ON '+new Date(val.lastModified*1000)+'').appendTo("#names");
      if(val.title){
        $('
Party Of '+val.title+'').appendTo('#names');
      }
      $('
'+items.join('')+'
').appendTo('#names');
      if(val.message){
        $('Message:
'+val.message+'').appendTo('#names');
      }

      $('
').appendTo('#names');
    });
  });
});
<commit_msg>remove rsvp on<commit_after>$(function(){
  $.getJSON("/api/rsvp", function(data) {
    $.each(data, function(key, val) {
      var items = [];

      $.each(val.names, function(key, val) {
        if(val){
          items.push('
' + val + '
');
        }
      });
      $(''+new Date(val.lastModified*1000)+'').appendTo("#names");
      if(val.title){
        $('
Party Of '+val.title+'').appendTo('#names');
      }
      $('
'+items.join('')+'
').appendTo('#names');
      if(val.message){
        $('Message:
'+val.message+'').appendTo('#names');
      }

      $('
').appendTo('#names');
    });
  });
});
<|endoftext|>


<commit_before>var game = new Phaser.Game(
    800, 600,
    Phaser.AUTO,
    'gamediv',
    {
        preload: preload,
        create: create,
        update: update
    });

function preload() {
    game.load.tilemap('map', 'assets/map.json', null, Phaser.Tilemap.TILED_JSON);

    game.load.image('level', 'assets/level.png');
    game.load.image('background', 'assets/bg.png');

    game.load.atlasJSONHash('character', 'assets/character.png', 'assets/character.json');
}

var map;
var layer;
var player;
var facing = "left";
var cursors;
var jumpButton;
var hozMove = 160; // walk
var vertMove = -180; // jump
var jumpTimer = 0;

function create() {
    //Background
    game.stage.backgroundColor = '#FFFFFF';
    game.add.tileSprite(0, 0, 2000, 600, 'background');

    //Physik
    game.physics.startSystem(Phaser.Physics.ARCADE);

    //Tilemap & Level
    map = game.add.tilemap('map');
    map.addTilesetImage('level');
    layer = map.createLayer('Kachelebene 1');

    // Collisions
    map.setCollisionByExclusion([1, 31]);

    // Resize World
    layer.resizeWorld();

    // Player & Animations
    player = game.add.sprite(1, 5 * 70, 'character', 'p1_walk01.png');
    player.animations.add('walk', [
        'p1_walk01.png',
        'p1_walk02.png',
        'p1_walk03.png',
        'p1_walk04.png',
        'p1_walk05.png',
        'p1_walk06.png',
        'p1_walk07.png',
        'p1_walk08.png',
        'p1_walk09.png'
    ], 30, false, false);

    // Player Physics
    game.physics.enable(player);
    player.body.bounce.y = 0.1;
    player.body.gravity.y = 160;

    // Controls
    cursors = game.input.keyboard.createCursorKeys();
    jumpButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);

    // Set Camera
    game.camera.x = player.body.x - 150;
    game.camera.y = player.body.y;
}

function update() {
    // Check collisions & Move player forward
    game.physics.arcade.collide(player, layer);
    player.body.velocity.x = 10;

    // Update Camera
    game.camera.y = player.body.y;
    game.camera.x = game.time.now / 100;
    if (!player.inCamera) {
        playerOOC();
    }

    if (cursors.left.isDown) {
        player.body.velocity.x = -hozMove;
        player.animations.play('walk', 30);
    }
    else if (cursors.right.isDown) {
        player.body.velocity.x = hozMove;
        player.animations.play('walk', 30);
    }
    else {
        player.animations.play('walk', 10);
    }

    if (jumpButton.isDown && player.body.onFloor() && game.time.now > jumpTimer) {
        player.body.velocity.y = vertMove;
        jumpTimer = game.time.now + 650;
    }
}

function playerOOC() {
    alert("Player OOC!");
    location.reload();
}<commit_msg>better camera movement<commit_after>var game = new Phaser.Game(
    800, 600,
    Phaser.AUTO,
    'gamediv',
    {
        preload: preload,
        create: create,
        update: update
    });

function preload() {
    game.load.tilemap('map', 'assets/map.json', null, Phaser.Tilemap.TILED_JSON);

    game.load.image('level', 'assets/level.png');
    game.load.image('background', 'assets/bg.png');

    game.load.atlasJSONHash('character', 'assets/character.png', 'assets/character.json');
}

var map;
var layer;
var player;
var cursors;
var jumpButton;
var hozMove = 160; // walk
var vertMove = -180; // jump
var jumpTimer = 0;
var cameraPosX;

function create() {
    //Background
    game.stage.backgroundColor = '#FFFFFF';
    game.add.tileSprite(0, 0, 2000, 600, 'background');

    //Physik
    game.physics.startSystem(Phaser.Physics.ARCADE);

    //Tilemap & Level
    map = game.add.tilemap('map');
    map.addTilesetImage('level');
    layer = map.createLayer('Kachelebene 1');

    // Collisions
    map.setCollisionByExclusion([1, 31]);

    // Resize World
    layer.resizeWorld();

    // Player & Animations
    player = game.add.sprite(1, 5 * 70, 'character', 'p1_walk01.png');
    player.animations.add('walk', [
        'p1_walk01.png',
        'p1_walk02.png',
        'p1_walk03.png',
        'p1_walk04.png',
        'p1_walk05.png',
        'p1_walk06.png',
        'p1_walk07.png',
        'p1_walk08.png',
        'p1_walk09.png'
    ], 30, false, false);

    // Player Physics
    game.physics.enable(player);
    player.body.bounce.y = 0.1;
    player.body.gravity.y = 160;

    // Controls
    cursors = game.input.keyboard.createCursorKeys();
    jumpButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);

    // Set Camera
    cameraPosX = player.body.x - 150;
    game.camera.x = cameraPosX;
    game.camera.y = player.body.y;
}

function update() {
    // Check collisions & Move player forward
    game.physics.arcade.collide(player, layer);
    player.body.velocity.x = 10;

    // Update Camera
    if (game.camera.x <= player.body.x - 600)
        cameraPosX += 2;

    game.camera.y = player.body.y;
    game.camera.x = cameraPosX++;

    if (!player.inCamera) {
        playerOOC();
    }

    if (cursors.left.isDown) {
        player.body.velocity.x = -hozMove;
        player.animations.play('walk', 30);
    }
    else if (cursors.right.isDown) {
        player.body.velocity.x = hozMove;
        player.animations.play('walk', 30);
    }
    else {
        player.animations.play('walk', 10);
    }

    if (jumpButton.isDown && player.body.onFloor() && game.time.now > jumpTimer) {
        player.body.velocity.y = vertMove;
        jumpTimer = game.time.now + 650;
    }
}

function playerOOC() {
    alert("Game Over!");
    location.reload();
}<|endoftext|>