<commit_before>
BasicGame.Game = function (game) {

};

BasicGame.Game.prototype = {

  preload: function () {
    this.load.image('sea','assets/sea.png');
    this.load.image('bullet', 'assets/bullet.png');
    this.load.spritesheet('greenEnemy', 'assets/enemy.png', 32, 32);
    this.load.spritesheet('explosion', 'assets/explosion.png', 32, 32);
    this.load.spritesheet('player', 'assets/player.png', 64, 64);
  },

  create: function () {

    this.sea = this.add.tileSprite(0, 0, 800, 600, 'sea');

    this.player = this.add.sprite(400, 550, 'player');
    this.player.anchor.setTo(0.5, 0.5);
    this.player.animations.add('fly', [0, 1, 2], 20, true);
    this.player.play('fly');
    this.physics.enable(this.player, Phaser.Physics.ARCADE);
    this.player.speed = 300;
    this.player.body.collideWorldBounds = true;

    this.enemy = this.add.sprite(400, 200, 'greenEnemy');
    this.enemy.animations.add('fly', [0, 1, 2], 20, true);
    this.enemy.play('fly');
    this.enemy.anchor.setTo(0.5, 0.5);
    this.physics.enable(this.enemy, Phaser.Physics.ARCADE);
    this.bullets = [];
    this.nextShotAt = 0;
    this.shotDelay = 100;

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

    this.instructions = this.add.text( 400, 500, 'Use Arrow Keys to Move, Press Z to Fire\n' + 'Tapping/clicking does both', {font: '20px monospace', fill: '#fff', align: 'center'});
    this.instructions.anchor.setTo(0.5, 0.5);
    this.instExpire = this.time.now + 10000;
  },

  update: function () {
    //  Honestly, just about anything could go here. It's YOUR game after all. Eat your heart out!
    this.sea.tilePosition.y += 0.2;
    for (var i = 0; i < this.bullets.length; i++) {
      this.physics.arcade.overlap( this.bullets[i], this.enemy, this.enemyHit, null, this);
    }

    this.player.body.velocity.x = 0;
    this.player.body.velocity.y = 0;

    if (this.cursors.left.isDown) {
      this.player.body.velocity.x = -this.player.speed;
    } else if (this.cursors.right.isDown) {
      this.player.body.velocity.x = this.player.speed;
    }

    if (this.cursors.up.isDown) {
      this.player.body.velocity.y = -this.player.speed;
    } else if (this.cursors.down.isDown) {
      this.player.body.velocity.y = this.player.speed;
    }

    if (this.input.activePointer.isDown && this.physics.arcade.distanceToPointer(this.player) > 15) {
      this.physics.arcade.moveToPointer(this.player, this.player.speed);
    }

    if (this.input.keyboard.isDown(Phaser.Keyboard.Z) || this.input.activePointer.isDown) {
      this.fire();
    }

    if (this.instructions.exists && this.time.now > this.instExpire) {
      this.instructions.destroy();
    }
  },

  fire: function () {
    if (this.nextShotAt > this.time.now) {
      return;
    }
    this.nextShotAt = this.time.now + this.shotDelay;

    var bullet = this.add.sprite(this.player.x, this.player.y - 20, 'bullet');

    bullet.anchor.setTo(0.5, 0.5);
    this.physics.enable(bullet, Phaser.Physics.ARCADE);
    bullet.body.velocity.y = -500;
    this.bullets.push(bullet);
  },

  enemyHit: function (bullet, enemy) {
    bullet.kill();
    enemy.kill();
    var explosion = this.add.sprite(enemy.x, enemy.y, 'explosion');
    explosion.anchor.setTo(0.5, 0.5);
    explosion.animations.add('boom');
    explosion.play('boom', 15, false, true);
  },

  render: function() {
  },

  quitGame: function (pointer) {

    //  Here you should destroy anything you no longer need.
    //  Stop music, delete sprites, purge caches, free resources, all that good stuff.

    //  Then let's go back to the main menu.
    this.state.start('MainMenu');

  }

};
<commit_msg>added random enemy spawning<commit_after>
BasicGame.Game = function (game) {

};

BasicGame.Game.prototype = {

  preload: function () {
    this.load.image('sea','assets/sea.png');
    this.load.image('bullet', 'assets/bullet.png');
    this.load.spritesheet('greenEnemy', 'assets/enemy.png', 32, 32);
    this.load.spritesheet('explosion', 'assets/explosion.png', 32, 32);
    this.load.spritesheet('player', 'assets/player.png', 64, 64);
  },

  create: function () {

    this.sea = this.add.tileSprite(0, 0, 800, 600, 'sea');

    this.player = this.add.sprite(400, 550, 'player');
    this.player.anchor.setTo(0.5, 0.5);
    this.player.animations.add('fly', [0, 1, 2], 20, true);
    this.player.play('fly');
    this.physics.enable(this.player, Phaser.Physics.ARCADE);
    this.player.speed = 300;
    this.player.body.collideWorldBounds = true;

    this.enemy = this.add.sprite(400, 200, 'greenEnemy');
    this.enemy.animations.add('fly', [0, 1, 2], 20, true);
    this.enemy.play('fly');
    this.enemy.anchor.setTo(0.5, 0.5);
    this.physics.enable(this.enemy, Phaser.Physics.ARCADE);

    this.enemyPool = this.add.group();
    this.enemyPool.enableBody = true;
    this.enemyPool.physicsBodyType = Phaser.Physics.ARCADE;
    this.enemyPool.createMultiple(50, 'greenEnemy');
    this.enemyPool.setAll('anchor.x', 0.5);
    this.enemyPool.setAll('anchor.y', 0.5);
    this.enemyPool.setAll('outOfBoundsKill', true);
    this.enemyPool.setAll('checkWorldBounds', true);

    this.enemyPool.forEach(function (enemy){
      enemy.animations.add('fly', [0, 1, 2], 20, true);
    });

    this.nextEnemyAt = 0;
    this.enemyDelay = 1000;

    this.bulletPool = this.add.group();
    this.bulletPool.enableBody = true;
    this.bulletPool.physicsBodyType = Phaser.Physics.ARCADE;
    this.bulletPool.createMultiple(100, 'bullet');
    this.bulletPool.setAll('outOfBoundsKill', true);
    this.bulletPool.setAll('checkWorldBounds', true);

    this.nextShotAt = 0;

    this.nextShotAt = 0;
    this.shotDelay = 100;

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

    this.instructions = this.add.text( 400, 500, 'Use Arrow Keys to Move, Press Z to Fire\n' + 'Tapping/clicking does both', {font: '20px monospace', fill: '#fff', align: 'center'});
    this.instructions.anchor.setTo(0.5, 0.5);
    this.instExpire = this.time.now + 10000;
  },

  update: function () {
    //  Honestly, just about anything could go here. It's YOUR game after all. Eat your heart out!
    this.sea.tilePosition.y += 0.2;
    this.physics.arcade.overlap( this.bulletPool, this.enemyPool, this.enemyHit, null, this);

    if (this.nextEnemyAt < this.time.now && this.enemyPool.countDead() > 0) {
      this.nextEnemyAt = this.time.now + this.enemyDelay;
      var enemy = this.enemyPool.getFirstExists(false);

      enemy.reset(this.rnd.integerInRange(20, 780), 0);
      enemy.body.velocity.y = this.rnd.integerInRange(30, 60);
      enemy.play('fly');
    }

    this.player.body.velocity.x = 0;
    this.player.body.velocity.y = 0;

    if (this.cursors.left.isDown) {
      this.player.body.velocity.x = -this.player.speed;
    } else if (this.cursors.right.isDown) {
      this.player.body.velocity.x = this.player.speed;
    }

    if (this.cursors.up.isDown) {
      this.player.body.velocity.y = -this.player.speed;
    } else if (this.cursors.down.isDown) {
      this.player.body.velocity.y = this.player.speed;
    }

    if (this.input.activePointer.isDown && this.physics.arcade.distanceToPointer(this.player) > 15) {
      this.physics.arcade.moveToPointer(this.player, this.player.speed);
    }

    if (this.input.keyboard.isDown(Phaser.Keyboard.Z) || this.input.activePointer.isDown) {
      this.fire();
    }

    if (this.instructions.exists && this.time.now > this.instExpire) {
      this.instructions.destroy();
    }
  },

  fire: function () {
    if (this.nextShotAt > this.time.now) {
      return;
    }
    this.nextShotAt = this.time.now + this.shotDelay;

    var bullet = this.bulletPool.getFirstExists(false);
    bullet.reset(this.player.x, this.player.y - 20);
    bullet.body.velocity.y = -500;
  },

  enemyHit: function (bullet, enemy) {
    bullet.kill();
    enemy.kill();
    var explosion = this.add.sprite(enemy.x, enemy.y, 'explosion');
    explosion.anchor.setTo(0.5, 0.5);
    explosion.animations.add('boom');
    explosion.play('boom', 15, false, true);
  },

  render: function() {
  },

  quitGame: function (pointer) {

    //  Here you should destroy anything you no longer need.
    //  Stop music, delete sprites, purge caches, free resources, all that good stuff.

    //  Then let's go back to the main menu.
    this.state.start('MainMenu');

  }

};
<|endoftext|>


