<repo_name>svinotavr/JavascriptPhaserTutorials<file_sep>/Tutorial files/M13-Point-and-Click/05-collect-items/js/prefabs/Item.js
var PointClk = PointClk || {};

PointClk.Item = function(state, x, y, data) {
  Phaser.Sprite.call(this, state.game, x, y, data.asset);

  this.game = state.game;
  this.state = state;
  this.anchor.setTo(0.5);

  this.data = data;
};

PointClk.Item.prototype = Object.create(Phaser.Sprite.prototype);
PointClk.Item.prototype.constructor = PointClk.Item;<file_sep>/Tutorial files/M9-RPG/04-customizable-touch-control/js/states/Game.js
var RPG = RPG || {};

RPG.GameState = {

  init: function(currentLevel) {    
    //keep track of the current level
    this.currentLevel = currentLevel ? currentLevel : 'map1';

    //constants
    this.PLAYER_SPEED = 90;
    
    //no gravity in a top-down game
    this.game.physics.arcade.gravity.y = 0;    

    //keyboard cursors
    this.cursors = this.game.input.keyboard.createCursorKeys();
  },
  create: function() {   

    this.game.onscreenControls = this.game.plugins.add(Phaser.Plugin.OnscreenControls);

    this.loadLevel();
  },   
  update: function() {    
    
  },     
  loadLevel: function(){
    //create a tilemap object
    this.map = this.add.tilemap(this.currentLevel);
    
    //join the tile images to the json data
    this.map.addTilesetImage('terrains', 'tilesheet');
    
    //create tile layers
    this.backgroundLayer = this.map.createLayer('backgroundLayer');
    this.collisionLayer = this.map.createLayer('collisionLayer');
    
    //send background to the back
    this.game.world.sendToBack(this.backgroundLayer);
    
    //collision layer should be collisionLayer
    this.map.setCollisionBetween(1,16, true, 'collisionLayer');
    
    //resize the world to fit the layer
    this.collisionLayer.resizeWorld();

    //create player
    var playerData = {
      //list of items
      items: [],

      //player stats
      health: 25,
      attack: 12,
      defense: 8,
      gold: 100,

      //quest
      quests: []
    };

    this.player = new RPG.Player(this, 100, 100, playerData);

    //add player to the world
    this.add.existing(this.player);

    this.initGUI();
  },
  gameOver: function() {
    this.game.state.start('Game', true, false, this.currentLevel);
  },
  initGUI: function() {
    //onscreen controls setup
    this.game.onscreenControls.setup(this.player, {
      left: true,
      right: true,
      up: true,
      down: true,
      upleft: true,
      downleft: true,
      upright: true,
      downright: true,
      action: false
    })
  }

};
<file_sep>/Tutorial files/M11-Hipster-Town-Simulation/07-building-creation/js/states/Game.js
var HTown = HTown || {};

HTown.GameState = {

  init: function() {
    //game constants
    this.STEP =2;

    //no gravity in a top-down game
    this.game.physics.arcade.gravity.y = 0;

  },
  create: function() {

    //grass floor
    this.background = this.add.tileSprite(0,0, 1200, 800, 'grass');
    this.game.world.setBounds(0, 0, 1200, 800);

    this.buildings = this.add.group();

    var house = new HTown.Building(this, 100, 100, {asset: 'house', housing: 100});
    this.buildings.add(house);

    var farm = new HTown.Building(this, 200, 200, {asset: 'crops', food: 100});
    this.buildings.add(farm);

    var factory = new HTown.Building(this, 200, 300, {asset: 'factory', jobs: 20});
    this.buildings.add(factory);

    //create a town
    this.town = new HTown.TownModel({}, {population: 100, food: 200, money: 100}, this.buildings);

    //update simulation
    this.simulationTimer = this.game.time.events.loop(Phaser.Timer.SECOND * this.STEP, this.simulationStep, this);
  },
  update: function() {


  },
  simulationStep: function() {
    this.town.step();
  }
};
<file_sep>/Tutorial files/M9-RPG/12-battle/js/prefabs/Battle.js
var RPG = RPG || {};

RPG.Battle = function(game) {
  this.game = game;
};

RPG.Battle.prototype.attack = function(attacker, attacked) {
  var damage = Math.max(0, attacker.data.attack * Math.random() - attacked.data.defense * Math.random());

  console.log(damage);

  attacked.data.health -= damage;

  if(attacked.data.health <= 0) {
    attacked.kill();
  }
};<file_sep>/Tutorial files/M8-Veggies-vs-Zombies-updated-2015-07-03/14-button-bar/js/states/Game.js
var Veggies = Veggies || {};

Veggies.GameState = {

  init: function(currentLevel) {    
    //keep track of the current level
    this.currentLevel = currentLevel ? currentLevel : 'level1';

    //constants
    this.HOUSE_X = 60;
    this.SUN_FREQUENCY = 5;
    this.SUN_VELOCITY = 50;

    //no gravity in a top-down game
    this.game.physics.arcade.gravity.y = 0;    
  },
  create: function() {
    this.background = this.add.sprite(0, 0, 'background');

    //group for game objects
    this.bullets = this.add.group();
    this.plants = this.add.group();
    this.zombies = this.add.group();
    this.suns = this.add.group();

    //player stats
    this.numSums = 100;

    //create user interface
    this.createGui();

    var zombieData = {
      asset: 'zombie',
      health: 10,
      animationFrames: [0, 1, 2, 1],
      attack: 0.1,
      velocity: -10
    };

    this.zombie = new Veggies.Zombie(this, 400, 100, zombieData);
    this.zombies.add(this.zombie);


    var plantData = {
      plantAsset: 'plant',
      health: 10,
      isShooter: true,
      //isSunProducer: true,
      animationFrames: [1, 2, 1, 0]
    };

    this.plant = new Veggies.Plant(this, 100, 100, plantData);
    this.plants.add(this.plant);

    //create new suns with the specified frequency
    this.sunGenerationTimer = this.game.time.create(false);
    this.sunGenerationTimer.start();
    this.scheduleSunGeneration();

    //hitting sound
    this.hitSound = this.add.audio('hit');
  },   
  update: function() {    
    this.game.physics.arcade.collide(this.plants, this.zombies, this.attackPlant, null, this)
    this.game.physics.arcade.collide(this.bullets, this.zombies, this.hitZombie, null, this)
  
    this.zombies.forEachAlive(function(zombie){
      //zombies need to keep their speed
      zombie.body.velocity.x = zombie.defaultVelocity;

      //if one of them reaches the house, it's game over
      if(zombie.x <= this.HOUSE_X) {
        this.gameOver();
      }
    }, this);
  },  
  gameOver: function() {
    this.game.state.start('Game');
  },
  attackPlant: function(plant, zombie) {
    plant.damage(zombie.attack);
  },
  createZombie: function(x, y, data) {
    //look for a dead element
    var newElement = this.zombies.getFirstDead();

    //if there are no dead ones, create a new one
    if(!newElement) {
      newElement = new Veggies.Zombie(this, x, y, data);
      this.zombies.add(newElement);
    }
    else {
      newElement.reset(x, y, data);
    }

    return newElement;
  },
  createPlant: function(x, y, data) {
    //look for a dead element
    var newElement = this.plants.getFirstDead();

    //if there are no dead ones, create a new one
    if(!newElement) {
      newElement = new Veggies.Plant(this, x, y, data);
      this.plants.add(newElement);
    }
    else {
      newElement.reset(x, y, data);
    }

    return newElement;
  },
  createGui: function() {
    //show sun stats
    var sun = this.add.sprite(10, this.game.height - 20, 'sun');
    sun.anchor.setTo(0.5);
    sun.scale.setTo(0.5);
    var style = {font: '14px Arial', fill: '#fff'};
    this.sunLabel = this.add.text(22, this.game.height - 28, '', style);
    this.updateStats();

    //show the button bar
    this.buttonData = JSON.parse(this.game.cache.getText('buttonData'));

    //buttons
    this.buttons = this.add.group();

    var button;
    this.buttonData.forEach(function(element, index){
      button = new Phaser.Button(this.game, 80 + index * 40, this.game.height - 35, element.btnAsset, this.clickButton, this)
      this.buttons.add(button);

      //pass the data to the button
      button.plantData = element;
    }, this);
  },
  updateStats: function() {
    this.sunLabel.text = this.numSums;
  },
  increaseSun: function(amount) {
    this.numSums += amount;
    this.updateStats();
  },
  scheduleSunGeneration: function() {
    this.sunGenerationTimer.add(Phaser.Timer.SECOND * this.SUN_FREQUENCY, function(){
      this.generateRandomSun();
      this.scheduleSunGeneration();
    }, this);
  },
  generateRandomSun: function() {
    //position
    var y = -20;
    var x = 40 + 420 * Math.random();

    //sun object
    var sun = this.createSun(x, y);

    //falling velocity
    sun.body.velocity.y = this.SUN_VELOCITY;
  },
  createSun: function(x, y) {
    //look for a dead element
    var newElement = this.suns.getFirstDead();

    //if there are no dead ones, create a new one
    if(!newElement) {
      newElement = new Veggies.Sun(this, x, y);
      this.suns.add(newElement);
    }
    else {
      newElement.reset(x, y);
    }

    return newElement;
  },
  hitZombie: function(bullet, zombie) {
    bullet.kill();
    this.hitSound.play();
    zombie.damage(1);
  },
  clickButton: function(button) {
    console.log(button.plantData);
  }
};
<file_sep>/Tutorial files/M14-Hexagon-Strategy-Game/06-units/js/prefabs/Unit.js
var HexGame = HexGame || {};

HexGame.Unit = function(state, data) {
  var position = state.board.getXYFromRowCol(data.row, data.col);

  Phaser.Sprite.call(this, state.game, position.x, position.y, data.asset);

  this.game = state.game;
  this.state = state;
  this.board = state.board;
  this.row = data.row;
  this.col = data.col;
  this.data = data;

  this.anchor.setTo(0.5);
};

HexGame.Unit.prototype = Object.create(Phaser.Sprite.prototype);
HexGame.Unit.prototype.constructor = HexGame.Unit;
<file_sep>/M8/js/prefabs/Zombie.js
var Veggies = Veggies || {};

Veggies.Zombie = function(state, x, y, data) {
  Phaser.Sprite.call(this, state.game, x, y, data.asset);

  this.state = state;
  this.game = state.game;
  this.anchor.setTo(0.5);    

  //enable physics 
  this.game.physics.arcade.enable(this);
    
  this.reset(x, y, data);    
};

Veggies.Zombie.prototype = Object.create(Phaser.Sprite.prototype);
Veggies.Zombie.prototype.constructor = Veggies.Zombie;

Veggies.Zombie.prototype.reset = function(x, y, data){
    Phaser.Sprite.prototype.reset.call(this, x, y, data.health);
    
    //change the image of zombie
    this.loadTexture(data.asset);
    
    //create an animation if any was passed
    this.animationName = null;
    if(data.animationFrames){
        this.animationName = data.asset + 'Anim';
        this.animations.add(this.animationName, data.animationFrames, 4, true);
        this.play(this.animationName);
    }
    
    //save properties
    this.attack = data.attack;
    this.defaultVelocity = data.velocity;
    this.body.velocity.x = data.velocity;
};

Veggies.Zombie.prototype.damage = function(amount){
    Phaser.Sprite.prototype.damage.call(this, amount);
    
    //particle effect for blood
    var emitter = this.game.add.emitter(this.x, this.y, 50);
    emitter.makeParticles('bloodParticle');
    emitter.minParticleSpeed.setTo(-100, -100);
    emitter.maxParticleSpeed.setTo(100, 100);
    emitter.gravity = 300;
    emitter.start(true, 200, null, 100);
    
    //corpse
    if(this.health <= 0){
        var corpse = this.game.add.sprite(this.x, this.bottom, 'deadZombie');
        corpse.anchor.setTo(0.5, 1);
    }
};<file_sep>/Tutorial files/M13-Point-and-Click/04-custom-font/js/states/Game.js
var PointClk = PointClk || {};