<commit_before>/**
 * Created by shaibenvalid on 1/20/17.
 */

var gameOptions = {
    gameWidth: 960,    // game width, in pixels
    gameHeight: 600,   // game height, in pixels
    tileSize: 60,     // tile size, in pixels
    colors: [0xff0000, 0x00ff00, 0x0000ff, 0xffff00] // tile colors
}

var gameLevelObj = new GameLevel();

var gameLevel = gameLevelObj.getData();

var agents = [];

window.onload = function () {

    //  Note that this html file is set to pull down Phaser 2.5.0 from the JS Delivr CDN.
    //  Although it will work fine with this tutorial, it's almost certainly not the most current version.
    //  Be sure to replace it with an updated version before you start experimenting with adding your own code.

    this.game = new Phaser.Game(960, 600, Phaser.AUTO, '', {preload: PreLoader.preload, create: create, update: update});

    function update() {
        updateBuldings();
        updateAgents();
    }

    function create() {
        this.game.physics.startSystem(Phaser.Physics.ARCADE);

        createBuildings(); //temp function
        drawBoard(gameLevel);
        gameLevelObj.completeData();
        bankFactory.init(this.game);
        createAgents();

    }

    function drawBoard(board) {
        for (var i = 0; i < board.length; i++) {
            var row = board[i];
            for (var j = 0; j < row.length; j++) {
                var tileType = row[j];
                var x = j * gameOptions.tileSize;
                var y = (i+1) * gameOptions.tileSize;
                if (tileType == 0) {
                    var assetName = 'block';
                }
                else {
                    tileType = tileType -1;
                    var assetName = gameLevelObj.getAssetNameById(tileType);
                    var tileObject = gameLevelObj.getObjectTypeByTileType(tileType+1);
                    var entity =null;
                    if (tileObject) { //TODO: fix this
                        switch (tileObject) {
                            case "Obsticle":
                                entity = new Obsticle(this.game, x, y, assetName, agents);
                                break;
                            case "House":
                                entity = new House(this.game, x, y, assetName, agents);
                                break;
                            case "Mosque":
                                entity = new Mosque(this.game, x, y, assetName);
                                break;
                        }
                    }
                    if (entity) {
                        entity.anchor.set(0,1);
                        this.game.add.existing(entity);
                    } else {
                        var sprite = this.game.add.sprite(x, y, assetName);
                        sprite.anchor.set(0,1);
                    }
                }
            }
        }
    }

    function createBuildings() {
        this.mosques = [];
        this.churches = [];
        this.synagogues = [];
        this.mosques.push(new Mosque(game, 100, 100, "mosque"));
    }

    /*
        TODO: will move to emitter
     */
    function createAgents(){
        var agent = new Agent(this.game, 300 + 30, 10, 0, 2, 1);
        this.game.add.existing(agent);
        agents.push(agent);
    }

    function updateBuldings() {
        var buildings = this.mosques.concat(this.churches).concat(this.synagogues);
        for (var i = 0; i < buildings.length; i++) {
            var building = buildings[i];
            building.doTick(new Date());
        }
    }

    function updateAgents(){
        for (var i = 0; i<agents.length; i++){
            agents[i].move();
        }

    }

};
<commit_msg>minor<commit_after>/**
 * Created by shaibenvalid on 1/20/17.
 */

var gameOptions = {
    gameWidth: 960,    // game width, in pixels
    gameHeight: 600,   // game height, in pixels
    tileSize: 60,     // tile size, in pixels
    colors: [0xff0000, 0x00ff00, 0x0000ff, 0xffff00] // tile colors
}

var gameLevelObj = new GameLevel();

var gameLevel = gameLevelObj.getData();

var agents = [];

window.onload = function () {

    //  Note that this html file is set to pull down Phaser 2.5.0 from the JS Delivr CDN.
    //  Although it will work fine with this tutorial, it's almost certainly not the most current version.
    //  Be sure to replace it with an updated version before you start experimenting with adding your own code.

    this.game = new Phaser.Game(960, 600, Phaser.AUTO, '', {preload: PreLoader.preload, create: create, update: update});

    function update() {
        updateBuldings();
        updateAgents();
    }

    function create() {
        this.game.physics.startSystem(Phaser.Physics.ARCADE);

        createBuildings(); //temp function
        drawBoard(gameLevel);
        gameLevelObj.completeData();
        bankFactory.init(this.game);
        createAgents();

    }

    function drawBoard(board) {
        for (var i = 0; i < board.length; i++) {
            var row = board[i];
            for (var j = 0; j < row.length; j++) {
                var tileType = row[j];
                var x = j * gameOptions.tileSize;
                var y = (i+1) * gameOptions.tileSize;
                if (tileType == 0) {
                    var assetName = 'block';
                }
                else {
                    tileType = tileType -1;
                    var assetName = gameLevelObj.getAssetNameById(tileType);
                    var tileObject = gameLevelObj.getObjectTypeByTileType(tileType+1);
                    var entity =null;
                    if (tileObject) { //TODO: fix this
                        switch (tileObject) {
                            case "Obsticle":
                                entity = new Obsticle(this.game, x, y, assetName);
                                break;
                            case "House":
                                entity = new House(this.game, x, y, assetName, agents);
                                break;
                            case "Mosque":
                                entity = new Mosque(this.game, x, y, assetName);
                                break;
                        }
                    }
                    if (entity) {
                        entity.anchor.set(0,1);
                        this.game.add.existing(entity);
                    } else {
                        var sprite = this.game.add.sprite(x, y, assetName);
                        sprite.anchor.set(0,1);
                    }
                }
            }
        }
    }

    function createBuildings() {
        this.mosques = [];
        this.churches = [];
        this.synagogues = [];
        this.mosques.push(new Mosque(game, 100, 100, "mosque"));
    }

    /*
        TODO: will move to emitter
     */
    function createAgents(){
        var agent = new Agent(this.game, 300 + 30, 10, 0, 2, 1);
        this.game.add.existing(agent);
        agents.push(agent);
    }

    function updateBuldings() {
        var buildings = this.mosques.concat(this.churches).concat(this.synagogues);
        for (var i = 0; i < buildings.length; i++) {
            var building = buildings[i];
            building.doTick(new Date());
        }
    }

    function updateAgents(){
        for (var i = 0; i<agents.length; i++){
            agents[i].move();
        }

    }

};
<|endoftext|>


<commit_before>// Canvas Size
var WIDTH = 1280;
var HEIGHT = 720;

// Initialize Renderer
var renderer = PIXI.autoDetectRenderer(WIDTH, HEIGHT, {antialiasing: false, transparent: false, resolution: 1});
renderer.backgroundColor = 0xABC8D2;
document.getElementById("game").appendChild(renderer.view);

// Master Containter
var stage = new PIXI.Container();

// Config goes here:
var fontConfig = {font: "30px 'rockfire'", fill: "#000000", align: "left"};
var relcenter = (0.5,0.5);

// Layers
var cBack = new PIXI.Container();
var cMiddle = new PIXI.Container();
var cFront = new PIXI.Container();
var cGui = new PIXI.Container();
/*
    stage
      |
      +-- cBack
      +-- cMiddle
      +-- cFront
      +-- cGui

Drawn from top to bottom
*/
stage.addChild(cBack);
stage.addChild(cMiddle);
stage.addChild(cFront);
stage.addChild(cGui);

// Version Text (top left)
var versionconfig = fontConfig;
var actionconfig = {font: "80px 'rockfire'", fill: "#000000", align:"center"};
var statsconfig = {font: "28px 'rockfire'", fill: "#000000", align:"right"};
var actionbgconfig = {font: "80px 'rockfire'", fill: "#FFFFFF", align:"center"};
var statsbgconfig = {font: "28px 'rockfire'", fill: "#FFFFFF", align:"right"};

var versionText = new PIXI.Text("Version 0.02d", versionconfig);
var actionText = new PIXI.Text("Fill all container ships\nSo that they carry 9 containers", actionconfig);
var statsText = new PIXI.Text("Mistake[s]\nPoint[s]\n#   Ship", statsconfig);
var animstatText = new PIXI.Text("n\nm\nN", statsconfig);
var actionbgText = new PIXI.Text("Fill all container ships\nSo that they carry 9 containers", actionbgconfig);
var statsbgText = new PIXI.Text("Mistake[s]\nPoint[s]\n#   Ship", statsbgconfig);
var animstatbgText = new PIXI.Text("n\nm\nN", statsbgconfig);

versionText.position = {x:10,y:10};
actionText.position = {x:WIDTH/2,y:HEIGHT/2};
actionText.anchor = {x:0.5,y:2.25};
statsText.position = {x:WIDTH-10, y:HEIGHT-5};
statsText.anchor = {x:1,y:1}
animstatText.position = {x:WIDTH-130, y:HEIGHT-5};
animstatText.anchor = {x:1,y:1}
actionbgText.position = {x:WIDTH/2+2,y:HEIGHT/2+2};
actionbgText.anchor = {x:0.5,y:2.25};
statsbgText.position = {x:WIDTH-10+2, y:HEIGHT-5+2};
statsbgText.anchor = {x:1,y:1}
animstatbgText.position = {x:WIDTH-130+2, y:HEIGHT-5+2};
animstatbgText.anchor = {x:1,y:1}

// Adding info text
cGui.addChild(actionbgText);
cGui.addChild(statsbgText);
cGui.addChild(animstatbgText);
cGui.addChild(versionText);
cGui.addChild(actionText);
cGui.addChild(statsText);
cGui.addChild(animstatText);

// Keyboard IO
// TODO on screen keys (interactive=true)
var loadKey = keyboard(65);
loadKey.press=function(){
    ingameLoad();
};
var unloadKey = keyboard(68);
unloadKey.press=function(){
    ingameUnload();
};
// Don't worry about this one
var fuckKey = keyboard(70);
fuckKey.press=function(){
    versionText.text="FUCK YOU!";
}

// init Gamestate
var gameState = new State();

// Image Locations
var loadbtn_file = "assets/image/buttons/load_btn.png";
var unloadbtn_file = "assets/image/buttons/unload_btn.png";
var seabg_file = "assets/image/bg/sea_layer.png";
var shitsprite_file = "assets/image/sprites/boat_layer.png";
var crane_base_file = "assets/image/sprites/cran_layer.png";
var crane_arm_file = "assets/image/sprites/cranarm_layer.png";
var port_file = "assets/image/sprites/port_layer.png";
var sky_file = "assets/image/bg/sky_layer.png";

// Load Images
// eg. assets/images/buttons/[load_btn.png, unload_btn.png]
PIXI.loader
    .add(loadbtn_file)
    .add(unloadbtn_file)
    .add(seabg_file)
    .add(shitsprite_file)
    .add(crane_base_file)
    .add(crane_arm_file)
    .add(port_file)
    .load(setup)

// Global sprites
var loadbtn = null;
var unloadbtn = null;
var background = null;

function showIngame(){
    loadbtn.position = {x: 10,y: HEIGHT-100};
    loadbtn.height = 93;
    loadbtn.width = 190;
    unloadbtn.position = {x: loadbtn.width + 15, y: HEIGHT-100};
    unloadbtn.height = 93;
    unloadbtn.width = 190;
    cGui.addChild(loadbtn);
    cGui.addChild(unloadbtn);
    loadbtn.interactive = true;
    unloadbtn.interactive = true;
    loadbtn.click = function(data){ingameLoad();};
    unloadbtn.click = function(data){ingameUnload();};
}

// TODO: Do Howler Stuff here
// TODO: "rate" changes speed

// Called just before rendering the first frame
function setup(){
    loadbtn = new PIXI.Sprite.fromImage(loadbtn_file);
    unloadbtn = new PIXI.Sprite.fromImage(unloadbtn_file);
    background = new PIXI.Sprite.fromImage(seabg_file);
    background.height = HEIGHT;
    background.width = WIDTH;
    clouds = new Cloud();
    cBack.addChild(background);
    port = new PIXI.Sprite.fromImage(port_file);
    port.height=91;
    port.width=WIDTH;
    port.position = {x:0,y:HEIGHT-port.height};
    cFront.addChild(port);

    cranearm = new PIXI.Sprite.fromImage(crane_arm_file);
    cranearm.height=HEIGHT;
    cranearm.width=WIDTH;
    cranearm.anchor={x:0.1958,y:0.39125};
    cranearm.position={x:250.624,y:281.7};
    cFront.addChild(cranearm);

    cranebase = new PIXI.Sprite.fromImage(crane_base_file);
    cranebase.height=HEIGHT;
    cranebase.width=WIDTH;
    cFront.addChild(cranebase);

    showIngame();
    testship = new Ship();

    // Filters
    // thisfil = new PIXI.filters.ColorMatrixFilter();
    // stage.filters = [thisfil];

    // FIXME: this is just debug, switch sin to tan for fun
    counter = 0.0;
    interv2 = window.setInterval(function(){cranearm.scale.x=1+0.55*Math.sin(counter);counter +=0.01 },10)

    renderStage();
}

function Cloud(){
    c = this;
    this.sprite1 = new PIXI.Sprite.fromImage(sky_file);
    this.sprite2 = new PIXI.Sprite.fromImage(sky_file);
    this.sprite1.scale = {x:1.5,y:1.5};
    this.sprite2.scale = {x:1.5,y:1.5};
    this.move= function(){
        if(this.sprite1.position.x<-1*this.sprite1.width){
            this.sprite1.position.x=this.sprite1.width;
        }
        if (this.sprite2.position.x<-1*this.sprite2.width) {
            this.sprite2.position.x=this.sprite2.width;
        }
        this.sprite1.position.x -= 1;
        this.sprite2.position.x -= 1;
    };
    cBack.addChild(this.sprite1);
    cBack.addChild(this.sprite2);
    this.sprite2.position.x=this.sprite1.width*1280;
    this.interv = window.setInterval(function(){c.move();},100);
}

// Class for Gamestate
function State(){
    this.level = 1;
    this.name = "Testie";
    this.mistakes = 0;
    this.points = 0;
    this.display = function(){
        // mistake, point, ship;
        animstatText.text=this.mistakes+"\n"+this.points+"\n"+this.level;
        animstatbgText.text=this.mistakes+"\n"+this.points+"\n"+this.level;
    }
    window.setInterval(function(){gameState.display();},100);
}