PointClk.GameState = {

  init: function(playerData) {
    this.playerData = playerData ? playerData : {};
    this.playerData.room = this.playerData.room ? this.playerData.room : 'livingroom';
  },
  create: function() {
    //panel area
    this.panel = this.add.sprite(0, 270, 'panel');
    var style = {
      font: '16px Prstart',
      fill: '#fff',
      align: 'left',
      wordWrap: true,
      wordWrapWidth: 400
    };
    this.panelLabel = this.add.text(10, 290, '', style);

    this.loadRoom();
  },
  loadRoom: function() {
    this.roomData = JSON.parse(this.game.cache.getText(this.playerData.room));

    this.background = this.add.sprite(0, 0, this.roomData.background);

    //create things
    this.things = this.add.group();
    var thing;
    this.roomData.things.forEach(function(thingData){
      thing = new PointClk.Thing(this, thingData);
      this.things.add(thing);
    }, this);
  }

};
<file_sep>/Tutorial files/M14-Hexagon-Strategy-Game/03-terrains/js/prefabs/Board.js
var HexGame = HexGame || {};

HexGame.Board = function(state, grid) {
  Phaser.Group.call(this, state.game);

  this.state = state;
  this.game = state.game;
  this.grid = grid;
  this.rows = grid.length;
  this.cols = grid[0].length;

  this.terrains = [
    {asset: 'grass'},
    {asset: 'water', blocked: true},
    {asset: 'rocks'},
    {asset: 'grasstrees'},
    {asset: 'grasstrees2'}
  ];

  //create hexagons
  var row, col, tile, x, y;
  for(row = 0; row < this.rows; row++) {
    for(col = 0; col < this.cols; col++) {
      //even rows
      if(row % 2 === 0) {
        x = this.state.MARGIN_X + col * this.state.TILE_W;
      }
      //odd rows
      else {
        x = this.state.MARGIN_X + col * this.state.TILE_W + this.state.TILE_W/2;
      }

      y = this.state.MARGIN_Y + row * this.state.TILE_H * 3/4;

      tile = new Phaser.Sprite(this.game, x, y, this.terrains[this.grid[row][col]].asset);

      //keep some information in the tile object
      tile.row = row;
      tile.col = col;
      tile.terrainAsset = this.terrains[this.grid[row][col]].asset;
      tile.blocked = this.terrains[this.grid[row][col]].blocked;

      tile.inputEnabled = true;
      tile.input.pixelPerfectClick = true;

      this.add(tile);
    }
  }


};


HexGame.Board.prototype = Object.create(Phaser.Group.prototype);
HexGame.Board.prototype.constructor = HexGame.Board;
<file_sep>/Tutorial files/M11-Hipster-Town-Simulation/02-population-growth/js/prefabs/TownModel.js
var HTown = HTown || {};

HTown.TownModel = function(coefs, initialStats){

  this.coefs = {};
  this.coefs.populationGrowth = this.coefs.populationGrowth || 1.02;
  this.coefs.foodConsumption = this.coefs.foodConsumption || 1;

  this.stats = {};
  this.stats.population = initialStats.population;
  this.stats.food = initialStats.food;
  this.stats.money = initialStats.money;

};

HTown.TownModel.prototype.step = function(){
  //population
  this.stats.population = this.stats.population * this.coefs.populationGrowth;

};
<file_sep>/Tutorial files/M15-Dungeon-Crawler/10-generate-enemies/js/prefabs/Enemy.js
var DunCrawl = DunCrawl || {};

DunCrawl.Enemy = function(state, data) {

  var position = state.board.getXYFromRowCol(data);

  Phaser.Sprite.call(this, state.game, position.x, position.y, data.asset);

  this.game = state.game;
  this.state = state;
  this.board = state.board;
  this.row = data.row;
  this.col = data.col;
  this.data = data;
  this.data.type = 'enemy';

  this.anchor.setTo(0.5);


};

DunCrawl.Enemy.prototype = Object.create(Phaser.Sprite.prototype);
DunCrawl.Enemy.prototype.constructor = DunCrawl.Unit;

<file_sep>/Tutorial files/M15-Dungeon-Crawler/03-collect-items/js/states/Game.js
var DunCrawl = DunCrawl || {};

DunCrawl.GameState = {

  init: function(data) {
    //board
    this.ROWS = 8;
    this.COLS = 6;
    this.TILE_SIZE = 60;

    data = data || {};
    this.currentLevel = data.currentLevel || 1;

    this.playerStats = data.playerStats || {
      health: 25,
      attack: 2,
      defense: 1,
      gold: 0,
      hasKey: false
    };
  },
  create: function() {
    //tiles groups
    this.backgroundTiles = this.add.group();

    //map elements
    this.mapElements = this.add.group();

    //board
    this.board = new DunCrawl.Board(this, {
      rows: this.ROWS,
      cols: this.COLS,
      tileSize: this.TILE_SIZE
    });

    //hard code an item
    this.item = new DunCrawl.Item(this, {
      row: 3,
      col: 2,
      asset: 'sword',
      type: 'consumable',
      health: 10,
      attack: 0,
      defense: 1,
      gold: 100
    });

    this.mapElements.add(this.item);

  },
  gameOver: function() {
    this.game.state.start('Game');
  },
  nextLevel: function() {
    this.game.state.start('Game', true, false, {currentLevel: this.currentLevel + 1, playerStats: this.playerStats});
  }


};
<file_sep>/Tutorial files/M14-Hexagon-Strategy-Game/05-get-adjacent-cells/js/prefabs/Board.js
var HexGame = HexGame || {};

HexGame.Board = function(state, grid) {
  Phaser.Group.call(this, state.game);

  this.state = state;
  this.game = state.game;
  this.grid = grid;
  this.rows = grid.length;
  this.cols = grid[0].length;

  this.terrains = [
    {asset: 'grass'},
    {asset: 'water', blocked: true},
    {asset: 'rocks'},
    {asset: 'grasstrees'},
    {asset: 'grasstrees2'}
  ];

  //create hexagons
  var row, col, tile, x, y;
  for(row = 0; row < this.rows; row++) {
    for(col = 0; col < this.cols; col++) {
      //even rows
      if(row % 2 === 0) {
        x = this.state.MARGIN_X + col * this.state.TILE_W;
      }
      //odd rows
      else {
        x = this.state.MARGIN_X + col * this.state.TILE_W + this.state.TILE_W/2;
      }

      y = this.state.MARGIN_Y + row * this.state.TILE_H * 3/4;

      tile = new Phaser.Sprite(this.game, x, y, this.terrains[this.grid[row][col]].asset);

      //keep some information in the tile object
      tile.row = row;
      tile.col = col;
      tile.terrainAsset = this.terrains[this.grid[row][col]].asset;
      tile.blocked = this.terrains[this.grid[row][col]].blocked;

      tile.inputEnabled = true;
      tile.input.pixelPerfectClick = true;
      tile.events.onInputDown.add(function(tile){
        var adj = this.getAdjacent(tile, true);

        adj.forEach(function(t){
          t.alpha = 0.3;
        }, this);
      }, this);

      this.add(tile);
    }
  }


};