// Class for Ships
function Ship(){
    ship = this;
    this.end = 9;
    this.filter = new PIXI.filters.ColorMatrixFilter();
    this.filter.hue(rinr(0,360));
    this.sprite = new PIXI.Sprite.fromImage(shitsprite_file);
    this.sprite.scale={x:1.6,y:1.6};
    this.sprite.position={x:WIDTH+5,y:HEIGHT-350};
    this.sprite.filters = [this.filter];
    cMiddle.addChild(this.sprite);
    this.leftlevel = parseInt(rinr(2,6));
    this.middlelevel = parseInt(rinr(2,6));
    this.rightlevel = parseInt(rinr(2,6));
    this.die = function(){
        window.clearInterval(this.movement);
        cMiddle.removeChild(this.sprite);
        testship = new Ship();
        var sum = this.leftlevel + this.middlelevel + this.rightlevel;
        gameState.mistakes += abs(this.end-sum);
        gameState.points += abs(this.start-sum);
    };
    // FIXME: If this part generates properly, it'll work fine!
    this.start = this.leftlevel + this.middlelevel + this.rightlevel;
    this.bobx = 0;
    this.boby = 0;
    this.move = function(){
        this.sprite.x -= gameState.points/4+3;
        // TODO: Bobbing...
        // this.bobx += rinr(-100,100)/100000.0;
        // this.boby += rinr(-100,100)/100000.0;
        // this.sprite.anchor = {x:this.bobx, y:this.boby};
        if (this.sprite.x+this.sprite.width<-4) {
            gameState.level += 1;
            this.die();
        }
    }
    this.sumv = function(){return this.leftlevel + this.middlelevel + this.rightlevel;};
    this.lose=function(){
        if(this.sumv()<=1){
            gameState.mistakes += 1;
            return false;
        } else {
            if(this.leftlevel>0){
                this.leftlevel -= 1;
            } else if (this.middlelevel>0){
                this.middlelevel -= 1;
            } else if (this.rightlevel>0){
                this.rightlevel -= 1;
            } else {
                return false;
            }
            return true;
        }
    }
    this.movement = window.setInterval(function(){ship.move();},20);
}

// Request Animation Frame
function renderStage(){
    requestAnimationFrame(renderStage);
    renderLoop();
    renderer.render(stage);
}

// Called on "Load"-Press
function ingameLoad(){
    loadbtn.rotation=-0.03;window.setTimeout(function(){loadbtn.rotation=0.03;window.setTimeout(function(){loadbtn.rotation=0},200)},200)
    // Debug
    //gameState.points += 1;
    // TODO: Hitbox then change container
}

// Called on "Unload"-Press
function ingameUnload(){
    unloadbtn.rotation=-0.03;window.setTimeout(function(){unloadbtn.rotation=0.03;window.setTimeout(function(){unloadbtn.rotation=0},200)},200)
    // Debug
    //gameState.mistakes += 1;
    if (testship.sprite.x < 600 && testship.sprite.x > -1500) {
        testship.lose();
    }
}

// Called in-between rendering
// should be used for logic
function renderLoop(){

}
<commit_msg>Added comment about crane<commit_after>// Canvas Size
var WIDTH = 1280;
var HEIGHT = 720;

// Initialize Renderer
var renderer = PIXI.autoDetectRenderer(WIDTH, HEIGHT, {antialiasing: false, transparent: false, resolution: 1});
renderer.backgroundColor = 0xABC8D2;
document.getElementById("game").appendChild(renderer.view);

// Master Containter
var stage = new PIXI.Container();

// Config goes here:
var fontConfig = {font: "30px 'rockfire'", fill: "#000000", align: "left"};
var relcenter = (0.5,0.5);

// Layers
var cBack = new PIXI.Container();
var cMiddle = new PIXI.Container();
var cFront = new PIXI.Container();
var cGui = new PIXI.Container();
/*
    stage
      |
      +-- cBack
      +-- cMiddle
      +-- cFront
      +-- cGui

Drawn from top to bottom
*/
stage.addChild(cBack);
stage.addChild(cMiddle);
stage.addChild(cFront);
stage.addChild(cGui);

// Version Text (top left)
var versionconfig = fontConfig;
var actionconfig = {font: "80px 'rockfire'", fill: "#000000", align:"center"};
var statsconfig = {font: "28px 'rockfire'", fill: "#000000", align:"right"};
var actionbgconfig = {font: "80px 'rockfire'", fill: "#FFFFFF", align:"center"};
var statsbgconfig = {font: "28px 'rockfire'", fill: "#FFFFFF", align:"right"};

var versionText = new PIXI.Text("Version 0.02d", versionconfig);
var actionText = new PIXI.Text("Fill all container ships\nSo that they carry 9 containers", actionconfig);
var statsText = new PIXI.Text("Mistake[s]\nPoint[s]\n#   Ship", statsconfig);
var animstatText = new PIXI.Text("n\nm\nN", statsconfig);
var actionbgText = new PIXI.Text("Fill all container ships\nSo that they carry 9 containers", actionbgconfig);
var statsbgText = new PIXI.Text("Mistake[s]\nPoint[s]\n#   Ship", statsbgconfig);
var animstatbgText = new PIXI.Text("n\nm\nN", statsbgconfig);

versionText.position = {x:10,y:10};
actionText.position = {x:WIDTH/2,y:HEIGHT/2};
actionText.anchor = {x:0.5,y:2.25};
statsText.position = {x:WIDTH-10, y:HEIGHT-5};
statsText.anchor = {x:1,y:1}
animstatText.position = {x:WIDTH-130, y:HEIGHT-5};
animstatText.anchor = {x:1,y:1}
actionbgText.position = {x:WIDTH/2+2,y:HEIGHT/2+2};
actionbgText.anchor = {x:0.5,y:2.25};
statsbgText.position = {x:WIDTH-10+2, y:HEIGHT-5+2};
statsbgText.anchor = {x:1,y:1}
animstatbgText.position = {x:WIDTH-130+2, y:HEIGHT-5+2};
animstatbgText.anchor = {x:1,y:1}

// Adding info text
cGui.addChild(actionbgText);
cGui.addChild(statsbgText);
cGui.addChild(animstatbgText);
cGui.addChild(versionText);
cGui.addChild(actionText);
cGui.addChild(statsText);
cGui.addChild(animstatText);

// Keyboard IO
// TODO on screen keys (interactive=true)
var loadKey = keyboard(65);
loadKey.press=function(){
    ingameLoad();
};
var unloadKey = keyboard(68);
unloadKey.press=function(){
    ingameUnload();
};
// Don't worry about this one
var fuckKey = keyboard(70);
fuckKey.press=function(){
    versionText.text="FUCK YOU!";
}

// init Gamestate
var gameState = new State();

// Image Locations
var loadbtn_file = "assets/image/buttons/load_btn.png";
var unloadbtn_file = "assets/image/buttons/unload_btn.png";
var seabg_file = "assets/image/bg/sea_layer.png";
var shitsprite_file = "assets/image/sprites/boat_layer.png";
var crane_base_file = "assets/image/sprites/cran_layer.png";
var crane_arm_file = "assets/image/sprites/cranarm_layer.png";
var port_file = "assets/image/sprites/port_layer.png";
var sky_file = "assets/image/bg/sky_layer.png";

// Load Images
// eg. assets/images/buttons/[load_btn.png, unload_btn.png]
PIXI.loader
    .add(loadbtn_file)
    .add(unloadbtn_file)
    .add(seabg_file)
    .add(shitsprite_file)
    .add(crane_base_file)
    .add(crane_arm_file)
    .add(port_file)
    .load(setup)

// Global sprites
var loadbtn = null;
var unloadbtn = null;
var background = null;

function showIngame(){
    loadbtn.position = {x: 10,y: HEIGHT-100};
    loadbtn.height = 93;
    loadbtn.width = 190;
    unloadbtn.position = {x: loadbtn.width + 15, y: HEIGHT-100};
    unloadbtn.height = 93;
    unloadbtn.width = 190;
    cGui.addChild(loadbtn);
    cGui.addChild(unloadbtn);
    loadbtn.interactive = true;
    unloadbtn.interactive = true;
    loadbtn.click = function(data){ingameLoad();};
    unloadbtn.click = function(data){ingameUnload();};
}

// TODO: Do Howler Stuff here
// TODO: "rate" changes speed

// Called just before rendering the first frame
function setup(){
    loadbtn = new PIXI.Sprite.fromImage(loadbtn_file);
    unloadbtn = new PIXI.Sprite.fromImage(unloadbtn_file);
    background = new PIXI.Sprite.fromImage(seabg_file);
    background.height = HEIGHT;
    background.width = WIDTH;
    clouds = new Cloud();
    cBack.addChild(background);
    port = new PIXI.Sprite.fromImage(port_file);
    port.height=91;
    port.width=WIDTH;
    port.position = {x:0,y:HEIGHT-port.height};
    cFront.addChild(port);

    cranearm = new PIXI.Sprite.fromImage(crane_arm_file);
    cranearm.height=HEIGHT;
    cranearm.width=WIDTH;
    cranearm.anchor={x:0.1958,y:0.39125};
    cranearm.position={x:250.624,y:281.7};
    cFront.addChild(cranearm);

    cranebase = new PIXI.Sprite.fromImage(crane_base_file);
    cranebase.height=HEIGHT;
    cranebase.width=WIDTH;
    cFront.addChild(cranebase);

    showIngame();
    testship = new Ship();

    // Filters
    // thisfil = new PIXI.filters.ColorMatrixFilter();
    // stage.filters = [thisfil];

    // FIXME: this is just debug, switch sin to tan for fun
    // If you switch cos for sin, it goes the other way around
    counter = 0.0;
    interv2 = window.setInterval(function(){cranearm.scale.x=1+0.55*Math.sin(counter);counter +=0.01 },10)

    renderStage();
}

function Cloud(){
    c = this;
    this.sprite1 = new PIXI.Sprite.fromImage(sky_file);
    this.sprite2 = new PIXI.Sprite.fromImage(sky_file);
    this.sprite1.scale = {x:1.5,y:1.5};
    this.sprite2.scale = {x:1.5,y:1.5};
    this.move= function(){
        if(this.sprite1.position.x<-1*this.sprite1.width){
            this.sprite1.position.x=this.sprite1.width;
        }
        if (this.sprite2.position.x<-1*this.sprite2.width) {
            this.sprite2.position.x=this.sprite2.width;
        }
        this.sprite1.position.x -= 1;
        this.sprite2.position.x -= 1;
    };
    cBack.addChild(this.sprite1);
    cBack.addChild(this.sprite2);
    this.sprite2.position.x=this.sprite1.width*1280;
    this.interv = window.setInterval(function(){c.move();},100);
}

// Class for Gamestate
function State(){
    this.level = 1;
    this.name = "Testie";
    this.mistakes = 0;
    this.points = 0;
    this.display = function(){
        // mistake, point, ship;
        animstatText.text=this.mistakes+"\n"+this.points+"\n"+this.level;
        animstatbgText.text=this.mistakes+"\n"+this.points+"\n"+this.level;
    }
    window.setInterval(function(){gameState.display();},100);
}

// Class for Ships
function Ship(){
    ship = this;
    this.end = 9;
    this.filter = new PIXI.filters.ColorMatrixFilter();
    this.filter.hue(rinr(0,360));
    this.sprite = new PIXI.Sprite.fromImage(shitsprite_file);
    this.sprite.scale={x:1.6,y:1.6};
    this.sprite.position={x:WIDTH+5,y:HEIGHT-350};
    this.sprite.filters = [this.filter];
    cMiddle.addChild(this.sprite);
    this.leftlevel = parseInt(rinr(2,6));
    this.middlelevel = parseInt(rinr(2,6));
    this.rightlevel = parseInt(rinr(2,6));
    this.die = function(){
        window.clearInterval(this.movement);
        cMiddle.removeChild(this.sprite);
        testship = new Ship();
        var sum = this.leftlevel + this.middlelevel + this.rightlevel;
        gameState.mistakes += abs(this.end-sum);
        gameState.points += abs(this.start-sum);
    };
    // FIXME: If this part generates properly, it'll work fine!
    this.start = this.leftlevel + this.middlelevel + this.rightlevel;
    this.bobx = 0;
    this.boby = 0;
    this.move = function(){
        this.sprite.x -= gameState.points/4+3;
        // TODO: Bobbing...
        // this.bobx += rinr(-100,100)/100000.0;
        // this.boby += rinr(-100,100)/100000.0;
        // this.sprite.anchor = {x:this.bobx, y:this.boby};
        if (this.sprite.x+this.sprite.width<-4) {
            gameState.level += 1;
            this.die();
        }
    }
    this.sumv = function(){return this.leftlevel + this.middlelevel + this.rightlevel;};
    this.lose=function(){
        if(this.sumv()<=1){
            gameState.mistakes += 1;
            return false;
        } else {
            if(this.leftlevel>0){
                this.leftlevel -= 1;
            } else if (this.middlelevel>0){
                this.middlelevel -= 1;
            } else if (this.rightlevel>0){
                this.rightlevel -= 1;
            } else {
                return false;
            }
            return true;
        }
    }
    this.movement = window.setInterval(function(){ship.move();},20);
}

// Request Animation Frame
function renderStage(){
    requestAnimationFrame(renderStage);
    renderLoop();
    renderer.render(stage);
}

// Called on "Load"-Press
function ingameLoad(){
    loadbtn.rotation=-0.03;window.setTimeout(function(){loadbtn.rotation=0.03;window.setTimeout(function(){loadbtn.rotation=0},200)},200)
    // Debug
    //gameState.points += 1;
    // TODO: Hitbox then change container
}

// Called on "Unload"-Press
function ingameUnload(){
    unloadbtn.rotation=-0.03;window.setTimeout(function(){unloadbtn.rotation=0.03;window.setTimeout(function(){unloadbtn.rotation=0},200)},200)
    // Debug
    //gameState.mistakes += 1;
    if (testship.sprite.x < 600 && testship.sprite.x > -1500) {
        testship.lose();
    }
}

// Called in-between rendering
// should be used for logic
function renderLoop(){

}
<|endoftext|>


<commit_before>//Created a welcome message for the user//

var welcome=prompt("Welcome to my page! Please answer a few questions that will help you get to know me...Click OK to continue...")

//These are the questions about me to the user//

var answer1=prompt("Is my name Amina?");

	if (answer1=="yes")	{

		alert("Yes! My name is Amina")}

//no else statement is included so the alert will pop-up even if the answer is incorrect

var answer2=prompt("Do I have 5 children?");

	if(answer2=="yes") {

		alert("Yes! I have 5 children!")}

var answer3=prompt("Do I play the Trombone?");

	if(answer3=="yes")	{

			alert("Yes! I play the Trombone!")}

//Numerical variable question

//var number=prompt("What is my favorite number?")

	//if(number= 17)	{

		//	alert("Yes!")
	//}

	//else if(number<=17)	{

	//		alert("Too low!")
//	}

// need to add more if/else statements
//End of questions.<commit_msg>adjusted answers for prompts<commit_after>//Created a welcome message for the user//

var welcome=prompt("Welcome to my page! Please answer a few questions that will help you get to know me...Click OK to continue...")

//These are the questions about me to the user//

var answer1=prompt("Is my name Amina?");

	if (answer1=="yes"||"Yes"||"y"||"Y")	{

		alert("Yes! My name is Amina")}

//no else statement is included so the alert will pop-up even if the answer is incorrect

var answer2=prompt("Do I have 5 children?");

	if(answer2=="yes"||"Yes"||"y"||"Y") {

		alert("Yes! I have 5 children!")}

var answer3=prompt("Do I play the Trombone?");

	if(answer3=="yes"||"Yes"||"y"||"Y")	{

			alert("Yes! I play the Trombone!")}

//Numerical variable question

var number=prompt("What is my favorite number?")

	if(number==17)	{

			alert("Yes!")
	}

	else if(number<17)	{

		alert("Too low!")
	}

	else if(number>17) {

		alert("Too high!")
	}

// need to add more if/else statements
//End of questions.<|endoftext|>


<commit_before>// @flow

import * as React from 'react'
import * as glamorous from 'glamorous-native'
import * as c from '../components/colors'
import sample from 'lodash/sample'

const messages = [
	'☃ An Unofficial App Project ☃',
	'For students, by students',
	'By students, for students',
	'An unofficial St. Olaf app',
	'For Oles, by Oles',
	'☃',
	'🦁',
]

export function UnofficialAppNotice() {
	return (
		<glamorous.View justifyContent="center" marginBottom={10} marginHorizontal={10}>
			<glamorous.View backgroundColor="rgba(0,0,0,0.05)" borderRadius={7}>
				<glamorous.Text color={c.black25Percent} padding={8} textAlign="center">
					{sample(messages)}
				</glamorous.Text>
			</glamorous.View>
		</glamorous.View>
	)
}
<commit_msg>prettier changes<commit_after>// @flow