HexGame.Board.prototype = Object.create(Phaser.Group.prototype);
HexGame.Board.prototype.constructor = HexGame.Board;

HexGame.Board.prototype.getFromRowCol = function(row, col) {
  var foundTile;

  this.forEach(function(tile){
    if(tile.row === row && tile.col === col) {
      foundTile = tile;
    }
  }, this);

  return foundTile;
};

HexGame.Board.prototype.getXYFromRowCol = function(row, col){
  var pos = {};

  //even rows
  if(row % 2 === 0) {
    pos.x = this.state.MARGIN_X + col * this.state.TILE_W + this.state.TILE_W/2;
  }
  //odd rows
  else {
    pos.x = this.state.MARGIN_X + col * this.state.TILE_W + this.state.TILE_W/2 + this.state.TILE_W/2;
  }

  pos.y = this.state.MARGIN_Y + row * this.state.TILE_H * 3/4 + this.state.TILE_H/2;

  return pos;
};

HexGame.Board.prototype.getAdjacent = function(tile, rejectBlocked) {
  var adjacentTiles = [];
  var row = tile.row;
  var col = tile.col;

  var relativePositions = [];

  //relative positions of adjacent cells depend whether the row is odd or event
  //even rows
  if(row % 2 === 0) {
    relativePositions = [
      {r: -1, c: 0},
      {r: -1, c: -1},
      {r: 0, c: -1},
      {r: 0, c: 1},
      {r: 1, c: 0},
      {r: 1, c: -1}
    ]
  }

  //odd rows
  else {
    relativePositions = [


      {r: -1, c: 0},
      {r: -1, c: 1},
      {r: 0, c: -1},
      {r: 0, c: 1},
      {r: 1, c: 0},
      {r: 1, c: 1}
    ];
  }

  var adjTile;

  relativePositions.forEach(function(pos){
    //check that we are not on the edge of the map
    if((row + pos.r >= 0) && (row + pos.r < this.rows) && (col + pos.c >= 0) && (col + pos.c < this.cols)) {
      //get adjacent tile
      adjTile = this.getFromRowCol(row + pos.r, col + pos.c);

      if(!rejectBlocked || !adjTile.blocked) {
        adjacentTiles.push(adjTile);
      }
    }
  }, this);

  return adjacentTiles;
};
<file_sep>/Tutorial files/M8-Veggies-vs-Zombies-updated-2015-07-03/16-land patches/js/prefabs/Plant.js
var Veggies = Veggies || {};

Veggies.Plant = function(state, x, y, data) {
  Phaser.Sprite.call(this, state.game, x, y, data.plantAsset);
  
  this.state = state;
  this.game = state.game;
  this.bullets = state.bullets;
  this.suns = state.suns;

  this.anchor.setTo(0.5);

  //init physics body
  this.game.physics.arcade.enable(this);
  this.body.immovable = true;

  //create timers
  this.shootingTimer = this.game.time.create(false);
  this.producingTimer = this.game.time.create(false);

  this.reset(x, y, data);
};

Veggies.Plant.prototype = Object.create(Phaser.Sprite.prototype);
Veggies.Plant.prototype.constructor = Veggies.Plant;

Veggies.Plant.prototype.reset = function(x, y, data){
  Phaser.Sprite.prototype.reset.call(this, x, y, data.health);

  //change the image of the plant
  this.loadTexture(data.plantAsset);

  //create an animation if any was passed
  this.animationName = null;
  if(data.animationFrames) {
    this.animationName = data.plantAsset + 'Anim';
    this.animations.add(this.animationName, data.animationFrames, 6, false);    
  }

  //save properties
  this.isShooter = data.isShooter;
  this.isSunProducer = data.isSunProducer;

  //if plant is a shooter then setup shooting timer
  if(this.isShooter) {
    this.shootingTimer.start();
    this.scheduleShooting();
  }

  //if plant is a sun producer then setup production timer
  if(this.isSunProducer) {
    this.producingTimer.start();
    this.scheduleProduction();
  }
};

Veggies.Plant.prototype.kill = function() {
  Phaser.Sprite.prototype.kill.call(this);

  //stop timers
  this.shootingTimer.stop();
  this.producingTimer.stop();
};

Veggies.Plant.prototype.scheduleShooting = function() {
  this.shoot();

  //plants shoot once per second
  this.shootingTimer.add(Phaser.Timer.SECOND, this.scheduleShooting, this);
};

Veggies.Plant.prototype.shoot = function() {

  //play shooting animation
  if(this.animations.getAnimation(this.animationName)) {
    this.play(this.animationName);
  }

  //location y ofthe bullet
  var y = this.y - 10;

  //look for a dead element
  var newElement = this.bullets.getFirstDead();

  //if there are no dead ones, create a new one
  if(!newElement) {
    newElement = new Veggies.Bullet(this, this.x, y);
    this.bullets.add(newElement);
  }
  else {
    newElement.reset(this.x, y);
  }

  //set the velocity
  newElement.body.velocity.x = 100;
};

Veggies.Plant.prototype.scheduleProduction = function() {
  //create a random sun
  this.produceSun();

  //plants shoot once per second
  this.producingTimer.add(Phaser.Timer.SECOND * 5, this.scheduleProduction, this);
};