import * as React from 'react'
import * as glamorous from 'glamorous-native'
import * as c from '../components/colors'
import sample from 'lodash/sample'

const messages = [
	'☃ An Unofficial App Project ☃',
	'For students, by students',
	'By students, for students',
	'An unofficial St. Olaf app',
	'For Oles, by Oles',
	'☃',
	'🦁',
]

export function UnofficialAppNotice() {
	return (
		<glamorous.View
			justifyContent="center"
			marginBottom={10}
			marginHorizontal={10}
		>
			<glamorous.View backgroundColor="rgba(0,0,0,0.05)" borderRadius={7}>
				<glamorous.Text color={c.black25Percent} padding={8} textAlign="center">
					{sample(messages)}
				</glamorous.Text>
			</glamorous.View>
		</glamorous.View>
	)
}
<|endoftext|>


<commit_before>var Randomgit = {
    // Array of repositories currently loaded
    cache: [],

    // Array of the previously viewed repositories
    history: [],

    // Current language filter
    lang: "all",

    // Amount of pending requests to ajax/random.php
    currentRequests: 0,

    load: function() {
        this.fetchRepos();

        $("#rand-btn").click(this.showNextRepo.bind(this));
        $("#lang-select").change(this.changeLanguage.bind(this));

        var self = this;
        $("body").popover({
            title: 'History',
            placement: 'left',
            selector: '#history-btn',
            container: '#current-repo',
            html: 'true'
        }).tooltip({
            title: 'History of previously seen repositories',
            selector: '#history-btn',
            placement: 'top'
        }).on('show.bs.popover', function() {
            self.updateHistory();
            $("#history-btn").tooltip("hide");
            $("#history-btn").attr('data-content', $("#history-list").html());
        });
    },

    /**
     * Checks the cache's size. If it contains less than 10 repos, fetches 10 more.
     *
     * @todo Request a variable number of repos
     */
    fetchRepos: function() {
        var lang = this.lang,
            data = {limit: 10};  // TODO: make the amount variable

        if(lang !== "all") {
            data.lang = lang;
        }

        /* Sends a request to fetch data when the cache's size goes below 10.
         * Sends another one when the cache's size goes below 5. Thus, the two
         * requests won't happen at the same time which can avoid them bugging
         * because of them same network mini-lag.
         */
        if(this.cache.length < 10 && this.currentRequests < 1 || this.cache.length < 5 && this.currentRequests < 2) {
            this.currentRequests++;

            $.ajax({
                url: "ajax/random.php",
                type: "GET",
                data: data,
                dataType: "json",
                timeout: 30000,
                context: this,

                success: function(newRepos) {
                    // Makes sure the language hasn't changed since the request was sent
                    if(lang === this.lang) {
                        this.cache = this.cache.concat(newRepos);
                        this.enableRandBtn();
                    }
                },

                error: function(xhr, error, exception) {
                    console.log("Failed to fetch repos from the server");
                    console.log(error);
                    console.log(exception);
                    console.log("Retrying...");

                    var self = this;
                    setTimeout(function() {
                        self.fetchRepos();
                    }, 1000);
                },

                complete: function() {
                    this.currentRequests--;
                }
            });
        }
    },

    /**
     * Pops the next repo from the cache and shows it.
     */
    showNextRepo: function() {
        var repo = this.cache.shift();

        this.history.unshift(repo);
        if (this.history.length > 10) {
            this.history.pop();
        }

        if($("#next-repo").length === 0) {
            var template = tmpl("repo_tmpl", repo);
            $(template).appendTo("#readme-container");
            repo = this.cache.shift();
            this.history.unshift(repo);
        }

        $("#intro").slideUp();

        $("#next-repo")
            .css("display", "block")
            .animate({"opacity": 1}, 200, function() {
                $("#current-repo").remove();
                $("#next-repo").attr("id", "current-repo");

                // Loads the next readme in a hidden div
                var template = tmpl("repo_tmpl", repo);
                $(template).appendTo("#readme-container");
            });

        this.fetchRepos();

        if(this.cache.length === 0) {
            this.disableRandBtn();
        }

        // Send a google analytics event to track the click on Randomize!
        if(typeof _gaq == "object") {
            _gaq.push(["_trackEvent", "Repositories", "Randomize", this.lang]);
        }
    },

    /**
     * Disables the "Randomize!" button and changes its text to "Loading..."
     * The text change is done with CSS
     */
    disableRandBtn: function() {
        $("#rand-btn").prop("disabled", true);
    },

    /**
     * Re-enables the Randomize! button
     */
    enableRandBtn: function() {
        $("#rand-btn").prop("disabled", false).focus();
    },

    /**
     * Updates the current language according to the value of #lang-select
     */
    changeLanguage: function() {
        this.disableRandBtn();
        this.lang = $("#lang-select").val();
        this.cache = [];
        $("#next-repo").remove();
        this.fetchRepos();
    },

    /**
     * Updates the html content of the history popover
     */
    updateHistory: function() {
        var list = $("#history-list .list-group");

        list.html("");

        this.history.forEach(function(repo, index) {
            /* Does not show the first element of the history because it
             * was displayed yet (currently waiting in next-repo).
             */
            if (index > 0) {
                var template = tmpl("history_item_tmpl", repo);
                list.append(template);
            }
        });
    }
}<commit_msg>Sets the language filter to 'all' by default because sometimes the browser keeps the state of the <select><commit_after>var Randomgit = {
    // Array of repositories currently loaded
    cache: [],

    // Array of the previously viewed repositories
    history: [],

    // Current language filter
    lang: "all",

    // Amount of pending requests to ajax/random.php
    currentRequests: 0,

    load: function() {
        this.fetchRepos();

        $("#lang-select").val("all");

        $("#rand-btn").click(this.showNextRepo.bind(this));
        $("#lang-select").change(this.changeLanguage.bind(this));

        var self = this;
        $("body").popover({
            title: 'History',
            placement: 'left',
            selector: '#history-btn',
            container: '#current-repo',
            html: 'true'
        }).tooltip({
            title: 'History of previously seen repositories',
            selector: '#history-btn',
            placement: 'top'
        }).on('show.bs.popover', function() {
            self.updateHistory();
            $("#history-btn").tooltip("hide");
            $("#history-btn").attr('data-content', $("#history-list").html());
        });
    },

    /**
     * Checks the cache's size. If it contains less than 10 repos, fetches 10 more.
     *
     * @todo Request a variable number of repos
     */
    fetchRepos: function() {
        var lang = this.lang,
            data = {limit: 10};  // TODO: make the amount variable

        if(lang !== "all") {
            data.lang = lang;
        }

        /* Sends a request to fetch data when the cache's size goes below 10.
         * Sends another one when the cache's size goes below 5. Thus, the two
         * requests won't happen at the same time which can avoid them bugging
         * because of them same network mini-lag.
         */
        if(this.cache.length < 10 && this.currentRequests < 1 || this.cache.length < 5 && this.currentRequests < 2) {
            this.currentRequests++;

            $.ajax({
                url: "ajax/random.php",
                type: "GET",
                data: data,
                dataType: "json",
                timeout: 30000,
                context: this,

                success: function(newRepos) {
                    // Makes sure the language hasn't changed since the request was sent
                    if(lang === this.lang) {
                        this.cache = this.cache.concat(newRepos);
                        this.enableRandBtn();
                    }
                },

                error: function(xhr, error, exception) {
                    console.log("Failed to fetch repos from the server");
                    console.log(error);
                    console.log(exception);
                    console.log("Retrying...");

                    var self = this;
                    setTimeout(function() {
                        self.fetchRepos();
                    }, 1000);
                },

                complete: function() {
                    this.currentRequests--;
                }
            });
        }
    },

    /**
     * Pops the next repo from the cache and shows it.
     */
    showNextRepo: function() {
        var repo = this.cache.shift();

        this.history.unshift(repo);
        if (this.history.length > 10) {
            this.history.pop();
        }

        if($("#next-repo").length === 0) {
            var template = tmpl("repo_tmpl", repo);
            $(template).appendTo("#readme-container");
            repo = this.cache.shift();
            this.history.unshift(repo);
        }

        $("#intro").slideUp();

        $("#next-repo")
            .css("display", "block")
            .animate({"opacity": 1}, 200, function() {
                $("#current-repo").remove();
                $("#next-repo").attr("id", "current-repo");

                // Loads the next readme in a hidden div
                var template = tmpl("repo_tmpl", repo);
                $(template).appendTo("#readme-container");
            });

        this.fetchRepos();

        if(this.cache.length === 0) {
            this.disableRandBtn();
        }

        // Send a google analytics event to track the click on Randomize!
        if(typeof _gaq == "object") {
            _gaq.push(["_trackEvent", "Repositories", "Randomize", this.lang]);
        }
    },

    /**
     * Disables the "Randomize!" button and changes its text to "Loading..."
     * The text change is done with CSS
     */
    disableRandBtn: function() {
        $("#rand-btn").prop("disabled", true);
    },

    /**
     * Re-enables the Randomize! button
     */
    enableRandBtn: function() {
        $("#rand-btn").prop("disabled", false).focus();
    },

    /**
     * Updates the current language according to the value of #lang-select
     */
    changeLanguage: function() {
        this.disableRandBtn();
        this.lang = $("#lang-select").val();
        this.cache = [];
        $("#next-repo").remove();
        this.fetchRepos();
    },

    /**
     * Updates the html content of the history popover
     */
    updateHistory: function() {
        var list = $("#history-list .list-group");

        list.html("");

        this.history.forEach(function(repo, index) {
            /* Does not show the first element of the history because it
             * was displayed yet (currently waiting in next-repo).
             */
            if (index > 0) {
                var template = tmpl("history_item_tmpl", repo);
                list.append(template);
            }
        });
    }
}<|endoftext|>