Veggies.Plant.prototype.produceSun = function() {
  //place the sun in a random location near the plant
  var diffX = -40 + Math.random() * 80;
  var diffY = -40 + Math.random() * 80;
  this.state.createSun(this.x + diffX, this.y + diffY);
};
<file_sep>/Tutorial files/M9-RPG/03-hello-world-phaser-plugin/js/plugins/OnscreenControls.js
Phaser.Plugin.OnscreenControls = function(game, parent) {
  Phaser.Plugin.call(this, game, parent);

  //add your own custom init logic
  this.game = game;
  console.log('plugin ready');
};

Phaser.Plugin.OnscreenControls.prototype = Object.create(Phaser.Plugin.prototype);
Phaser.Plugin.OnscreenControls.prototype.constructor = Phaser.Plugin.OnscreenControls;<file_sep>/Tutorial files/M8-Veggies-vs-Zombies-updated-2015-07-03/07 shooting plants/js/prefabs/Zombie.js
var Veggies = Veggies || {};

Veggies.Zombie = function(state, x, y, data) {
  Phaser.Sprite.call(this, state.game, x, y, data.asset);

  this.state = state;
  this.game = state.game;
  this.anchor.setTo(0.5);

  //enable physics
  this.game.physics.arcade.enable(this);

  this.reset(x, y, data);
};

Veggies.Zombie.prototype = Object.create(Phaser.Sprite.prototype);
Veggies.Zombie.prototype.constructor = Veggies.Zombie;

Veggies.Zombie.prototype.reset = function(x, y, data) {
  Phaser.Sprite.prototype.reset.call(this, x, y, data.health);

  //change the image of the plant
  this.loadTexture(data.asset);

  //create an animation if any was passed
  this.animationName = null;
  if(data.animationFrames) {
    this.animationName = data.asset + 'Anim';
    this.animations.add(this.animationName, data.animationFrames, 4, true);
    this.play(this.animationName);
  }

  //save properties
  this.attack = data.attack;
  this.defaultVelocity = data.velocity;
  this.body.velocity.x = data.velocity;

}<file_sep>/Tutorial files/M14-Hexagon-Strategy-Game/09-attack/js/states/Game.js
var HexGame = HexGame || {};

HexGame.GameState = {

  init: function() {

    this.TILE_W = 56;
    this.TILE_H = 64;
    this.MARGIN_X = 30;
    this.MARGIN_Y = 5;
  },
  create: function() {
    this.map = JSON.parse(this.game.cache.getText('map'));
    this.board = new HexGame.Board(this, this.map.grid);

    this.playerUnits = this.add.group();
    this.enemyUnits = this.add.group();

    this.initUnits();
  },
  initUnits: function() {
    //load player units
    this.playerUnitsData = JSON.parse(this.game.cache.getText('playerUnits'));

    var unit;
    this.playerUnitsData.forEach(function(unitData){
      unit = new HexGame.Unit(this, unitData);

      //unit belongs to the player
      unit.isPlayer = true;

      this.playerUnits.add(unit);
    }, this);

    //load player units
    this.enemyUnitsData = JSON.parse(this.game.cache.getText('enemyUnits'));

    this.enemyUnitsData.forEach(function(unitData){
      unit = new HexGame.Unit(this, unitData);
      this.enemyUnits.add(unit);
    }, this);
  },
  clearSelection: function() {
    this.board.setAll('alpha', 1);

    //remove attached events from tiles
    this.board.forEach(function(tile){
      tile.events.onInputDown.removeAll();
    }, this);
  }

};
<file_sep>/Tutorial files/M11-Hipster-Town-Simulation/08-hud/js/states/Game.js
var HTown = HTown || {};

HTown.GameState = {

  init: function() {
    //game constants
    this.STEP =2;

    //no gravity in a top-down game
    this.game.physics.arcade.gravity.y = 0;

  },
  create: function() {

    //grass floor
    this.background = this.add.tileSprite(0,0, 1200, 800, 'grass');
    this.game.world.setBounds(0, 0, 1200, 800);

    this.buildings = this.add.group();

    var house = new HTown.Building(this, 100, 100, {asset: 'house', housing: 100});
    this.buildings.add(house);

    var farm = new HTown.Building(this, 200, 200, {asset: 'crops', food: 100});
    this.buildings.add(farm);

    var factory = new HTown.Building(this, 200, 300, {asset: 'factory', jobs: 20});
    this.buildings.add(factory);

    //create a town
    this.town = new HTown.TownModel({}, {population: 100, food: 200, money: 100}, this.buildings);

    //update simulation
    this.simulationTimer = this.game.time.events.loop(Phaser.Timer.SECOND * this.STEP, this.simulationStep, this);

    this.initGui();
  },
  update: function() {


  },
  simulationStep: function() {
    this.town.step();
    this.refreshStats();
  },
  initGui: function() {
    //money
    this.moneyIcon = this.add.sprite(10, 10, 'money');
    this.moneyIcon.fixedToCamera = true;

    var style = {font: '14px Arial', fill: '#fff'};
    this.moneyLabel = this.add.text(45, 15, '0', style);
    this.moneyLabel.fixedToCamera = true;

    //food icon
    this.foodIcon = this.add.sprite(100, 10, 'food');
    this.foodIcon.fixedToCamera = true;

    style = {font: '14px Arial', fill: '#fff'};
    this.foodLabel = this.add.text(135, 15, '0', style);
    this.foodLabel.fixedToCamera = true;

    //population icon
    this.populationIcon = this.add.sprite(190, 10, 'population');
    this.populationIcon.fixedToCamera = true;

    style = {font: '14px Arial', fill: '#fff'};
    this.populationLabel = this.add.text(225, 15, '0', style);
    this.populationLabel.fixedToCamera = true;

    //jobs icon
    this.jobsIcon = this.add.sprite(280, 10, 'jobs');
    this.jobsIcon.fixedToCamera = true;

    style = {font: '14px Arial', fill: '#fff'};
    this.jobsLabel = this.add.text(315, 15, '0', style);
    this.jobsLabel.fixedToCamera = true;

    //refresh stats
    this.refreshStats();
  },
  refreshStats: function() {
    this.moneyLabel.text = Math.round(this.town.stats.money);
    this.foodLabel.text = Math.round(this.town.stats.food);
    this.populationLabel.text = Math.round(this.town.stats.population) + '/' + Math.round(this.town.stats.housing);
    this.jobsLabel.text = Math.round(this.town.stats.jobs);
  }
};
<file_sep>/Tutorial files/M13-Point-and-Click/08-unlock-door/js/prefabs/Thing.js
var PointClk = PointClk || {};

PointClk.Thing = function(state, data) {
  Phaser.Sprite.call(this, state.game, data.x, data.y, data.asset);

  this.game = state.game;
  this.state = state;
  this.anchor.setTo(0.5);
  this.data = data;

  //listen for input
  this.inputEnabled = true;
  this.input.pixelPerfectClick = true;
  this.events.onInputDown.add(this.touch, this);
};

PointClk.Thing.prototype = Object.create(Phaser.Sprite.prototype);
PointClk.Thing.prototype.constructor = PointClk.Thing;

PointClk.Thing.prototype.touch = function() {
  this.state.panelLabel.text = this.data.text;

  //if it's a collectable then collect it!
  if(this.data.type == 'collectable') {
    this.state.addItem(this.data);
    this.kill();
    return;
  }

  //if it's an open door, go to another room
  else if(this.data.type == 'door' && this.data.isOpen) {
    console.log('go to ' + this.data.destination);
    return;
  }

  //are we selecting anything?
  var selectedItem = this.state.selectedItem;

  if(selectedItem) {
    //are there interactions? are they with the selected item?
    if(this.data.interactions && this.data.interactions[this.state.selectedItem.data.id]) {

      //we do have an interaction between the "thing" and the selected item
      var interaction = this.data.interactions[this.state.selectedItem.data.id];

      //show text
      if(interaction.text) {
        this.state.panelLabel.text = interaction.text;
      }

      //change asset
      if(interaction.asset) {
        this.loadTexture(interaction.asset);
        this.data.asset = interaction.asset;
      }

      //open door
      if(interaction.action == 'open-door') {
        this.data.isOpen = true;
        selectedItem.kill();
        this.state.clearSelection();
      }
    }
  }

};<file_sep>/Tutorial files/M6-Mr-Hop/02-pool-of-floors/js/states/Game.js
var MrHop = MrHop || {};

MrHop.GameState = {

  init: function() {
    
    //pool of floors
    this.floorPool = this.add.group();
    
    //gravity
    this.game.physics.arcade.gravity.y = 1000;    
  },
  create: function() {

    //hard-code first platform
    var platform = new MrHop.Platform(this.game, this.floorPool, 3, 100, 200);
    this.add.existing(platform);
  },   
  update: function() {    

  } 
};
<file_sep>/Tutorial files/M8-Veggies-vs-Zombies-updated-2015-07-03/02 plant prefab/js/states/Game.js
var Veggies = Veggies || {};

Veggies.GameState = {

  init: function(currentLevel) {    
    //keep track of the current level
    this.currentLevel = currentLevel ? currentLevel : 'level1';

    //no gravity in a top-down game
    this.game.physics.arcade.gravity.y = 0;    
  },
  create: function() {
    this.background = this.add.sprite(0, 0, 'background');

    //group for game objects
    this.bullets = this.add.group();
    this.plants = this.add.group();
    this.zombies = this.add.group();
    this.suns = this.add.group();

    var plantData = {
      plantAsset: 'plant',
      health: 10
    };

    this.plant = new Veggies.Plant(this, 100, 100, plantData);
    this.plants.add(this.plant);
  },   
  update: function() {    
    
  },  
  gameOver: function() {
    this.game.state.start('Game');
  }  
};
<file_sep>/M11/js/prefabs/Building.js
var HTown = HTown || {};

HTown.Building = function(state, x, y, data) {
  Phaser.Sprite.call(this, state.game, x, y, data.asset);

  this.game = state.game;
  this.state = state;

  //init stats
  this.food = data.food;    
  this.jobs = data.jobs;
  this.housing = data.housing;


  this.anchor.setTo(0.5);

  //init physics
  this.game.physics.arcade.enable(this);
};

HTown.Building.prototype = Object.create(Phaser.Sprite.prototype);
HTown.Building.prototype.constructor = HTown.Building;<file_sep>/M3/js/main.js
//this game will have only 1 state
var GameState = {

  //initiate some game-level settings
  init: function() {
  	//scaling options
  	this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
  	this.scale.pageAlignHorizontally = true;
  	this.scale.pageAlignVertically = true;
  },
  //load the game assets before the game starts
  preload: function() {
    this.load.image('backyard', 'assets/images/backyard.png');    
    this.load.image('apple', 'assets/images/apple.png');    
    this.load.image('candy', 'assets/images/candy.png');    
    this.load.image('rotate', 'assets/images/rotate.png');    
    this.load.image('toy', 'assets/images/rubber_duck.png');    
    this.load.image('arrow', 'assets/images/arrow.png');   
    this.load.spritesheet('pet', 'assets/images/pet.png', 97, 83, 5, 1, 1); 
  },
  //executed after everything is loaded
  create: function() {      
  	this.background = this.game.add.sprite(0, 0, 'backyard');

  	this.pet = this.game.add.sprite(100, 400, 'pet');
  	this.pet.anchor.setTo(0.5);

  	//custom properties
  	this.pet.customParams = {health: 100, fun: 100};

  	this.apple = this.game.add.sprite(72, 570, 'apple');
  	this.candy = this.game.add.sprite(144, 570, 'candy');
  	this.toy = this.game.add.sprite(216, 570, 'toy');
  	this.rotate = this.game.add.sprite(288, 570, 'rotate');

  },

  
};

//initiate the Phaser framework
var game = new Phaser.Game(360, 640, Phaser.AUTO);

game.state.add('GameState', GameState);
game.state.add('HomeState', HomeState);
game.state.add('PreloadState', PreloadState);
game.state.add('BootState', BootState);
game.state.start('GameState');<file_sep>/M11/js/states/Game.js
var HTown = HTown || {};