<commit_before>(function () {

    'use strict';

    /* global require:true */
    /* global __dirname:true */
    /* global console:true */

    // Configuration
    var destination = './../static/vaultier/';
    var destinationUrl = '/static/vaultier/';
    var sourcesDestination = destination;
    var includesFile = destination + 'includes.json';
    var environment = 'dev';

    // Load modules definition
    var modulesFilename = './modules.js';
    var modulesDefinition = require(modulesFilename);
    var modulesTasks = [];
    var moduleTaskNameFormat = 'build-module-{name}';
    var moduleScriptFilenameFormat = '{name}.js';
    var moduleTemplateFilenameFormat = '{name}.tpl.js';

    // Gulp requirements
    var gulp = require('gulp');

    var gulp_concat = require('gulp-concat');
    var gulp_concat_sourcemap = require('gulp-concat-sourcemap');
    var gulp_uglify = require('gulp-uglify');
    var gulp_jshint = require('gulp-jshint');
    var gulp_sourcemaps = require('gulp-sourcemaps');
    var gulp_newer = require('gulp-newer'); // including only newer files
    var gulp_rimraf = require('gulp-rimraf'); // deleting and cleaning
    var gulp_hbars = require('gulp-ember-handlebars');
    var gulp_watch = require('gulp-watch');
    var gulp_livereload = require('gulp-livereload');

    // Global requirements
    var runSequence = require('run-sequence');
    var fs = require('fs');
    var path = require('path');

    var createTemplateBuildTask = function (taskname, name, content) {
        var destFile = moduleTemplateFilenameFormat.replace('{name}', name);
        var glob = content.templates;

        gulp.task(taskname, function () {
            return gulp
                .src(glob)
                .pipe(gulp_newer(destination + destFile))
                .pipe(gulp_hbars({
                    outputType: 'browser',
                    processTemplatePath: function (file) {
                        var path = file.path;
                        var dirs = path.split('/');
                        return dirs.slice(-2).join('/');
                    }
                }))
//                .pipe(gulp_sourcemaps.init())
//                .pipe(gulp_uglify())
//                .pipe(gulp_concat(destFile))
//                .pipe(gulp_sourcemaps.write())

                .pipe(gulp_concat_sourcemap(destFile))
                .pipe(gulp.dest(destination));
        });
    };

    var createScriptsBuildTask = function (taskname, name, content) {
        var destFile = moduleScriptFilenameFormat.replace('{name}', name);
        var glob = content.scripts;
        gulp.task(taskname, function () {
            return gulp
                .src(glob)
                .pipe(gulp_newer(destination + destFile))
//                .pipe(gulp_sourcemaps.init())
//                .pipe(gulp_uglify())
//                .pipe(gulp_concat(destFile))
//                .pipe(gulp_sourcemaps.write())

                .pipe(gulp_concat_sourcemap(destFile))
                .pipe(gulp.dest(destination));
        });

    };

    var createBuildTasksForModules = function () {
        var modules = modulesDefinition[environment];

        for (var m in modules) {
            if (modules.hasOwnProperty(m)) {
                var name = m;
                var content = modules[m];
                var taskname = moduleTaskNameFormat.replace('{name}', name);
                var subtasks = [];

                if (content.templates) {
                    var templatesTaskname = taskname + '-templates';
                    createTemplateBuildTask(templatesTaskname, name, content);
                    subtasks.push(templatesTaskname);
                }

                if (content.scripts) {
                    var scriptsTaskname = taskname + '-scripts';
                    createScriptsBuildTask(scriptsTaskname, name, content);
                    subtasks.push(scriptsTaskname);
                }

                gulp.task(taskname, subtasks);
                modulesTasks.push(taskname);
            }
        }

    };

    createBuildTasksForModules();

    gulp.task('build-resources', function () {
        var modules = modulesDefinition[environment];
        var resources = [];
        for (var m in modules) {
            if (modules.hasOwnProperty(m)) {
                var name = m;
                var content = modules[m];
                if (content.resources) {
                    resources = resources.concat(content.resources);
                }
                if (content.styles) {
                    resources = resources.concat(content.styles);
                }
            }
        }

        resources = resources.concat([
            // add custom resources to copy here
        ]);

        return gulp
            .src(resources, { base: './' })
            .pipe(gulp_newer(sourcesDestination))
            .pipe(gulp.dest(sourcesDestination));
    });

    gulp.task('build-includes', function (cb) {
        var modules = modulesDefinition[environment];
        var scripts = [];
        var styles = [];
        for (var m in modules) {
            if (modules.hasOwnProperty(m)) {
                var name = m;
                var content = modules[m];
                if (content.scripts && !content.skipLoading) {
                    scripts.push(
                            destination + moduleScriptFilenameFormat.replace('{name}', name)
                    );
                }
                if (content.templates && !content.skipLoading) {
                    scripts.push(
                            destination + moduleTemplateFilenameFormat.replace('{name}', name)
                    );
                }
                if (content.styles && !content.skipLoading) {
                    for (var i = 0; i < content.styles.length; i++) {
                        styles.push(destination + content.styles[i].replace('./', ''));
                    }
                }
            }
        }

        var buildForFileType = function (urls, files, type) {
            for (var i = 0; i < files.length; i++) {
                var destinationPath = path.resolve(destination) + '/';
                var filepath = path.resolve(__dirname, files[i]);
                var mtime = fs.statSync(filepath).mtime.getTime();
                var url = filepath.replace(destinationPath, destinationUrl);
                url = url + '?t=' + mtime;

                urls.push({file: url, type: type});
            }
        };

        var urls = [];
        buildForFileType(urls, scripts, 'scripts');
        buildForFileType(urls, styles, 'styles');

        var pathname = path.resolve(includesFile);
        var file = fs.openSync(pathname, 'w');
        fs.writeSync(file, JSON.stringify({modules: urls}));
        fs.close(file);

        cb();
    });

    gulp.task('clean', function () {
        return gulp.src(destination)
            .pipe(gulp_rimraf({force: true}));
    });

    gulp.task('build', function () {
        var buildTasks = [].concat(modulesTasks, ['build-resources']);

        return runSequence(
            buildTasks,
            'build-includes'
        );
    });

    gulp.task('watch', ['build'], function () {
        gulp_livereload.listen();

        var modules = modulesDefinition[environment];
        var glob = [];
        for (var m in modules) {
            if (modules.hasOwnProperty(m)) {
                var content = modules[m];
                if (content.scripts) {
                    glob = glob.concat(content.scripts);
                }
                if (content.templates) {
                    glob = glob.concat(content.templates);
                }
                if (content.styles) {
                    glob = glob.concat(content.styles);
                }
                if (content.images) {
                    glob = glob.concat(content.images);
                }
            }
        }

        gulp.watch(glob, ['build']);

        gulp.watch([destination + '**/*.*'], function (file) {
            var message = file.path + ' ...rebuilt';
            if (file.path.indexOf(path.resolve(includesFile)) === -1) {
                message = message + ' ...reloading';
                gulp_livereload.changed(file.path);
            }
            console.log(message);
        });

    });

    gulp.task('default', ['watch']);

    gulp.task('clean-build', function () {
        return runSequence(
            'clean',
            'build'
        );
    });

}());

<commit_msg>fixes #223 create gulp task (clean&watch)<commit_after>(function () {

    'use strict';

    /* global require:true */
    /* global __dirname:true */
    /* global console:true */

    // Configuration
    var destination = './../static/vaultier/';
    var destinationUrl = '/static/vaultier/';
    var sourcesDestination = destination;
    var includesFile = destination + 'includes.json';
    var environment = 'dev';

    // Load modules definition
    var modulesFilename = './modules.js';
    var modulesDefinition = require(modulesFilename);
    var modulesTasks = [];
    var moduleTaskNameFormat = 'build-module-{name}';
    var moduleScriptFilenameFormat = '{name}.js';
    var moduleTemplateFilenameFormat = '{name}.tpl.js';

    // Gulp requirements
    var gulp = require('gulp');

    var gulp_concat = require('gulp-concat');
    var gulp_concat_sourcemap = require('gulp-concat-sourcemap');
    var gulp_uglify = require('gulp-uglify');
    var gulp_jshint = require('gulp-jshint');
    var gulp_sourcemaps = require('gulp-sourcemaps');
    var gulp_newer = require('gulp-newer'); // including only newer files
    var gulp_rimraf = require('gulp-rimraf'); // deleting and cleaning
    var gulp_hbars = require('gulp-ember-handlebars');
    var gulp_watch = require('gulp-watch');
    var gulp_livereload = require('gulp-livereload');

    // Global requirements
    var runSequence = require('run-sequence');
    var fs = require('fs');
    var path = require('path');

    var createTemplateBuildTask = function (taskname, name, content) {
        var destFile = moduleTemplateFilenameFormat.replace('{name}', name);
        var glob = content.templates;

        gulp.task(taskname, function () {
            return gulp
                .src(glob)
                .pipe(gulp_newer(destination + destFile))
                .pipe(gulp_hbars({
                    outputType: 'browser',
                    processTemplatePath: function (file) {
                        var path = file.path;
                        var dirs = path.split('/');
                        return dirs.slice(-2).join('/');
                    }
                }))
//                .pipe(gulp_sourcemaps.init())
//                .pipe(gulp_uglify())
//                .pipe(gulp_concat(destFile))
//                .pipe(gulp_sourcemaps.write())

                .pipe(gulp_concat_sourcemap(destFile))
                .pipe(gulp.dest(destination));
        });
    };

    var createScriptsBuildTask = function (taskname, name, content) {
        var destFile = moduleScriptFilenameFormat.replace('{name}', name);
        var glob = content.scripts;
        gulp.task(taskname, function () {
            return gulp
                .src(glob)
                .pipe(gulp_newer(destination + destFile))
//                .pipe(gulp_sourcemaps.init())
//                .pipe(gulp_uglify())
//                .pipe(gulp_concat(destFile))
//                .pipe(gulp_sourcemaps.write())

                .pipe(gulp_concat_sourcemap(destFile))
                .pipe(gulp.dest(destination));
        });

    };

    var createBuildTasksForModules = function () {
        var modules = modulesDefinition[environment];

        for (var m in modules) {
            if (modules.hasOwnProperty(m)) {
                var name = m;
                var content = modules[m];
                var taskname = moduleTaskNameFormat.replace('{name}', name);
                var subtasks = [];

                if (content.templates) {
                    var templatesTaskname = taskname + '-templates';
                    createTemplateBuildTask(templatesTaskname, name, content);
                    subtasks.push(templatesTaskname);
                }

                if (content.scripts) {
                    var scriptsTaskname = taskname + '-scripts';
                    createScriptsBuildTask(scriptsTaskname, name, content);
                    subtasks.push(scriptsTaskname);
                }

                gulp.task(taskname, subtasks);
                modulesTasks.push(taskname);
            }
        }

    };

    createBuildTasksForModules();

    gulp.task('build-resources', function () {
        var modules = modulesDefinition[environment];
        var resources = [];
        for (var m in modules) {
            if (modules.hasOwnProperty(m)) {
                var name = m;
                var content = modules[m];
                if (content.resources) {
                    resources = resources.concat(content.resources);
                }
                if (content.styles) {
                    resources = resources.concat(content.styles);
                }
            }
        }

        resources = resources.concat([
            // add custom resources to copy here
        ]);

        return gulp
            .src(resources, { base: './' })
            .pipe(gulp_newer(sourcesDestination))
            .pipe(gulp.dest(sourcesDestination));
    });

    gulp.task('build-includes', function (cb) {
        var modules = modulesDefinition[environment];
        var scripts = [];
        var styles = [];
        for (var m in modules) {
            if (modules.hasOwnProperty(m)) {
                var name = m;
                var content = modules[m];
                if (content.scripts && !content.skipLoading) {
                    scripts.push(
                            destination + moduleScriptFilenameFormat.replace('{name}', name)
                    );
                }
                if (content.templates && !content.skipLoading) {
                    scripts.push(
                            destination + moduleTemplateFilenameFormat.replace('{name}', name)
                    );
                }
                if (content.styles && !content.skipLoading) {
                    for (var i = 0; i < content.styles.length; i++) {
                        styles.push(destination + content.styles[i].replace('./', ''));
                    }
                }
            }
        }

        var buildForFileType = function (urls, files, type) {
            for (var i = 0; i < files.length; i++) {
                var destinationPath = path.resolve(destination) + '/';
                var filepath = path.resolve(__dirname, files[i]);
                var mtime = fs.statSync(filepath).mtime.getTime();
                var url = filepath.replace(destinationPath, destinationUrl);
                url = url + '?t=' + mtime;

                urls.push({file: url, type: type});
            }
        };

        var urls = [];
        buildForFileType(urls, scripts, 'scripts');
        buildForFileType(urls, styles, 'styles');

        var pathname = path.resolve(includesFile);
        var file = fs.openSync(pathname, 'w');
        fs.writeSync(file, JSON.stringify({modules: urls}));
        fs.close(file);

        cb();
    });

    gulp.task('clean', function () {
        return gulp.src(destination)
            .pipe(gulp_rimraf({force: true}));
    });

    gulp.task('build', function () {
        var buildTasks = [].concat(modulesTasks, ['build-resources']);

        return runSequence(
            buildTasks,
            'build-includes'
        );
    });

    gulp.task('watch', ['build'], function () {
        gulp_livereload.listen();

        var modules = modulesDefinition[environment];
        var glob = [];
        for (var m in modules) {
            if (modules.hasOwnProperty(m)) {
                var content = modules[m];
                if (content.scripts) {
                    glob = glob.concat(content.scripts);
                }
                if (content.templates) {
                    glob = glob.concat(content.templates);
                }
                if (content.styles) {
                    glob = glob.concat(content.styles);
                }
                if (content.images) {
                    glob = glob.concat(content.images);
                }
            }
        }

        gulp.watch(glob, ['build']);

        gulp.watch([destination + '**/*.*'], function (file) {
            var message = file.path + ' ...rebuilt';
            if (file.path.indexOf(path.resolve(includesFile)) === -1) {
                message = message + ' ...reloading';
                gulp_livereload.changed(file.path);
            }
            console.log(message);
        });

    });

    gulp.task('default', ['watch']);

    gulp.task('clean-build', function () {
        return runSequence(
            'clean',
            'build'
        );
    });

    gulp.task('clean-watch', function () {
        return runSequence(
            'clean',
            'build',
            'watch'
        );
    });

}());

<|endoftext|>