HTown.GameState = {

  init: function() {
    //game constants
    this.STEP = 2;  
      
    //no gravity in a top-down game
    this.game.physics.arcade.gravity.y = 0;

  },
  create: function() {

    //grass floor
    this.background = this.add.tileSprite(0,0, 1200, 800, 'grass');
    this.game.world.setBounds(0, 0, 1200, 800);

    this.buildings = this.add.group();  
    
    var house = new HTown.Building(this, 100, 100, {asset: 'house', housing: 100});
    this.buildings.add(house); 
      
    var farm = new HTown.Building(this, 200, 200, {asset: 'crops', food: 2200});
    this.buildings.add(farm);
      
    var factory = new HTown.Building(this, 300, 300, {asset: 'factory', jobs: 20});
    this.buildings.add(factory);       
      
    //create town
    this.town = new HTown.TownModel({}, {population: 100, food: 200, money: 100}, this.buildings);
      
    //update simulation
    this.simulationTimer = this.game.time.events.loop(Phaser.Timer.SECOND * this.STEP, this.simulationStep, this);  
      
    this.initGui();
    this.refreshStats();  
  },
    
  update: function() {

    //check if dragging is not blocked
    if(!this.isDraggingMapBlock){
        //start dragging
        if(!this.isDraggingMap){
            if(this.game.input.activePointer.isDown){
                this.isDraggingMap = true;
                this.startDragPoint = {};
                this.startDragPoint.x = this.game.input.activePointer.position.x;
                this.startDragPoint.y = this.game.input.activePointer.position.y;
            }
        }else{
            this.endDragPoint = {};
            this.endDragPoint.x = this.game.input.activePointer.position.x;
            this.endDragPoint.y = this.game.input.activePointer.position.y;
            
            this.game.camera.x += this.startDragPoint.x - this.endDragPoint.x;
            this.game.camera.y += this.startDragPoint.y - this.endDragPoint.y;
            
            
            //after update take new starting point
            this.startDragPoint.x = this.game.input.activePointer.position.x;
            this.startDragPoint.y = this.game.input.activePointer.position.y;
            
            //stop dragging map when active pointer is released
            if(this.game.input.activePointer.isUp){
                this.isDraggingMap = false;
            }
        }
    }
      
    if(this.isBuildingBtnActive && this.game.input.activePointer.isDown){
        //we can no longer drag the map
        this.isDraggingMapBlock = true;
       
        //start dragging a shadow building
        this.isDraggingBuilding = true;
    }
      
    if(this.isDraggingBuilding){
        var pointerWX = this.game.input.activePointer.worldX;
        var pointerWY = this.game.input.activePointer.worldY;
        
        if(!this.shadowBuilding || !this.shadowBuilding.alive){
            this.shadowBuilding = this.add.sprite(pointerWX, pointerWY, this.selectedBuilding.asset);
            this.shadowBuilding.alpha = 0.5;
            this.shadowBuilding.anchor.setTo(0.5);
            
            //enable physics
            this.game.physics.arcade.enable(this.shadowBuilding);
        }
        this.shadowBuilding.x = pointerWX;  
        this.shadowBuilding.y = pointerWY;         
    } 
      
    if(this.isDraggingBuilding && this.game.input.activePointer.isUp){   
        
        if(this.canBuild()){
            this.town.stats.money -= this.selectedBuilding.cost;
            this.createBuilding(this.game.input.activePointer.worldX, this.game.input.activePointer.worldY, this.selectedBuilding);
        }
        this.clearSelection();
    }  

  },
    
  simulationStep: function(){
    this.town.step();
    this.refreshStats();  
  },
    
  initGui: function(){
    //money  
    this.moneyIcon = this.add.sprite(10, 10, 'money');
    this.moneyIcon.fixedToCamera = true;  
  
    var style = {font: '14 px Arial', fill: '#fff'};
    this.moneyLabel = this.add.text(45, 15, '0', style); 
    this.moneyLabel.fixedToCamera = true;
      
    //food  
    this.foodIcon = this.add.sprite(100, 10, 'food');
    this.foodIcon.fixedToCamera = true;  
  
    this.foodLabel = this.add.text(135, 15, '0', style);
    this.foodLabel.fixedToCamera = true; 
      
    //population  
    this.populationIcon = this.add.sprite(190, 10, 'population');
    this.populationIcon.fixedToCamera = true;  
  
    var style = {font: '14 px Arial', fill: '#fff'};
    this.populationLabel = this.add.text(225, 15, '0', style);
    this.populationLabel.fixedToCamera = true;
      
    //jobs  
    this.jobsIcon = this.add.sprite(280, 10, 'jobs');
    this.jobsIcon.fixedToCamera = true; 
          
    var style = {font: '14 px Arial', fill: '#fff'};
    this.jobsLabel = this.add.text(315, 15, '0', style);
    this.jobsLabel.fixedToCamera = true;
      
    //button data
    this.buttonData = JSON.parse(this.game.cache.getText('buttonData'));
      
    //buttons group
    this.buttons = this.add.group();
      
    var button;
    this.buttonData.forEach(function(element, index){
        button = new Phaser.Button(this.game, this.game.width - 60 - 60 * index, this.game.height - 60, element.btnAsset, this.clickBuildBtn, this);
        button.fixedToCamera = true;
        this.buttons.add(button);
        
        //pass data of the button
        button.buildingData = element;
    }, this);  
       
  },
    
  refreshStats: function(){
    this.moneyLabel.text = Math.round(this.town.stats.money);
    this.foodLabel.text = Math.round(this.town.stats.food);
    this.jobsLabel.text = Math.round(this.town.stats.jobs);
    this.populationLabel.text = Math.round(this.town.stats.population) + '/' + Math.round(this.town.stats.housing);
      
  },
    
  clickBuildBtn: function(button){
    this.clearSelection();
      
    //check if user can afford the building
    if(this.town.stats.money >= button.buildingData.cost){
        button.alpha = 0.5;
        this.selectedBuilding = button.buildingData;
        this.isBuildingBtnActive = true;
    }  
  },
    
  clearSelection: function(){
    this.isDraggingMapBlock = false;
    this.isDraggingMap = false; 
    this.isBuildingBtnActive = false;
    this.selectedBuilding = null;
    this.isDraggingBuilding = false;
      
    if(this.shadowBuilding){
        this.shadowBuilding.kill();
    }  
    
   // this.refreshStats();
      
    this.buttons.setAll('alpha', 1);  
  },
    
  createBuilding: function(x, y, data){
    var newBuilding = new HTown.Building(this, x, y, data);
    this.buildings.add(newBuilding);  
  },
    
  canBuild: function(){
    var isOverlappingBuildings = this.game.physics.arcade.overlap(this.shadowBuilding, this.buildings);
      
    return !isOverlappingBuildings;  
  }    
};
<file_sep>/Tutorial files/M8-Veggies-vs-Zombies-updated-2015-07-03/09 sun prefab and expiration/js/prefabs/Sun.js
var Veggies = Veggies || {};

Veggies.Sun = function(state, x, y) {
  Phaser.Sprite.call(this, state.game, x, y, 'sun');

  this.state = state;
  this.game = state.game;

  //init physics body
  this.game.physics.arcade.enable(this);

  this.animations.add('shine', [0,1,0], 10, true);
  this.play('shine');

  //some default values
  this.anchor.setTo(0.5);

  //collect suns when tapping
  this.inputEnabled = true;
  this.input.pixelPerfectClick = true;
  this.events.onInputDown.add(function(){
    console.log('sun collected');

    this.kill();
  }, this);

  //expiration of the sun
  this.sunExpirationTimer = this.game.time.create(false);
  
  this.reset(x, y);
};

Veggies.Sun.prototype = Object.create(Phaser.Sprite.prototype);
Veggies.Sun.prototype.constructor = Veggies.Sun;

Veggies.Sun.prototype.scheduleExpiration = function(){
  this.sunExpirationTimer.start();

  //random expiration time between 2 and 6 seconds
  var expirationTime = 2 + Math.random() * 4;

  this.sunExpirationTimer.add(Phaser.Timer.SECOND * expirationTime, function(){
    this.kill();
  }, this);
};

Veggies.Sun.prototype.kill = function() {
  this.sunExpirationTimer.stop();

  Phaser.Sprite.prototype.kill.call(this);
};

Veggies.Sun.prototype.reset = function(x, y) {
  Phaser.Sprite.prototype.reset.call(this, x, y);

  this.scheduleExpiration();
}
<file_sep>/Tutorial files/M14-Hexagon-Strategy-Game/12-enemy-ai/js/prefabs/Unit.js
var HexGame = HexGame || {};

HexGame.Unit = function(state, data) {
  var position = state.board.getXYFromRowCol(data.row, data.col);

  Phaser.Sprite.call(this, state.game, position.x, position.y, data.asset);

  this.game = state.game;
  this.state = state;
  this.board = state.board;
  this.row = data.row;
  this.col = data.col;
  this.data = data;

  this.anchor.setTo(0.5);

  //this.inputEnabled = true;
  //this.input.pixelPerfectClick = true;
  //this.events.onInputDown.add(this.showMovementOptions, this);
};

HexGame.Unit.prototype = Object.create(Phaser.Sprite.prototype);
HexGame.Unit.prototype.constructor = HexGame.Unit;

HexGame.Unit.prototype.showMovementOptions = function(){

  this.state.clearSelection();

  //only if the UI is free
  if(this.state.uiBlocked) {
    return;
  }

  //get current tile
  var currTile = this.board.getFromRowCol(this.row, this.col);

  //get the adjacent cells
  var adjacentCells = this.board.getAdjacent(currTile, true);

  adjacentCells.forEach(function(tile){
    tile.alpha = 0.7;

    //add input
    tile.events.onInputDown.add(this.moveUnit, this);
  }, this);
};

HexGame.Unit.prototype.moveUnit = function(tile){
  this.state.clearSelection();

  this.state.uiBlocked = true;

  //target position
  var pos = this.board.getXYFromRowCol(tile.row, tile.col);

  var unitMovement = this.game.add.tween(this);

  unitMovement.to(pos, 200);
  unitMovement.onComplete.add(function(){
    this.state.uiBlocked = false;
    this.row = tile.row;
    this.col = tile.col;

    //check for battles
    this.checkBattle();

    //check for game ending

    //prepare the next unit
    this.state.prepareNextUnit();

  }, this);
  unitMovement.start();
};

HexGame.Unit.prototype.attack = function(attacked) {
  var attacker = this;

  //both units attack each other
  var damageAttacked = Math.max(0, attacker.data.attack * Math.random() - attacked.data.defense * Math.random());
  var damageAttacker = Math.max(0, attacked.data.attack * Math.random() - attacker.data.defense * Math.random());

  attacked.data.health -= damageAttacked;
  attacker.data.health -= damageAttacker;

  if(attacked.data.health <= 0) {
    attacked.kill();
  }

  if(attacker.data.health <= 0) {
    attacker.kill();
  }
};

HexGame.Unit.prototype.checkBattle = function() {
  //get rival army
  var rivalUnits = this.isPlayer ? this.state.enemyUnits : this.state.playerUnits;
  var fightUnit;

  //check rival army units to find a match
  rivalUnits.forEachAlive(function(unit){
    if(this.row === unit.row && this.col === unit.col) {
      console.log('both are in the same cell! -- fight!!!');
      fightUnit = unit;
    }
  }, this);

  //fight until death
  if(fightUnit) {
    while(this.data.health >= 0 && fightUnit.data.health >= 0) {
      this.attack(fightUnit);
    }
    console.log('battle end');
  }
};

HexGame.Unit.prototype.playTurn = function() {
  if(this.isPlayer) {
    this.showMovementOptions();
  }
  else {
    this.aiEnemyMovement();
  }
};

HexGame.Unit.prototype.aiEnemyMovement = function() {
  //clear previous selection
  this.state.clearSelection();

  //get the current tile
  var currTile = this.board.getFromRowCol(this.row, this.col);

  //get the adjacent cells
  var adjacentCells = this.board.getAdjacent(currTile, true);

  //target tile
  var targetTile;

  //go through each adjacent cell and find a rival
  adjacentCells.forEach(function(tile){
    //find out if there is a rival in there
    this.state.playerUnits.forEachAlive(function(unit){
      if(tile.row === unit.row && tile.col === unit.col) {
        console.log('we have found a rival to attack');
        targetTile = tile;
      }
    }, this);
  }, this);

  //if you didnt find a rival, then move randomly
  if(!targetTile) {
    var randomIndex = Math.floor(Math.random() * adjacentCells.length);
    targetTile = adjacentCells[randomIndex];
  }

  //move to the target
  this.moveUnit(targetTile);
};