<commit_before>//Add listener for the keyboard when a key is released.
//By Rory Bell and Alan Easdale
window.addEventListener("keyup", keyboardControls, false);

//Keyboard controller.
function keyboardControls(e) {
    if (e.keyCode == ("32"))
        Game.player.switchControl();
}

//Game object.
var Game = {
    fps: 60,
    width: 640,
    height: 480,
    time: 0
};

//Does animation stuff, need to look into how this actually works.
Game._onEachFrame = (function () {
    var requestAnimationFrame = window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame;

    if (requestAnimationFrame) {
        return function (cb) {
            var _cb = function () {
                cb();
                requestAnimationFrame(_cb);
            }
            _cb();
        };
    } else {
        return function (cb) {
            setInterval(cb, 1000 / Game.fps);
        }
    }
})();

Game.run = (function () {
    var loops = 0, skipTicks = 1000 / Game.fps,
        maxFrameSkip = 10,
        nextGameTick = (new Date).getTime(),
        lastGameTick;

    return function () {

        while ((new Date).getTime() > nextGameTick) {
            Game.update();
            nextGameTick += skipTicks;
            loops++;
        }

        if (loops) Game.draw();
    }
})();

//Sets up the Game object.
Game.start = function () {
    //Retrieves the canvas from the html file.
    Game.canvas = document.getElementById("canvas");
    Game.canvas.width = Game.width;
    Game.canvas.height = Game.height;
    console.log("start");
    //Retrives a copy of the context.
    Game.context = Game.canvas.getContext("2d");

    //Dont know what this does yet.
    document.body.appendChild(Game.canvas);

    //Instantiates a new player.
    Game.player = new Player();

    //Dont know what this does yet.
    Game._onEachFrame(Game.run);
};

Game.update = function () {
    Game.player.update();
};

Game.draw = function () {
    Game.context.clearRect(0, 0, Game.width, Game.height);
    Game.player.draw(Game.context);
};

//Player object.
function Player() {
    this.x = 0;
    this.y = 0;
    this.rot = 0;
    this.speed = 0.05;
    this.movDir = true;
    this.projectile = new Projectile();

//Updates the rotation of the player.
    this.update = function () {
        if (this.movDir == true)
            this.rot -= this.speed;
        else
            this.rot += this.speed;

        if (this.rot > Math.PI*2)
            this.rot -= Math.PI*2;
        if (this.rot < -Math.PI*2)
            this.rot += Math.PI*2;

        if (this.projectile.alive == true)
            this.projectile.update();
    }

//Control for flipping rotation direction and firing (To be added).
    this.switchControl = function () {
        this.movDir = !this.movDir;
        this.projectile.spawn(this.x, this.y, this.rot, 2.5);
    }

    this.draw = function (context) {

        //Calculate the position of the player in accordance to the "this.rot" value.
        this.x = (Game.width / 2) + 30 * Math.cos(this.rot);
        this.y = (Game.height / 2) + 30 * Math.sin(this.rot);

        //Create a 8x8 pixel filled rectangle at the position of [x,y]
        context.fillRect(this.x - 4, this.y - 4, 8, 8);

        //Create a 20r circle at the center of the screen.
        context.beginPath();
        context.arc(Game.width / 2, Game.height / 2, 20, 0, Math.PI * 2, false);
        //context.fillStyle = "green";
        context.fill();
        context.closePath();

        if (this.projectile.alive == true)
            this.projectile.draw(context);
    }

}

//Projectile object.
function Projectile() {
    this.alive = false;

    this.spawn = function (x, y, angle, speed) {
        this.x = x;
        this.y = y;
        this.rot = angle;
        this.speed = speed;
        this.alive = true;
        console.log("Pos: " + this.x + " " + this.y);
        console.log("Rot: " + this.rot);
        console.log("Spe: " + this.speed);

    }

    this.update = function () {
        //Move by 'speed' in the direction of 'rot'.
        this.x += this.speed * Math.cos(this.rot);
        this.y += this.speed * Math.sin(this.rot);

        if (this.x > Game.width || this.x < 0 || this.y < 0 || this.y > Game.height)
        {
            this.destroy();
            console.log("Bullet reset.");
        }
    }

    this.draw = function (context) {
        //Create a 4x4 pixel filled rectangle at the position of [x,y]
        context.fillRect(this.x - 2, this.y - 2, 4, 4);
    }
    this.destroy = function () {
        this.x = 0;
        this.y = 0;
        this.rot = 0;
        this.speed = 0;
        this.alive = false;
    }
}<commit_msg>Git test... Again<commit_after>//Add listener for the keyboard when a key is released.
//By Rory Bell and Alan Easdale
window.addEventListener("keyup", keyboardControls, false);

//Keyboard controller.
function keyboardControls(e) {
    if (e.keyCode == ("32"))
        Game.player.switchControl();
}

//Game object.
var Game = {
    fps: 60,
    width: 640,
    height: 480,
    time: 0
};

//Does animation stuff, need to look into how this actually works.
Game._onEachFrame = (function () {
    var requestAnimationFrame = window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame;

    if (requestAnimationFrame) {
        return function (cb) {
            var _cb = function () {
                cb();
                requestAnimationFrame(_cb);
            }
            _cb();
        };
    } else {
        return function (cb) {
            setInterval(cb, 1000 / Game.fps);
        }
    }
})();

Game.run = (function () {
    var loops = 0, skipTicks = 1000 / Game.fps,
        maxFrameSkip = 10,
        nextGameTick = (new Date).getTime(),
        lastGameTick;

    return function () {

        while ((new Date).getTime() > nextGameTick) {
            Game.update();
            nextGameTick += skipTicks;
            loops++;
        }

        if (loops) Game.draw();
    }
})();

//Sets up the Game object.
Game.start = function () {
    //Retrieves the canvas from the html file.
    Game.canvas = document.getElementById("canvas");
    Game.canvas.width = Game.width;
    Game.canvas.height = Game.height;
    console.log("start");
    //Retrives a copy of the context.
    Game.context = Game.canvas.getContext("2d");

    //Dont know what this does yet.
    document.body.appendChild(Game.canvas);

    console.log("Line test")

    //Instantiates a new player.
    Game.player = new Player();

    //Dont know what this does yet.
    Game._onEachFrame(Game.run);
};

Game.update = function () {
    Game.player.update();
};

Game.draw = function () {
    Game.context.clearRect(0, 0, Game.width, Game.height);
    Game.player.draw(Game.context);
};

//Player object.
function Player() {
    this.x = 0;
    this.y = 0;
    this.rot = 0;
    this.speed = 0.05;
    this.movDir = true;
    this.projectile = new Projectile();

//Updates the rotation of the player.
    this.update = function () {
        if (this.movDir == true)
            this.rot -= this.speed;
        else
            this.rot += this.speed;

        if (this.rot > Math.PI*2)
            this.rot -= Math.PI*2;
        if (this.rot < -Math.PI*2)
            this.rot += Math.PI*2;

        if (this.projectile.alive == true)
            this.projectile.update();
    }

//Control for flipping rotation direction and firing (To be added).
    this.switchControl = function () {
        this.movDir = !this.movDir;
        this.projectile.spawn(this.x, this.y, this.rot, 2.5);
    }

    this.draw = function (context) {

        //Calculate the position of the player in accordance to the "this.rot" value.
        this.x = (Game.width / 2) + 30 * Math.cos(this.rot);
        this.y = (Game.height / 2) + 30 * Math.sin(this.rot);

        //Create a 8x8 pixel filled rectangle at the position of [x,y]
        context.fillRect(this.x - 4, this.y - 4, 8, 8);

        //Create a 20r circle at the center of the screen.
        context.beginPath();
        context.arc(Game.width / 2, Game.height / 2, 20, 0, Math.PI * 2, false);
        //context.fillStyle = "green";
        context.fill();
        context.closePath();

        if (this.projectile.alive == true)
            this.projectile.draw(context);
    }

}

//Projectile object.
function Projectile() {
    this.alive = false;

    this.spawn = function (x, y, angle, speed) {
        this.x = x;
        this.y = y;
        this.rot = angle;
        this.speed = speed;
        this.alive = true;
        console.log("Pos: " + this.x + " " + this.y);
        console.log("Rot: " + this.rot);
        console.log("Spe: " + this.speed);

    }

    this.update = function () {
        //Move by 'speed' in the direction of 'rot'.
        this.x += this.speed * Math.cos(this.rot);
        this.y += this.speed * Math.sin(this.rot);

        if (this.x > Game.width || this.x < 0 || this.y < 0 || this.y > Game.height)
        {
            this.destroy();
            console.log("Bullet reset.");
        }
    }

    this.draw = function (context) {
        //Create a 4x4 pixel filled rectangle at the position of [x,y]
        context.fillRect(this.x - 2, this.y - 2, 4, 4);
    }
    this.destroy = function () {
        this.x = 0;
        this.y = 0;
        this.rot = 0;
        this.speed = 0;
        this.alive = false;
    }
}<|endoftext|>


<commit_before>define([
    'jquery',
    'jqueryui',
    'underscore',
    'backbone',
    'models/faunaSpeciesList',
    'models/floraSpeciesList',
    'models/communityList',
    'models/wetlandList',
    'views/assets/assetsSpeciesSummaryView',
    'views/assets/assetsCommunitySummaryView',
    'text!templates/assets.html'
], function ($, ui, _, Backbone, FaunaList, FloraList, CommunityList, WetlandList, SpeciesSummaryView, CommunitySummaryView, template) {

    function getSpeciesLabel(model) {
        var result = model.id();
        if (model.name()) {
            result += ' (' + model.name() + ')';
        }
        return result;
    }

    function getCommunityLabel(model) {
        var result = model.id();
        if (model.name()) {
            result += ' (' + model.name() + ')';
        }
        return result;
    }

    function getWetlandLabel(model) {
        return model.id();
    }

    return Backbone.View.extend({
        el: '#content',
        events: {
            "click #species_header": function () {
                this.clear('species')
            },
            "click #community_header": function () {
                this.clear('community')
            },
            "click #wetland_header": function () {
                this.clear('wetland')
            }
        },

        initialize: function () {
            this.fauna = new FaunaList();
            this.flora = new FloraList();
            this.communities = new CommunityList();
            this.wetlands = new WetlandList();
        },

        render: function (type, id) {
            this.$el.html(_.template(template, {}));
            this.initSpeciesInputs();
            this.initCommunityInputs();
            this.initWetlandInputs();
            this.fauna.on("reset", this.initSpeciesInputs, this);
            this.flora.on("reset", this.initSpeciesInputs, this);
            this.communities.on("reset", this.initCommunityInputs, this);
            this.wetlands.on("reset", this.initWetlandInputs, this);
            // show something?
            if (type || id) {
                if (type === 'fauna' || type === 'flora'){
                    type = 'species';
                }
                this.doSelectValue(type, id);
            }
            else {
                $('#species_header').click();
            }
        },

        doSelectValue: function (type, id){
            // here type must be species, community, wetland
            var tab = this.$el.find("#" + type + "_header"),
                input = this.$el.find("#" + type + "_input"),
                menu;
            // select the tab
            tab.click();
            // simulate a auto complete selection
            input.autocomplete("search", id);
            menu = input.autocomplete("widget");
            $(menu[0].children[0]).click();
        },

        initSpeciesInputs: function () {
            $("#species_input").autocomplete({
                source: _.bind(function (request, response) {
                    var faunaValues = this.fauna ? this.buildTaxaValues(this.fauna, 'fauna') : [];
                    var floraValues = this.flora ? this.buildTaxaValues(this.flora, 'flora') : [];
                    var allValues = faunaValues.concat(floraValues);
                    //delegate to the normal auto complete response
                    response($.ui.autocomplete.filter(allValues, request.term));
                }, this),
                select: _.bind(function (event, ui) {
                    this.showSpeciesSummary(ui.item.category, ui.item.value);
                }, this)
            });
        },

        initCommunityInputs: function () {
            $("#community_input").autocomplete({
                source: _.bind(function (request, response) {
                    var allValues = this.communities.map(function (model) {
                        return {
                            value: model.id(),
                            label: getCommunityLabel(model)
                        }
                    });
                    response($.ui.autocomplete.filter(allValues, request.term));
                }, this),
                select: _.bind(function (event, ui) {
                    this.showCommunitySummary(ui.item.value)
                }, this)
            })
        },

        initWetlandInputs: function () {
            $("#wetland_input").autocomplete({
                source: _.bind(function (request, response) {
                    var allValues = this.wetlands.map(function (model) {
                        return {
                            value: model.id(),
                            label: getWetlandLabel(model)
                        }
                    });
                    response($.ui.autocomplete.filter(allValues, request.term));
                }, this),
                select: _.bind(function (event, ui) {
                    this.showWetlandSummary(ui.item.value, ui.item.label)
                }, this)
            })
        },

        showSpeciesSummary: function (category, taxon) {
            var collection, model, records;
            collection = category === 'fauna' ? this.fauna : this.flora;
            model = collection.find(function (model) {
                return model.id() === taxon;
            });
            if (model) {
                records = model.recordsByRegion();
                // clear previous tables
                this.clearTables();
                new SpeciesSummaryView({model: records, label: getSpeciesLabel(model)}).render();
            }
        },

        showCommunitySummary: function (id) {
            var model, records;
            model = this.communities.find(function (m) {
                return m.id() === id
            });
            if (model) {
                records = model.recordsByRegion();
                this.clearTables();
                new CommunitySummaryView({model: records, label: id}).render();
            }
        },

        showWetlandSummary: function (id) {
            var model, records;
            model = this.wetlands.find(function (m) {
                return m.id() === id
            });
            if (model) {
                records = model.recordsByRegion();
                this.clearTables();
                new CommunitySummaryView({model: records, label: id}).render();
            }
        },

        buildTaxaValues: function (collection, category) {
            return collection.map(function (model) {
                return {
                    value: model.id(),
                    label: getSpeciesLabel(model),
                    category: category
                };
            });
        },

        clearTables: function () {
            this.$el.find('#summary_content').html('');
            this.$el.find('#details_content').html('');
        },

        clearInput: function (type) {
            this.$el.find('#' + type + '_input').autocomplete().val('');
        },

        clear: function (type) {
            this.clearTables();
            this.clearInput(type);
        }

    });
});<commit_msg>- refactor<commit_after>define([
    'jquery',
    'jqueryui',
    'underscore',
    'backbone',
    'models/faunaSpeciesList',
    'models/floraSpeciesList',
    'models/communityList',
    'models/wetlandList',
    'views/assets/assetsSpeciesSummaryView',
    'views/assets/assetsCommunitySummaryView',
    'text!templates/assets.html'
], function ($, ui, _, Backbone, FaunaList, FloraList, CommunityList, WetlandList, SpeciesSummaryView, CommunitySummaryView, template) {

    function getSpeciesLabel(model) {
        var result = model.id();
        if (model.name()) {
            result += ' (' + model.name() + ')';
        }
        return result;
    }

    function getCommunityLabel(model) {
        var result = model.id();
        if (model.name()) {
            result += ' (' + model.name() + ')';
        }
        return result;
    }

    function getWetlandLabel(model) {
        return model.id();
    }

    return Backbone.View.extend({
        el: '#content',
        events: {
            "click #species_header": function () {
                this.clear('species')
            },
            "click #community_header": function () {
                this.clear('community')
            },
            "click #wetland_header": function () {
                this.clear('wetland')
            }
        },

        initialize: function () {
            this.fauna = new FaunaList();
            this.flora = new FloraList();
            this.communities = new CommunityList();
            this.wetlands = new WetlandList();
        },

        render: function (type, id) {
            this.$el.html(_.template(template, {}));
            this.initSpeciesInputs();
            this.initCommunityInputs();
            this.initWetlandInputs();
            this.fauna.on("reset", this.initSpeciesInputs, this);
            this.flora.on("reset", this.initSpeciesInputs, this);
            this.communities.on("reset", this.initCommunityInputs, this);
            this.wetlands.on("reset", this.initWetlandInputs, this);
            // show something?
            if (type || id) {
                if (type === 'fauna' || type === 'flora'){
                    type = 'species';
                }
                this.doSelectValue(type, id);
            }
            else {
                this.doSelectValue('species', undefined);
            }
        },

        doSelectValue: function (type, id){
            // here type must be species, community, wetland
            var tab = this.$el.find("#" + type + "_header"),
                input = this.$el.find("#" + type + "_input"),
                menu;
            // select the tab
            tab.click();
            // simulate a auto complete selection
            if (id) {
                input.autocomplete("search", id);
            }
            menu = input.autocomplete("widget");
            $(menu[0].children[0]).click();
        },

        initSpeciesInputs: function () {
            $("#species_input").autocomplete({
                source: _.bind(function (request, response) {
                    var faunaValues = this.fauna ? this.buildTaxaValues(this.fauna, 'fauna') : [];
                    var floraValues = this.flora ? this.buildTaxaValues(this.flora, 'flora') : [];
                    var allValues = faunaValues.concat(floraValues);
                    //delegate to the normal auto complete response
                    response($.ui.autocomplete.filter(allValues, request.term));
                }, this),
                select: _.bind(function (event, ui) {
                    this.showSpeciesSummary(ui.item.category, ui.item.value);
                }, this)
            });
        },

        initCommunityInputs: function () {
            $("#community_input").autocomplete({
                source: _.bind(function (request, response) {
                    var allValues = this.communities.map(function (model) {
                        return {
                            value: model.id(),
                            label: getCommunityLabel(model)
                        }
                    });
                    response($.ui.autocomplete.filter(allValues, request.term));
                }, this),
                select: _.bind(function (event, ui) {
                    this.showCommunitySummary(ui.item.value)
                }, this)
            })
        },

        initWetlandInputs: function () {
            $("#wetland_input").autocomplete({
                source: _.bind(function (request, response) {
                    var allValues = this.wetlands.map(function (model) {
                        return {
                            value: model.id(),
                            label: getWetlandLabel(model)
                        }
                    });
                    response($.ui.autocomplete.filter(allValues, request.term));
                }, this),
                select: _.bind(function (event, ui) {
                    this.showWetlandSummary(ui.item.value, ui.item.label)
                }, this)
            })
        },

        showSpeciesSummary: function (category, taxon) {
            var collection, model, records;
            collection = category === 'fauna' ? this.fauna : this.flora;
            model = collection.find(function (model) {
                return model.id() === taxon;
            });
            if (model) {
                records = model.recordsByRegion();
                // clear previous tables
                this.clearTables();
                new SpeciesSummaryView({model: records, label: getSpeciesLabel(model)}).render();
            }
        },

        showCommunitySummary: function (id) {
            var model, records;
            model = this.communities.find(function (m) {
                return m.id() === id
            });
            if (model) {
                records = model.recordsByRegion();
                this.clearTables();
                new CommunitySummaryView({model: records, label: id}).render();
            }
        },

        showWetlandSummary: function (id) {
            var model, records;
            model = this.wetlands.find(function (m) {
                return m.id() === id
            });
            if (model) {
                records = model.recordsByRegion();
                this.clearTables();
                new CommunitySummaryView({model: records, label: id}).render();
            }
        },

        buildTaxaValues: function (collection, category) {
            return collection.map(function (model) {
                return {
                    value: model.id(),
                    label: getSpeciesLabel(model),
                    category: category
                };
            });
        },

        clearTables: function () {
            this.$el.find('#summary_content').html('');
            this.$el.find('#details_content').html('');
        },

        clearInput: function (type) {
            this.$el.find('#' + type + '_input').autocomplete().val('');
        },

        clear: function (type) {
            this.clearTables();
            this.clearInput(type);
        }

    });
});<|endoftext|>


<commit_before>window.onload = function() {

    WebFontConfig = {
        active: function() { game.time.events.add(10, showLogoText, this); },
        google: {
            families: ['Fontdiner Swanky']
        }
    };

    var player;
    var map;
    var layer;
    var buttons;
    var doors = [];
    var monsters;
    var gameLevel = 0;
    var remainingMonsters;
    var healthbar;
    var scoreText;
    var LevelText;
    var logoText;
    var gameRunning;
    var lockCounter;

    var sound_intro;
    var sound_death;
    var sound_bomb;
    var sound_melee;
    var sound_bullet;
    var sound_monster_bullet;

    var door_locations = [ [270,158], [252,1025], [1875,986], [1683,197], [1080,765], [966,668], [1020,976] ];

    var game = new Phaser.Game('100', '100', Phaser.CANVAS, 'phaser-example', {
        preload: function() {
            game.load.image('bullet', 'assets/sprites/bullet.png');
            game.load.image('bullet_monster', 'assets/sprites/bullet_monster.png');
            game.load.image('door', 'assets/sprites/door.png');
            game.load.spritesheet('player', 'assets/sprites/player.png', 42, 48);
            game.load.spritesheet('skel', 'assets/sprites/monster_skel.png', 42, 48);
            game.load.spritesheet('frank', 'assets/sprites/monster_frank.png', 39, 48);
            game.load.spritesheet('bomb', 'assets/sprites/monster_bomb.png', 36, 48);

            game.load.tilemap('map', 'assets/map1.csv', null, Phaser.Tilemap.CSV);
            game.load.image('tiles', 'assets/tiles.png');
            game.load.script('webfont', '//ajax.googleapis.com/ajax/libs/webfont/1.4.7/webfont.js');

            game.load.audio('bomb', 'assets/sfx/bomb.wav');
            game.load.audio('bullet', 'assets/sfx/bullet.wav');
            game.load.audio('melee', 'assets/sfx/melee.wav');
            game.load.audio('monster_bullet', 'assets/sfx/monster_bullet.wav');
            game.load.audio('intro', 'assets/sfx/intro.wav');
            game.load.audio('death', 'assets/sfx/death.wav');
        },

        create: function() {
            map = game.add.tilemap('map', 64, 64);
            map.addTilesetImage('tiles');
            layer = map.createLayer(0);
            layer.resizeWorld();
            map.setCollisionBetween(0, 11);
            map.setCollisionBetween(16, 24);

            monsters = game.add.group();

            sound_intro = game.add.audio('intro');
            sound_bomb = game.add.audio('bomb');
            sound_bullet = game.add.audio('bullet');
            sound_melee = game.add.audio('melee');
            sound_monster_bullet = game.add.audio('monster_bullet');
            sound_death = game.add.audio('death');

            buttons = {
                up: this.input.keyboard.addKey(Phaser.KeyCode.W),
                down: this.input.keyboard.addKey(Phaser.KeyCode.S),
                left: this.input.keyboard.addKey(Phaser.KeyCode.A),
                right: this.input.keyboard.addKey(Phaser.KeyCode.D)
            };

            healthbar = game.add.graphics();
            healthbar.fixedToCamera = true;

            levelText = game.add.text(game.camera.x + (game.width/2), game.camera.y + (game.height/2), "Level 1", { font: "bold 60px Arial", fill: "#fff", boundsAlignH: "center", boundsAlignV: "middle" });
            levelText.setShadow(3, 3, 'rgba(0,0,0,0.5)', 2);
            levelText.setTextBounds(0, 0, 0, 0);
            levelText.fixedToCamera = true;
            levelText.visible = false;
            scoreText = game.add.text(116, 120, "", { font: "bold 24px Arial", fill: "#fff", boundsAlignH: "center", boundsAlignV: "middle" });
            scoreText.setShadow(3, 3, 'rgba(0,0,0,0.5)', 2);
            scoreText.setTextBounds(0, 0, 0, 0);
            scoreText.fixedToCamera = true;

            gameRunning = false;
            lockCounter = 40;
        },

        update: function() {
            if (!gameRunning) {
                lockCounter -= 1;
                if (game.input.activePointer.isDown && lockCounter <= 0) {
                    gameRunning = true;
                    reset();
                }
                return;
            }
            update_healthbar();
            player.weapon.fireAngle = Phaser.Math.radToDeg(game.physics.arcade.angleToPointer(player));

            game.physics.arcade.collide(player, layer);
            game.physics.arcade.collide(monsters, monsters);
            game.physics.arcade.collide(player.weapon.bullets, layer, function(bullet, wall) { bullet.kill(); });
            game.physics.arcade.collide(player.weapon.bullets, monsters, function(bullet, monster) {
                bullet.kill();
                monster.hp -= player.firePower;
                player.score += 10;
            });
            game.physics.arcade.collide(monsters, layer, function(monster, layer) {
                monster.reel = 35;
                game.physics.arcade.moveToXY(monster, game.rnd.integerInRange(0, game.world.width), game.rnd.integerInRange(0, game.world.height), monster.speed);
            });
            game.physics.arcade.collide(player, monsters, function(player, monster) {
                if (monster.type == 'bomb') {
                    player.hp -= 33;
                    monster.hp = 0;
                } else {
                    player.hp -= 2;
                    game.camera.shake(0.005, 20);
                    if (!sound_melee.isPlaying)
                        sound_melee.play();
                }
            });

            if (player.hp <= 0) {
                player.kill();
                sound_death.play();
                gameRunning = false;
                lockCounter = 100;
                logoText.visible = true;
                sound_intro.play();
                monsters.forEach(function(m) {
                    m.visible = false;
                    m.destroy();
                });
                remainingMonsters = 0;
                return;
            }

            if (remainingMonsters <=0) {
                nextLevel();
            };

            player.body.velocity.setTo(0, 0);
            if (buttons.up.isDown) {
                player.body.velocity.y = -player.speed;
            } else if (buttons.down.isDown) {
                player.body.velocity.y = player.speed;
            }
            if (buttons.left.isDown) {
                player.body.velocity.x = -player.speed;
            } else if (buttons.right.isDown) {
                player.body.velocity.x = player.speed;
            }
            if (game.input.activePointer.isDown) {
                player.weapon.fire();
            }
            player.animations.play((player.body.velocity.x != 0 || player.body.velocity.y != 0 ? 'walk_' : 'idle_') +getDirection(player.weapon.fireAngle), 8, true);
            monsters.forEach(function(monster) {
                if (monster.hp <= 0) {
                    monster.kill();
                    sound_death.play();
                    monsters.remove(monster);
                    remainingMonsters -= 1;
                    if (monster.type == 'frank') {
                        player.score += 20;
                    } else if (monster.type == 'bomb')  {
                        player.score += 30;
                        game.camera.shake(0.05, 400);
                        sound_bomb.play();
                    } else {
                        player.score += 40;
                    }
                }
                // AI
                angle = Phaser.Math.radToDeg(game.physics.arcade.angleBetween(monster, player));
                if (monster.reel<=0) {
                    game.physics.arcade.moveToObject(monster, player, monster.speed);
                } else {
                    monster.reel -= 1;
                }
                if (monster.type == 'skel') {
                    monster.weapon.fireAngle = angle;
                    monster.weapon.fire();
                    game.physics.arcade.collide(player, monster.weapon.bullets, function(player, bullet) {
                        bullet.kill();
                        game.camera.shake(0.01, 50);
                        player.hp -= 20;
                        if (!sound_melee.isPlaying)
                            sound_melee.play();
                    });
                }
                monster.animations.play('walk_'+getDirection(angle), 5, true);
            })
            scoreText.setText('Score: ' + player.score + '\nLevel: ' + gameLevel + '\nHorde: ' + remainingMonsters);
            scoreText.bringToTop();
        },
        render: function() {
            //game.debug.cameraInfo(game.camera, 32, 32);
        }
    });

    function create_door() {
        if (doors.length >= door_locations.length)
            return;
        var door = game.add.sprite(door_locations[doors.length][0], door_locations[doors.length][1], 'door');
        door.anchor.set(0.5);
        doors.push(door);
    }

    function nextLevel() {
        gameLevel += 1;
        if (gameLevel == 1 || gameLevel > 2 && gameLevel % 2 == 0) {
            create_door();
        }
        player.hp += 15;
        if (player.hp > 100)
            player.hp = 100;
        showLevelText();
        remainingMonsters = gameLevel*3;
        for (var i=0;i<remainingMonsters; i++) {
            game.time.events.add(Phaser.Timer.SECOND * (i+1)*game.rnd.integerInRange(1, 2)+1, generate_monster, game);
        }
    }

    function generate_monster() {
        roll = game.rnd.integerInRange(1,10);
        var door = doors[game.rnd.integerInRange(0,doors.length-1)];
        if (roll < 5) {
            var monster = game.add.sprite(door.x, door.y, 'frank');
            monster.animations.add('walk_down', [1,2]);
            monster.animations.add('walk_up', [3,4]);
            monster.animations.add('walk_left', [7,8]);
            monster.animations.add('walk_right', [5,6]);
            monster.hp = 15;
            monster.speed = 180;
            monster.type = 'frank';
        } else if (roll >= 5 && roll <= 7) {
            var monster = game.add.sprite(door.x, door.y, 'skel');
            monster.animations.add('walk_down', [1,2]);
            monster.animations.add('walk_up', [4,5]);
            monster.animations.add('walk_left', [8,9]);
            monster.animations.add('walk_right', [6,7]);
            monster.hp = 36;
            monster.speed = 70;
            monster.type = 'skel';

            monster.weapon = game.add.weapon(2, 'bullet_monster');
            monster.weapon.bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS;
            monster.weapon.bulletSpeed = 350;
            monster.weapon.fireRate = 600;
            monster.weapon.bulletAngleVariance = 8;
            monster.weapon.trackSprite(monster);
            monster.weapon.onFire.add(function(bullet, owner) { sound_monster_bullet.play() });
        } else {
            var monster = game.add.sprite(door.x, door.y, 'bomb');
            monster.animations.add('walk_down', [1,2]);
            monster.animations.add('walk_up', [1,2]);
            monster.animations.add('walk_left', [7,9]);
            monster.animations.add('walk_right', [6,8]);
            monster.hp = 5;
            monster.speed = 300;
            monster.type = 'bomb';
        }
        monster.reel = 0;
        game.physics.arcade.enable(monster);
        monster.anchor.set(0.5);
        monster.body.collideWorldBounds = true;
        monsters.add(monster);
    }

    function update_healthbar() {
        healthbar.clear()
        healthbar.beginFill(0x000000, 0.2);
        healthbar.drawRect(60, 30, 250, 30);
        healthbar.beginFill((player.hp <= 20 ? 0xaa0000 : 0x505099), 1);
        healthbar.drawRect(60, 30, player.hp>0 ? (250*player.hp)/100 : 0, 30);
    }

    function showLevelText() {
        levelText.setText('Level ' + gameLevel);
        levelText.visible = true;
        game.time.events.add(Phaser.Timer.SECOND * 2, hideLevelText, game);
        levelText.bringToTop();
    }

    function hideLevelText() {
        levelText.visible = false;
    }

    function getDirection(vangle) {
        angle = parseInt(vangle);
        if (angle < 45 && angle >- 45) {
            return 'right';
        } else if (angle < -45 && angle > -135) {
            return 'up';
        } else if (angle > -135 && angle < 135) {
            return 'down';
        }
        return 'left';
    }

    function showLogoText() {
        logoText = game.add.text(game.camera.x + (game.width/2), game.camera.y + (game.height/2), "AH NÃO!\nMAIS MONSTROS?");
        logoText.anchor.setTo(0.5);
        logoText.font = 'Fontdiner Swanky';
        logoText.fontSize = 60;
        logoText.padding.set(10, 16);
        logoText.fixedToCamera = true;

        grd = logoText.context.createLinearGradient(0, 0, 0, logoText.canvas.height);
        grd.addColorStop(0, '#004CB3');
        grd.addColorStop(1, '#8ED6FF');
        logoText.fill = grd;

        logoText.align = 'center';
        logoText.stroke = '#000000';
        logoText.strokeThickness = 2;
        logoText.setShadow(5, 5, 'rgba(0,0,0,0.5)', 5);
        sound_intro.play();
    }

    function reset() {
        logoText.visible = false;
        gameLevel = 0;
        for (var i=0;i<doors.length;i++)
            doors[i].destroy();
        doors = []
        monsters.forEach(function(monster) {
            monster.destroy();
        });
        player = game.add.sprite(600, 360, 'player');
        player.animations.add('idle_up', [7]);
        player.animations.add('idle_down', [0]);
        player.animations.add('idle_left', [4]);
        player.animations.add('idle_right', [2]);
        player.animations.add('walk_up', [7,8]);
        player.animations.add('walk_down', [9,10]);
        player.animations.add('walk_left', [5,6]);
        player.animations.add('walk_right', [2,3]);
        game.physics.arcade.enable(player);
        player.anchor.set(0.5);
        player.body.collideWorldBounds = true;
        player.weapon = game.add.weapon(20, 'bullet');
        player.weapon.bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS;
        player.weapon.trackSprite(player);
        player.weapon.onFire.add(function(bullet, owner) { sound_bullet.play() });

        game.camera.follow(player, Phaser.Camera.FOLLOW_LOCKON, 0.1, 0.1);

        player.hp = 100;
        player.speed = 250;
        player.score = 0;
        player.firePower = 3;
        player.weapon.bulletSpeed = 500;
        player.weapon.fireRate = 300;
        player.weapon.bulletAngleVariance = 6;

        remainingMonsters = 0;
        player.bringToTop();
        nextLevel();
    }

};
<commit_msg>destroy bug fixed<commit_after>window.onload = function() {

    WebFontConfig = {
        active: function() { game.time.events.add(10, showLogoText, this); },
        google: {
            families: ['Fontdiner Swanky']
        }
    };

    var player;
    var map;
    var layer;
    var buttons;
    var doors = [];
    var monsters;
    var gameLevel = 0;
    var remainingMonsters;
    var healthbar;
    var scoreText;
    var LevelText;
    var logoText;
    var gameRunning;
    var lockCounter;

    var sound_intro;
    var sound_death;
    var sound_bomb;
    var sound_melee;
    var sound_bullet;
    var sound_monster_bullet;

    var door_locations = [ [270,158], [252,1025], [1875,986], [1683,197], [1080,765], [966,668], [1020,976] ];

    var game = new Phaser.Game('100', '100', Phaser.CANVAS, 'phaser-example', {
        preload: function() {
            game.load.image('bullet', 'assets/sprites/bullet.png');
            game.load.image('bullet_monster', 'assets/sprites/bullet_monster.png');
            game.load.image('door', 'assets/sprites/door.png');
            game.load.spritesheet('player', 'assets/sprites/player.png', 42, 48);
            game.load.spritesheet('skel', 'assets/sprites/monster_skel.png', 42, 48);
            game.load.spritesheet('frank', 'assets/sprites/monster_frank.png', 39, 48);
            game.load.spritesheet('bomb', 'assets/sprites/monster_bomb.png', 36, 48);

            game.load.tilemap('map', 'assets/map1.csv', null, Phaser.Tilemap.CSV);
            game.load.image('tiles', 'assets/tiles.png');
            game.load.script('webfont', '//ajax.googleapis.com/ajax/libs/webfont/1.4.7/webfont.js');

            game.load.audio('bomb', 'assets/sfx/bomb.wav');
            game.load.audio('bullet', 'assets/sfx/bullet.wav');
            game.load.audio('melee', 'assets/sfx/melee.wav');
            game.load.audio('monster_bullet', 'assets/sfx/monster_bullet.wav');
            game.load.audio('intro', 'assets/sfx/intro.wav');
            game.load.audio('death', 'assets/sfx/death.wav');
        },

        create: function() {
            map = game.add.tilemap('map', 64, 64);
            map.addTilesetImage('tiles');
            layer = map.createLayer(0);
            layer.resizeWorld();
            map.setCollisionBetween(0, 11);
            map.setCollisionBetween(16, 24);

            monsters = game.add.group();

            sound_intro = game.add.audio('intro');
            sound_bomb = game.add.audio('bomb');
            sound_bullet = game.add.audio('bullet');
            sound_melee = game.add.audio('melee');
            sound_monster_bullet = game.add.audio('monster_bullet');
            sound_death = game.add.audio('death');

            buttons = {
                up: this.input.keyboard.addKey(Phaser.KeyCode.W),
                down: this.input.keyboard.addKey(Phaser.KeyCode.S),
                left: this.input.keyboard.addKey(Phaser.KeyCode.A),
                right: this.input.keyboard.addKey(Phaser.KeyCode.D)
            };

            healthbar = game.add.graphics();
            healthbar.fixedToCamera = true;

            levelText = game.add.text(game.camera.x + (game.width/2), game.camera.y + (game.height/2), "Level 1", { font: "bold 60px Arial", fill: "#fff", boundsAlignH: "center", boundsAlignV: "middle" });
            levelText.setShadow(3, 3, 'rgba(0,0,0,0.5)', 2);
            levelText.setTextBounds(0, 0, 0, 0);
            levelText.fixedToCamera = true;
            levelText.visible = false;
            scoreText = game.add.text(116, 120, "", { font: "bold 24px Arial", fill: "#fff", boundsAlignH: "center", boundsAlignV: "middle" });
            scoreText.setShadow(3, 3, 'rgba(0,0,0,0.5)', 2);
            scoreText.setTextBounds(0, 0, 0, 0);
            scoreText.fixedToCamera = true;

            gameRunning = false;
            lockCounter = 40;
        },

        update: function() {
            if (!gameRunning) {
                lockCounter -= 1;
                if (game.input.activePointer.isDown && lockCounter <= 0) {
                    gameRunning = true;
                    reset();
                }
                return;
            }
            update_healthbar();
            player.weapon.fireAngle = Phaser.Math.radToDeg(game.physics.arcade.angleToPointer(player));

            game.physics.arcade.collide(player, layer);
            game.physics.arcade.collide(monsters, monsters);
            game.physics.arcade.collide(player.weapon.bullets, layer, function(bullet, wall) { bullet.kill(); });
            game.physics.arcade.collide(player.weapon.bullets, monsters, function(bullet, monster) {
                bullet.kill();
                monster.hp -= player.firePower;
                player.score += 10;
            });
            game.physics.arcade.collide(monsters, layer, function(monster, layer) {
                monster.reel = 35;
                game.physics.arcade.moveToXY(monster, game.rnd.integerInRange(0, game.world.width), game.rnd.integerInRange(0, game.world.height), monster.speed);
            });
            game.physics.arcade.collide(player, monsters, function(player, monster) {
                if (monster.type == 'bomb') {
                    player.hp -= 33;
                    monster.hp = 0;
                } else {
                    player.hp -= 2;
                    game.camera.shake(0.005, 20);
                    if (!sound_melee.isPlaying)
                        sound_melee.play();
                }
            });

            if (player.hp <= 0) {
                player.kill();
                sound_death.play();
                gameRunning = false;
                lockCounter = 100;
                logoText.visible = true;
                sound_intro.play();
                monsters.destroy(true, true);
                remainingMonsters = 0;
                return;
            }

            if (remainingMonsters <=0) {
                nextLevel();
            };

            player.body.velocity.setTo(0, 0);
            if (buttons.up.isDown) {
                player.body.velocity.y = -player.speed;
            } else if (buttons.down.isDown) {
                player.body.velocity.y = player.speed;
            }
            if (buttons.left.isDown) {
                player.body.velocity.x = -player.speed;
            } else if (buttons.right.isDown) {
                player.body.velocity.x = player.speed;
            }
            if (game.input.activePointer.isDown) {
                player.weapon.fire();
            }
            player.animations.play((player.body.velocity.x != 0 || player.body.velocity.y != 0 ? 'walk_' : 'idle_') +getDirection(player.weapon.fireAngle), 8, true);
            monsters.forEach(function(monster) {
                if (monster.hp <= 0) {
                    monster.kill();
                    sound_death.play();
                    monsters.remove(monster);
                    remainingMonsters -= 1;
                    if (monster.type == 'frank') {
                        player.score += 20;
                    } else if (monster.type == 'bomb')  {
                        player.score += 30;
                        game.camera.shake(0.05, 400);
                        sound_bomb.play();
                    } else {
                        player.score += 40;
                    }
                }
                // AI
                angle = Phaser.Math.radToDeg(game.physics.arcade.angleBetween(monster, player));
                if (monster.reel<=0) {
                    game.physics.arcade.moveToObject(monster, player, monster.speed);
                } else {
                    monster.reel -= 1;
                }
                if (monster.type == 'skel') {
                    monster.weapon.fireAngle = angle;
                    monster.weapon.fire();
                    game.physics.arcade.collide(player, monster.weapon.bullets, function(player, bullet) {
                        bullet.kill();
                        game.camera.shake(0.01, 50);
                        player.hp -= 20;
                        if (!sound_melee.isPlaying)
                            sound_melee.play();
                    });
                }
                monster.animations.play('walk_'+getDirection(angle), 5, true);
            })
            scoreText.setText('Score: ' + player.score + '\nLevel: ' + gameLevel + '\nHorde: ' + remainingMonsters);
            scoreText.bringToTop();
        },
        render: function() {
            //game.debug.cameraInfo(game.camera, 32, 32);
        }
    });

    function create_door() {
        if (doors.length >= door_locations.length)
            return;
        var door = game.add.sprite(door_locations[doors.length][0], door_locations[doors.length][1], 'door');
        door.anchor.set(0.5);
        doors.push(door);
    }

    function nextLevel() {
        gameLevel += 1;
        if (gameLevel == 1 || gameLevel > 2 && gameLevel % 2 == 0) {
            create_door();
        }
        player.hp += 15;
        if (player.hp > 100)
            player.hp = 100;
        showLevelText();
        remainingMonsters = gameLevel*3;
        for (var i=0;i<remainingMonsters; i++) {
            game.time.events.add(Phaser.Timer.SECOND * (i+1)*game.rnd.integerInRange(1, 2)+1, generate_monster, game);
        }
    }

    function generate_monster() {
        roll = game.rnd.integerInRange(1,10);
        var door = doors[game.rnd.integerInRange(0,doors.length-1)];
        if (roll < 5) {
            var monster = game.add.sprite(door.x, door.y, 'frank');
            monster.animations.add('walk_down', [1,2]);
            monster.animations.add('walk_up', [3,4]);
            monster.animations.add('walk_left', [7,8]);
            monster.animations.add('walk_right', [5,6]);
            monster.hp = 15;
            monster.speed = 180;
            monster.type = 'frank';
        } else if (roll >= 5 && roll <= 7) {
            var monster = game.add.sprite(door.x, door.y, 'skel');
            monster.animations.add('walk_down', [1,2]);
            monster.animations.add('walk_up', [4,5]);
            monster.animations.add('walk_left', [8,9]);
            monster.animations.add('walk_right', [6,7]);
            monster.hp = 36;
            monster.speed = 70;
            monster.type = 'skel';

            monster.weapon = game.add.weapon(2, 'bullet_monster');
            monster.weapon.bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS;
            monster.weapon.bulletSpeed = 350;
            monster.weapon.fireRate = 600;
            monster.weapon.bulletAngleVariance = 8;
            monster.weapon.trackSprite(monster);
            monster.weapon.onFire.add(function(bullet, owner) { sound_monster_bullet.play() });
        } else {
            var monster = game.add.sprite(door.x, door.y, 'bomb');
            monster.animations.add('walk_down', [1,2]);
            monster.animations.add('walk_up', [1,2]);
            monster.animations.add('walk_left', [7,9]);
            monster.animations.add('walk_right', [6,8]);
            monster.hp = 5;
            monster.speed = 300;
            monster.type = 'bomb';
        }
        monster.reel = 0;
        game.physics.arcade.enable(monster);
        monster.anchor.set(0.5);
        monster.body.collideWorldBounds = true;
        monsters.add(monster);
    }

    function update_healthbar() {
        healthbar.clear()
        healthbar.beginFill(0x000000, 0.2);
        healthbar.drawRect(60, 30, 250, 30);
        healthbar.beginFill((player.hp <= 20 ? 0xaa0000 : 0x505099), 1);
        healthbar.drawRect(60, 30, player.hp>0 ? (250*player.hp)/100 : 0, 30);
    }

    function showLevelText() {
        levelText.setText('Level ' + gameLevel);
        levelText.visible = true;
        game.time.events.add(Phaser.Timer.SECOND * 2, hideLevelText, game);
        levelText.bringToTop();
    }

    function hideLevelText() {
        levelText.visible = false;
    }

    function getDirection(vangle) {
        angle = parseInt(vangle);
        if (angle < 45 && angle >- 45) {
            return 'right';
        } else if (angle < -45 && angle > -135) {
            return 'up';
        } else if (angle > -135 && angle < 135) {
            return 'down';
        }
        return 'left';
    }

    function showLogoText() {
        logoText = game.add.text(game.camera.x + (game.width/2), game.camera.y + (game.height/2), "AH NÃO!\nMAIS MONSTROS?");
        logoText.anchor.setTo(0.5);
        logoText.font = 'Fontdiner Swanky';
        logoText.fontSize = 60;
        logoText.padding.set(10, 16);
        logoText.fixedToCamera = true;

        grd = logoText.context.createLinearGradient(0, 0, 0, logoText.canvas.height);
        grd.addColorStop(0, '#004CB3');
        grd.addColorStop(1, '#8ED6FF');
        logoText.fill = grd;

        logoText.align = 'center';
        logoText.stroke = '#000000';
        logoText.strokeThickness = 2;
        logoText.setShadow(5, 5, 'rgba(0,0,0,0.5)', 5);
        sound_intro.play();
    }

    function reset() {
        logoText.visible = false;
        gameLevel = 0;
        for (var i=0;i<doors.length;i++)
            doors[i].destroy();
        doors = []
        monsters.forEach(function(monster) {
            monster.destroy();
        });
        player = game.add.sprite(600, 360, 'player');
        player.animations.add('idle_up', [7]);
        player.animations.add('idle_down', [0]);
        player.animations.add('idle_left', [4]);
        player.animations.add('idle_right', [2]);
        player.animations.add('walk_up', [7,8]);
        player.animations.add('walk_down', [9,10]);
        player.animations.add('walk_left', [5,6]);
        player.animations.add('walk_right', [2,3]);
        game.physics.arcade.enable(player);
        player.anchor.set(0.5);
        player.body.collideWorldBounds = true;
        player.weapon = game.add.weapon(20, 'bullet');
        player.weapon.bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS;
        player.weapon.trackSprite(player);
        player.weapon.onFire.add(function(bullet, owner) { sound_bullet.play() });

        game.camera.follow(player, Phaser.Camera.FOLLOW_LOCKON, 0.1, 0.1);

        player.hp = 100;
        player.speed = 250;
        player.score = 0;
        player.firePower = 3;
        player.weapon.bulletSpeed = 500;
        player.weapon.fireRate = 300;
        player.weapon.bulletAngleVariance = 6;

        remainingMonsters = 0;
        player.bringToTop();
        nextLevel();
    }

};
<|endoftext|>


<commit_before>(function() {
	/**
	 * Load the list of files asynchronously. This uses recursion in
	 * order to create a queue of files that will be loaded serially.
	 * Each layer, starting at the bottom, loads a file and then loads
	 * the layer on top of it. The very top file on the stack will have
	 * zero files to load, so instead it will be the one to call the
	 * callback to notify the caller that all the content is loaded.
	 *
	 * @param {Object} context function to call this method in the context of
	 * @param {Array.<string>} paths array of strings containing relative paths for required locale data files
	 * @param {Array} results empty array in which to place the resulting json when it is loaded from a file
	 * @param {Object} params An object full of parameters that the caller is passing to this function to help load the files
	 * @param {function(Array.<Object>)} callback callback to call when this function is finished attempting
	 * to load all the files that exist and can be loaded
	 */
	function loadFiles(context, paths, results, params, callback) {
		var root = "resources/";
		if (params && typeof(params.root) !== "undefined") {
			root = params.root + '/';
		}
		if (paths.length > 0) {
			var path = paths.shift();
			var ajax = new enyo.Ajax({url: enyo.path.rewrite("$lib/enyo-ilib/ilib/locale/" + path)});
			//console.log("moondemo2: browser/async: attempting to load lib/enyo-ilib/ilib/locale/" + path);
			var resultFunc = function(inSender, json) {
                // console.log("moondemo2: " + (!inSender.failed && json ? "success" : "failed"));
				results.push(!inSender.failed && (typeof(json) === 'object') ? json : undefined);
				if (paths.length > 0) {
					loadFiles(context, paths, results, params, callback);
				} else {
					// only the bottom item on the stack will call
					// the callback
					callback.call(context, results);
				}
			};
			ajax.response(this, resultFunc);
			ajax.error(this, function(inSender, json) {
				//console.log("moondemo2: browser/async: attempting to load resources/" + path);
				// not there? Try the standard place instead
				var file = root + path;
				var ajax2 = new enyo.Ajax({url: file});

				ajax2.response(this, resultFunc);
				ajax2.error(this, resultFunc);
				ajax2.go();
			});
			ajax.go();
		}
	}

	ilib.setLoaderCallback(enyo.bind(this, function(paths, sync, params, callback) {
		if (sync) {
			var ret = [];
			var root = "resources/";
			if (params && typeof(params.root) !== "undefined") {
				root = params.root + '/';
			}
			// synchronous
			paths.forEach(function (path) {
				// console.log("browser/sync: attempting to load lib/enyo-ilib/ilib/locale/" + path);
				var ajax = new enyo.Ajax({
					url: enyo.path.rewrite("$lib/enyo-ilib/ilib/locale/" + path),
					sync: true
				});

				var handler = function(inSender, json) {
                    // console.log((!inSender.failed && json ? "success" : "failed"));
					ret.push(!inSender.failed && (typeof(json) === 'object') ? json : undefined);
				};
				ajax.response(this, handler);
				ajax.error(this, function(inSender, json) {
					// console.log("browser/sync: Now attempting to load resources/" + path);
					var ajax2 = new enyo.Ajax({
						url: root + path,
						sync: true
					});
					ajax2.response(this, handler);
					ajax2.error(this, handler);
					ajax2.go();
				});
				ajax.go();
			});

			if (typeof(callback) === 'function') {
				callback.call(this, ret);
			}
			return ret;
		}

		// asynchronous
		var results = [];
		loadFiles(this, paths, results, params, callback);
	}));

	if (typeof(window.UILocale) !== 'undefined') {
		// this is a hack until GF-1581 is fixed
		ilib.setLocale(window.UILocale);
	}

	// enyo.updateI18NClasses should be called after every setLocale, but there isn't such a callback in current version
    enyo.updateI18NClasses = function updateBodyClasses() {
        var li = new ilib.LocaleInfo(); // for the current locale
        var locale = li.getLocale();
		var base = "enyo-locale-";

        // Remove old style definitions (hack style becouse enyo.dom doesn't have methods like enyo.dom.getBodyClasses, enyo.dom.removeBodyClass)
        if (document && document.body && document.body.className && document.body.className) {
            document.body.className = document.body.className.replace(new RegExp('(^|\\s)'+ base +'[^\\s]*', 'g'), '');
        }

		if (li.getScript() !== "Latn" || locale.getLanguage() === "vi") {
			// allow enyo to define other fonts for non-Latin languages, or Vietnamese which
			// is Latin-based, but the characters with multiple accents don't appear in the
			// regular fonts, creating a strange "ransom note" look with a mix of fonts in the
			// same word. So, treat it like a non-Latin language in order to get all the characters
			// to display with the same font.
			enyo.dom.addBodyClass(base + "non-latin");
		}

		// allow enyo to apply right-to-left styles to the app and widgets if necessary
		var script = new ilib.ScriptInfo(li.getScript());
		if (script.getScriptDirection() === "rtl") {
			enyo.dom.addBodyClass(base + "right-to-left");
			if (enyo.Control) {
				enyo.Control.prototype.rtl = true;
			}
		}

		// allow enyo or the apps to give CSS classes that are specific to the language, country, or script
		if (locale.getLanguage()) {
			enyo.dom.addBodyClass(base + locale.getLanguage());
			if (locale.getScript()) {
				enyo.dom.addBodyClass(base + locale.getLanguage() + "-" + locale.getScript());
				if (locale.getRegion()) {
					enyo.dom.addBodyClass(base + locale.getLanguage() + "-" + locale.getScript() + "-" + locale.getRegion());
				}
			} else if (locale.getRegion()) {
				enyo.dom.addBodyClass(base + locale.getLanguage() + "-" + locale.getRegion());
			}
		}
		if (locale.getScript()) {
			enyo.dom.addBodyClass(base + locale.getScript());
		}
		if (locale.getRegion()) {
			enyo.dom.addBodyClass(base + locale.getRegion());
		}
    };
})();

/*
 * Reset the $L function to use ilib instead of the dummy function that enyo
 * comes with by default.
 */
$L = function (string) {
	var str;
	if (!$L.rb) {
		$L.setLocale();
	}
	if (typeof(string) === 'string') {
		if (!$L.rb) {
			return string;
		}
		str = $L.rb.getString(string);
	} else if (typeof(string) === 'object') {
		if (typeof(string.key) !== 'undefined' && typeof(string.value) !== 'undefined') {
			if (!$L.rb) {
				return string.value;
			}
			str = $L.rb.getString(string.value, string.key);
		} else {
			str = "";
		}
	} else {
		str = string;
	}
	return str.toString();
};

/**
 * Set the locale for the strings that $L loads. This may reload the
 * string resources if necessary.
 * @param {string} spec the locale specifier
 */
$L.setLocale = function (spec) {
	var locale = new ilib.Locale(spec);
	if (!$L.rb || spec !== $L.rb.getLocale().getSpec()) {
		$L.rb = new ilib.ResBundle({
			locale: locale,
			type: "html",
			name: "strings",
			sync: true,
			missing: locale.getLanguage() === "en" ? "source" : "pseudo",
			lengthen: true		// if pseudo-localizing, this tells it to lengthen strings
		});
	}
};

/**
 * This Enyo hook lets us know that the system locale has changed and gives
 * us a chance to update the iLib locale before Enyo broadcasts its
 * `onlocalechange` signal.
 */
enyo.updateLocale = function() {
	ilib.setLocale(navigator.language);
	$L.setLocale(navigator.language);
	enyo.updateI18NClasses();
};

<commit_msg>Fixed up the debug messages<commit_after>(function() {
	/**
	 * Load the list of files asynchronously. This uses recursion in
	 * order to create a queue of files that will be loaded serially.
	 * Each layer, starting at the bottom, loads a file and then loads
	 * the layer on top of it. The very top file on the stack will have
	 * zero files to load, so instead it will be the one to call the
	 * callback to notify the caller that all the content is loaded.
	 *
	 * @param {Object} context function to call this method in the context of
	 * @param {Array.<string>} paths array of strings containing relative paths for required locale data files
	 * @param {Array} results empty array in which to place the resulting json when it is loaded from a file
	 * @param {Object} params An object full of parameters that the caller is passing to this function to help load the files
	 * @param {function(Array.<Object>)} callback callback to call when this function is finished attempting
	 * to load all the files that exist and can be loaded
	 */
	function loadFiles(context, paths, results, params, callback) {
		var root = "resources/";
		if (params && typeof(params.root) !== "undefined") {
			root = params.root + '/';
		}
		if (paths.length > 0) {
			var path = paths.shift();
			var ajax = new enyo.Ajax({url: enyo.path.rewrite("$lib/enyo-ilib/ilib/locale/" + path)});
			//console.log("moondemo2: browser/async: attempting to load lib/enyo-ilib/ilib/locale/" + path);
			var resultFunc = function(inSender, json) {
                // console.log("moondemo2: " + (!inSender.failed && json ? "success" : "failed"));
				results.push(!inSender.failed && (typeof(json) === 'object') ? json : undefined);
				if (paths.length > 0) {
					loadFiles(context, paths, results, params, callback);
				} else {
					// only the bottom item on the stack will call
					// the callback
					callback.call(context, results);
				}
			};
			ajax.response(this, resultFunc);
			ajax.error(this, function(inSender, json) {
				// not there? Try the standard place instead
				var file = root + path;
				// console.log("moondemo2: browser/async: attempting to load " + file);
				var ajax2 = new enyo.Ajax({url: file});

				ajax2.response(this, resultFunc);
				ajax2.error(this, resultFunc);
				ajax2.go();
			});
			ajax.go();
		}
	}

	ilib.setLoaderCallback(enyo.bind(this, function(paths, sync, params, callback) {
		if (sync) {
			var ret = [];
			var root = "resources/";
			if (params && typeof(params.root) !== "undefined") {
				root = params.root + '/';
			}
			// synchronous
			paths.forEach(function (path) {
				// console.log("browser/sync: attempting to load lib/enyo-ilib/ilib/locale/" + path);
				var ajax = new enyo.Ajax({
					url: enyo.path.rewrite("$lib/enyo-ilib/ilib/locale/" + path),
					sync: true
				});

				var handler = function(inSender, json) {
                    // console.log((!inSender.failed && json ? "success" : "failed"));
					ret.push(!inSender.failed && (typeof(json) === 'object') ? json : undefined);
				};
				ajax.response(this, handler);
				ajax.error(this, function(inSender, json) {
					// console.log("browser/sync: Now attempting to load " + root + path);
					var ajax2 = new enyo.Ajax({
						url: root + path,
						sync: true
					});
					ajax2.response(this, handler);
					ajax2.error(this, handler);
					ajax2.go();
				});
				ajax.go();
			});

			if (typeof(callback) === 'function') {
				callback.call(this, ret);
			}
			return ret;
		}

		// asynchronous
		var results = [];
		loadFiles(this, paths, results, params, callback);
	}));

	if (typeof(window.UILocale) !== 'undefined') {
		// this is a hack until GF-1581 is fixed
		ilib.setLocale(window.UILocale);
	}

	// enyo.updateI18NClasses should be called after every setLocale, but there isn't such a callback in current version
    enyo.updateI18NClasses = function updateBodyClasses() {
        var li = new ilib.LocaleInfo(); // for the current locale
        var locale = li.getLocale();
		var base = "enyo-locale-";

        // Remove old style definitions (hack style becouse enyo.dom doesn't have methods like enyo.dom.getBodyClasses, enyo.dom.removeBodyClass)
        if (document && document.body && document.body.className && document.body.className) {
            document.body.className = document.body.className.replace(new RegExp('(^|\\s)'+ base +'[^\\s]*', 'g'), '');
        }

		if (li.getScript() !== "Latn" || locale.getLanguage() === "vi") {
			// allow enyo to define other fonts for non-Latin languages, or Vietnamese which
			// is Latin-based, but the characters with multiple accents don't appear in the
			// regular fonts, creating a strange "ransom note" look with a mix of fonts in the
			// same word. So, treat it like a non-Latin language in order to get all the characters
			// to display with the same font.
			enyo.dom.addBodyClass(base + "non-latin");
		}

		// allow enyo to apply right-to-left styles to the app and widgets if necessary
		var script = new ilib.ScriptInfo(li.getScript());
		if (script.getScriptDirection() === "rtl") {
			enyo.dom.addBodyClass(base + "right-to-left");
			if (enyo.Control) {
				enyo.Control.prototype.rtl = true;
			}
		}

		// allow enyo or the apps to give CSS classes that are specific to the language, country, or script
		if (locale.getLanguage()) {
			enyo.dom.addBodyClass(base + locale.getLanguage());
			if (locale.getScript()) {
				enyo.dom.addBodyClass(base + locale.getLanguage() + "-" + locale.getScript());
				if (locale.getRegion()) {
					enyo.dom.addBodyClass(base + locale.getLanguage() + "-" + locale.getScript() + "-" + locale.getRegion());
				}
			} else if (locale.getRegion()) {
				enyo.dom.addBodyClass(base + locale.getLanguage() + "-" + locale.getRegion());
			}
		}
		if (locale.getScript()) {
			enyo.dom.addBodyClass(base + locale.getScript());
		}
		if (locale.getRegion()) {
			enyo.dom.addBodyClass(base + locale.getRegion());
		}
    };
})();

/*
 * Reset the $L function to use ilib instead of the dummy function that enyo
 * comes with by default.
 */
$L = function (string) {
	var str;
	if (!$L.rb) {
		$L.setLocale();
	}
	if (typeof(string) === 'string') {
		if (!$L.rb) {
			return string;
		}
		str = $L.rb.getString(string);
	} else if (typeof(string) === 'object') {
		if (typeof(string.key) !== 'undefined' && typeof(string.value) !== 'undefined') {
			if (!$L.rb) {
				return string.value;
			}
			str = $L.rb.getString(string.value, string.key);
		} else {
			str = "";
		}
	} else {
		str = string;
	}
	return str.toString();
};

/**
 * Set the locale for the strings that $L loads. This may reload the
 * string resources if necessary.
 * @param {string} spec the locale specifier
 */
$L.setLocale = function (spec) {
	var locale = new ilib.Locale(spec);
	if (!$L.rb || spec !== $L.rb.getLocale().getSpec()) {
		$L.rb = new ilib.ResBundle({
			locale: locale,
			type: "html",
			name: "strings",
			sync: true,
			missing: locale.getLanguage() === "en" ? "source" : "pseudo",
			lengthen: true		// if pseudo-localizing, this tells it to lengthen strings
		});
	}
};

/**
 * This Enyo hook lets us know that the system locale has changed and gives
 * us a chance to update the iLib locale before Enyo broadcasts its
 * `onlocalechange` signal.
 */
enyo.updateLocale = function() {
	ilib.setLocale(navigator.language);
	$L.setLocale(navigator.language);
	enyo.updateI18NClasses();
};

<|endoftext|>


<commit_before>module.exports = {
	maxAmount: 100000000,
	maxPayloadLength: 1024 * 1024,
	blockHeaderLength: 248,
	addressLength: 208,
	maxAddressesLength: 208 * 128,
	maxClientConnections: 100,
	numberLength: 100000000,
	feeStartVolume: 10000 * 100000000,
	feeStart: 1,
	fees:{
		send:10000000,
		vote:100000000,
		secondsignature:500000000,
		delegate:10000000000,
		multisignature:500000000,
		dapp:50000000000
	},
	rewards: {
		offset: 2021,      // Start rewards at block (n)
		distance: 3000000, // Distance between each milestone
	},
	maxRequests: 10000 * 12,
	requestLength: 104,
	signatureLength: 196,
	maxSignaturesLength: 196 * 256,
	maxConfirmations : 77 * 100,
	confirmationLength: 77,
	fixedPoint : Math.pow(10, 8),
	totalAmount: 10000000000000000,
	maxTxsPerBlock: 25
}
<commit_msg>Sorting alphabetically.<commit_after>module.exports = {
	addressLength: 208,
	blockHeaderLength: 248,
	confirmationLength: 77,
	fees:{
		send: 10000000,
		vote: 100000000,
		secondsignature: 500000000,
		delegate: 10000000000,
		multisignature: 500000000,
		dapp: 50000000000
	},
	feeStart: 1,
	feeStartVolume: 10000 * 100000000,
	fixedPoint : Math.pow(10, 8),
	maxAddressesLength: 208 * 128,
	maxAmount: 100000000,
	maxClientConnections: 100,
	maxConfirmations : 77 * 100,
	maxPayloadLength: 1024 * 1024,
	maxRequests: 10000 * 12,
	maxSignaturesLength: 196 * 256,
	maxTxsPerBlock: 25,
	numberLength: 100000000,
	requestLength: 104,
	rewards: {
		offset: 2021,      // Start rewards at block (n)
		distance: 3000000, // Distance between each milestone
	},
	signatureLength: 196,
	totalAmount: 10000000000000000
}
<|endoftext|>


<commit_before>(function() {
	/**
	 * Load the list of files asynchronously. This uses recursion in
	 * order to create a queue of files that will be loaded serially.
	 * Each layer, starting at the bottom, loads a file and then loads
	 * the layer on top of it. The very top file on the stack will have
	 * zero files to load, so instead it will be the one to call the
	 * callback to notify the caller that all the content is loaded.
	 *
	 * @param {Object} context function to call this method in the context of
	 * @param {Array.<string>} paths array of strings containing relative paths for required locale data files
	 * @param {Array} results empty array in which to place the resulting json when it is loaded from a file
	 * @param {Object} params An object full of parameters that the caller is passing to this function to help load the files
	 * @param {function(Array.<Object>)} callback callback to call when this function is finished attempting
	 * to load all the files that exist and can be loaded
	 */
	function loadFiles(context, paths, results, params, callback) {
		if (paths.length > 0) {
			var path = paths.shift();
			var ajax = new enyo.Ajax({url: enyo.path.rewrite("$lib/enyo-ilib/ilib/locale/" + path)});
			//console.log("moondemo2: browser/async: attempting to load lib/enyo-ilib/ilib/locale/" + path);
			var resultFunc = function(inSender, json) {
				//console.log("moondemo2: " + (json ? "success" : "failed"));
				results.push((typeof(json) === 'object') ? json : undefined);
				if (paths.length > 0) {
					loadFiles(context, paths, results, params, callback);
				} else {
					// only the bottom item on the stack will call
					// the callback
					callback.call(context, results);
				}
			};
			ajax.response(this, resultFunc);
			ajax.error(this, function(inSender, json) {
				//console.log("moondemo2: browser/async: attempting to load resources/" + path);
				// not there? Try the standard place instead
				var file = "resources/" + path;
				var ajax2 = new enyo.Ajax({url: file});

				ajax2.response(this, resultFunc);
				ajax2.error(this, resultFunc);
				ajax2.go();
			});
			ajax.go();
		}
	}

	ilib.setLoaderCallback(enyo.bind(this, function(paths, sync, params, callback) {
		if (sync) {
			var ret = [];
			// synchronous
			paths.forEach(function (path) {
				// console.log("browser/sync: attempting to load lib/enyo-ilib/ilib/locale/" + path);
				var ajax = new enyo.Ajax({
					url: enyo.path.rewrite("$lib/enyo-ilib/ilib/locale/" + path),
					sync: true
				});

				var handler = function(inSender, json) {
					// console.log((json ? "success" : "failed"));
					ret.push((typeof(json) === 'object') ? json : undefined);
				};
				ajax.response(this, handler);
				ajax.error(this, function(inSender, json) {
					// console.log("browser/sync: Now attempting to load resources/" + path);
					var ajax2 = new enyo.Ajax({
						url: "resources/" + path,
						sync: true
					});
					ajax2.response(this, handler);
					ajax2.error(this, handler);
					ajax2.go();
				});
				ajax.go();
			});

			if (typeof(callback) === 'function') {
				callback.call(this, ret);
			}
			return ret;
		}

		// asynchronous
		var results = [];
		loadFiles(this, paths, results, params, callback);
	}));

	if (typeof(window.UILocale) !== 'undefined') {
		// this is a hack until GF-1581 is fixed
		ilib.setLocale(window.UILocale);
	}

	// This is temporary special code for webOS to be able to test apps with a font that works
	// in other locales.
	var li = new ilib.LocaleInfo(); // for the current locale
	var locale = li.getLocale();
	enyo.ready(function () {
		var base = " enyo-locale-";
		if (li.getScript() !== "Latn" || locale.getLanguage() === "vi") {
			// allow enyo to define other fonts for non-Latin languages, or Vietnamese which
			// is Latin-based, but the characters with multiple accents don't appear in the
			// regular fonts, creating a strange "ransom note" look with a mix of fonts in the
			// same word. So, treat it like a non-Latin language in order to get all the characters
			// to display with the same font.
			enyo.dom.getFirstElementByTagName("body").className += base + "non-latin";
		}

		// allow enyo to apply right-to-left styles to the app and widgets if necessary
		var script = new ilib.ScriptInfo(li.getDefaultScript());
		if (script.getScriptDirection() === "rtl") {
			enyo.dom.getFirstElementByTagName("body").className += base + "right-to-left";
			if (enyo.Control) {
				enyo.Control.prototype.rtl = true;
			}
		}

		// allow enyo or the apps to give CSS classes that are specific to the language, country, or script
		if (locale.getLanguage()) {
			enyo.dom.getFirstElementByTagName("body").className += base + locale.getLanguage();
			if (locale.getScript()) {
				enyo.dom.getFirstElementByTagName("body").className += base + locale.getLanguage() + "-" + locale.getScript();
				if (locale.getRegion()) {
					enyo.dom.getFirstElementByTagName("body").className += base + locale.getLanguage() + "-" + locale.getScript() + "-" + locale.getRegion();
				}
			} else if (locale.getRegion()) {
				enyo.dom.getFirstElementByTagName("body").className += base + locale.getLanguage() + "-" + locale.getRegion();
			}
		}
		if (locale.getScript()) {
			enyo.dom.getFirstElementByTagName("body").className += base + locale.getScript();
		}
		if (locale.getRegion()) {
			enyo.dom.getFirstElementByTagName("body").className += base + locale.getRegion();
		}
	});
})();

/*
 * Reset the $L function to use ilib instead of the dummy function that enyo
 * comes with by default.
 */
$L = (function() {
	var lfunc = function (string) {
		if (!$L.rb) {
			return string;
		}
		var str = $L.rb.getString(string);
		return str.toString();
	};
	var locale = new ilib.Locale();
	lfunc.rb = new ilib.ResBundle({
		type: "html",
		name: "strings",
		missing: locale.getLanguage() === "en" ? "source" : "pseudo",
		sync: true,
		lengthen: true		// if pseudo-localizing, this tells it to lengthen strings
	});
	return lfunc;
})();

/**
 * Set the locale for the strings that $L loads. This may reload the
 * string resources if necessary.
 */
$L.setLocale = function (spec) {
	if (spec !== $L.rb.getLocale().getSpec()) {
		$L.rb = new ilib.ResBundle({
			locale: spec,
			type: "html",
			name: "strings",
			sync: true,
			missing: locale.getLanguage() === "en" ? "source" : "pseudo",
			lengthen: true		// if pseudo-localizing, this tells it to lengthen strings
		});
	}
};

/**
 * This Enyo hook lets us know that the system locale has changed and gives
 * us a chance to update the iLib locale before Enyo broadcasts its
 * `onlocalechange` signal.
 */
enyo.updateLocale = function() {
	ilib.setLocale(navigator.$language);
}

<commit_msg>Replacing face navigator.language variable used in testing with the real McCoy.<commit_after>(function() {
	/**
	 * Load the list of files asynchronously. This uses recursion in
	 * order to create a queue of files that will be loaded serially.
	 * Each layer, starting at the bottom, loads a file and then loads
	 * the layer on top of it. The very top file on the stack will have
	 * zero files to load, so instead it will be the one to call the
	 * callback to notify the caller that all the content is loaded.
	 *
	 * @param {Object} context function to call this method in the context of
	 * @param {Array.<string>} paths array of strings containing relative paths for required locale data files
	 * @param {Array} results empty array in which to place the resulting json when it is loaded from a file
	 * @param {Object} params An object full of parameters that the caller is passing to this function to help load the files
	 * @param {function(Array.<Object>)} callback callback to call when this function is finished attempting
	 * to load all the files that exist and can be loaded
	 */
	function loadFiles(context, paths, results, params, callback) {
		if (paths.length > 0) {
			var path = paths.shift();
			var ajax = new enyo.Ajax({url: enyo.path.rewrite("$lib/enyo-ilib/ilib/locale/" + path)});
			//console.log("moondemo2: browser/async: attempting to load lib/enyo-ilib/ilib/locale/" + path);
			var resultFunc = function(inSender, json) {
				//console.log("moondemo2: " + (json ? "success" : "failed"));
				results.push((typeof(json) === 'object') ? json : undefined);
				if (paths.length > 0) {
					loadFiles(context, paths, results, params, callback);
				} else {
					// only the bottom item on the stack will call
					// the callback
					callback.call(context, results);
				}
			};
			ajax.response(this, resultFunc);
			ajax.error(this, function(inSender, json) {
				//console.log("moondemo2: browser/async: attempting to load resources/" + path);
				// not there? Try the standard place instead
				var file = "resources/" + path;
				var ajax2 = new enyo.Ajax({url: file});

				ajax2.response(this, resultFunc);
				ajax2.error(this, resultFunc);
				ajax2.go();
			});
			ajax.go();
		}
	}

	ilib.setLoaderCallback(enyo.bind(this, function(paths, sync, params, callback) {
		if (sync) {
			var ret = [];
			// synchronous
			paths.forEach(function (path) {
				// console.log("browser/sync: attempting to load lib/enyo-ilib/ilib/locale/" + path);
				var ajax = new enyo.Ajax({
					url: enyo.path.rewrite("$lib/enyo-ilib/ilib/locale/" + path),
					sync: true
				});

				var handler = function(inSender, json) {
					// console.log((json ? "success" : "failed"));
					ret.push((typeof(json) === 'object') ? json : undefined);
				};
				ajax.response(this, handler);
				ajax.error(this, function(inSender, json) {
					// console.log("browser/sync: Now attempting to load resources/" + path);
					var ajax2 = new enyo.Ajax({
						url: "resources/" + path,
						sync: true
					});
					ajax2.response(this, handler);
					ajax2.error(this, handler);
					ajax2.go();
				});
				ajax.go();
			});

			if (typeof(callback) === 'function') {
				callback.call(this, ret);
			}
			return ret;
		}

		// asynchronous
		var results = [];
		loadFiles(this, paths, results, params, callback);
	}));

	if (typeof(window.UILocale) !== 'undefined') {
		// this is a hack until GF-1581 is fixed
		ilib.setLocale(window.UILocale);
	}

	// This is temporary special code for webOS to be able to test apps with a font that works
	// in other locales.
	var li = new ilib.LocaleInfo(); // for the current locale
	var locale = li.getLocale();
	enyo.ready(function () {
		var base = " enyo-locale-";
		if (li.getScript() !== "Latn" || locale.getLanguage() === "vi") {
			// allow enyo to define other fonts for non-Latin languages, or Vietnamese which
			// is Latin-based, but the characters with multiple accents don't appear in the
			// regular fonts, creating a strange "ransom note" look with a mix of fonts in the
			// same word. So, treat it like a non-Latin language in order to get all the characters
			// to display with the same font.
			enyo.dom.getFirstElementByTagName("body").className += base + "non-latin";
		}

		// allow enyo to apply right-to-left styles to the app and widgets if necessary
		var script = new ilib.ScriptInfo(li.getDefaultScript());
		if (script.getScriptDirection() === "rtl") {
			enyo.dom.getFirstElementByTagName("body").className += base + "right-to-left";
			if (enyo.Control) {
				enyo.Control.prototype.rtl = true;
			}
		}

		// allow enyo or the apps to give CSS classes that are specific to the language, country, or script
		if (locale.getLanguage()) {
			enyo.dom.getFirstElementByTagName("body").className += base + locale.getLanguage();
			if (locale.getScript()) {
				enyo.dom.getFirstElementByTagName("body").className += base + locale.getLanguage() + "-" + locale.getScript();
				if (locale.getRegion()) {
					enyo.dom.getFirstElementByTagName("body").className += base + locale.getLanguage() + "-" + locale.getScript() + "-" + locale.getRegion();
				}
			} else if (locale.getRegion()) {
				enyo.dom.getFirstElementByTagName("body").className += base + locale.getLanguage() + "-" + locale.getRegion();
			}
		}
		if (locale.getScript()) {
			enyo.dom.getFirstElementByTagName("body").className += base + locale.getScript();
		}
		if (locale.getRegion()) {
			enyo.dom.getFirstElementByTagName("body").className += base + locale.getRegion();
		}
	});
})();

/*
 * Reset the $L function to use ilib instead of the dummy function that enyo
 * comes with by default.
 */
$L = (function() {
	var lfunc = function (string) {
		if (!$L.rb) {
			return string;
		}
		var str = $L.rb.getString(string);
		return str.toString();
	};
	var locale = new ilib.Locale();
	lfunc.rb = new ilib.ResBundle({
		type: "html",
		name: "strings",
		missing: locale.getLanguage() === "en" ? "source" : "pseudo",
		sync: true,
		lengthen: true		// if pseudo-localizing, this tells it to lengthen strings
	});
	return lfunc;
})();

/**
 * Set the locale for the strings that $L loads. This may reload the
 * string resources if necessary.
 */
$L.setLocale = function (spec) {
	if (spec !== $L.rb.getLocale().getSpec()) {
		$L.rb = new ilib.ResBundle({
			locale: spec,
			type: "html",
			name: "strings",
			sync: true,
			missing: locale.getLanguage() === "en" ? "source" : "pseudo",
			lengthen: true		// if pseudo-localizing, this tells it to lengthen strings
		});
	}
};

/**
 * This Enyo hook lets us know that the system locale has changed and gives
 * us a chance to update the iLib locale before Enyo broadcasts its
 * `onlocalechange` signal.
 */
enyo.updateLocale = function() {
	ilib.setLocale(navigator.language);
}

<|endoftext|>


<commit_before>const ping = require('ping');
const BroadlinkJS = require('broadlinkjs-rm');
const broadlink = new BroadlinkJS()

const pingFrequency = 1000;

const startPing = (host) => {
  setInterval(() => {
    ping.sys.probe(host)
  }, pingFrequency);
}

const discoveredDevices = {};

let discovering = false;

const discoverDevices = (count = 0) => {
  discovering = true;

  if (count >= 5) {
    discovering = false;

    return;
  }

  broadlink.discover();
  count++;

  setTimeout(() => {
    discoverDevices(count);
  }, 5 * 1000)
}

discoverDevices();

broadlink.on('deviceReady', (device) => {
  const macAddressParts = device.mac.toString('hex').match(/[\s\S]{1,2}/g) || []
  const macAddress = macAddressParts.join(':')
  device.host.macAddress = macAddress

  if (discoveredDevices[device.host.address] || discoveredDevices[device.host.macAddress]) return;

  console.log(`Discovered Broadlink RM device at ${device.host.address} (${device.host.macAddress})`)

  discoveredDevices[device.host.address] = device;
  discoveredDevices[device.host.macAddress] = device;

  startPing(device.host.address)
})

const getDevice = ({ host, log, learnOnly }) => {
  let device;

  if (host) {
    device = discoveredDevices[host];
  } else { // use the first one of no host is provided
    const hosts = Object.keys(discoveredDevices);
    if (hosts.length === 0) {
      log(`Send data (no devices found)`);
      if (!discovering) {
        log(`Attempting to discover RM devices for 5s`);

        discoverDevices()
      }

      return
    }

    // Only return device that can Learn Code codes
    if (learnOnly) {
      for (let i = 0; i < hosts.length; i++) {
        let currentDevice = discoveredDevices[hosts[i]];

        if (currentDevice.enterLearning) {
          device = currentDevice

          break;
        }
      }

      if (!device) log(`Learn Code (no device found at ${host})`)
      if (!device && !discovering) {
        log(`Attempting to discover RM devices for 5s`);

        discoverDevices()
      }
    } else {
      device = discoveredDevices[hosts[0]];

      if (!device) log(`Send data (no device found at ${host})`);
      if (!device && !discovering) {
        log(`Attempting to discover RM devices for 5s`);

        discoverDevices()
      }
    }
  }

  return device;
}

module.exports = getDevice;
<commit_msg>Additional logging for the status of Broadlink RM devices<commit_after>const ping = require('ping');
const BroadlinkJS = require('broadlinkjs-rm');
const broadlink = new BroadlinkJS()

const pingFrequency = 5000;

const startPing = (device) => {
  device.state = 'unknown';

  setInterval(() => {
    ping.sys.probe(device.host.address, (active) => {
      if (!active && device.state === 'active') {
        console.log(`Broadlink RM device at ${device.host.address} (${device.host.macAddress || ''}) is no longer reachable.`);

        device.state = 'inactive';
      } else if (active && device.state !== 'active') {
        if (device.state === 'inactive') console.log(`Broadlink RM device at ${device.host.address} (${device.host.macAddress || ''}) has been re-discovered.`);

        device.state = 'active';
      }
    })
  }, pingFrequency);
}

const discoveredDevices = {};
const manualDevices = {};

let discovering = false;

const discoverDevices = (count = 0) => {
  discovering = true;

  if (count >= 5) {
    discovering = false;

    return;
  }

  broadlink.discover();
  count++;

  setTimeout(() => {
    discoverDevices(count);
  }, 5 * 1000)
}

discoverDevices();

broadlink.on('deviceReady', (device) => {
  const macAddressParts = device.mac.toString('hex').match(/[\s\S]{1,2}/g) || []
  const macAddress = macAddressParts.join(':')
  device.host.macAddress = macAddress

  if (discoveredDevices[device.host.address] || discoveredDevices[device.host.macAddress]) return;

  console.log(`Discovered Broadlink RM device at ${device.host.address} (${device.host.macAddress})`)

  discoveredDevices[device.host.address] = device;
  discoveredDevices[device.host.macAddress] = device;

  startPing(device)
})

const getDevice = ({ host, log, learnOnly }) => {
  let device;

  if (host) {
    device = discoveredDevices[host];

    // Create manual device
    if (!device && !manualDevices[address]) {
      const device = { host: { address } };
      manualDevices[address] = device;

      startPing(device)
    }
  } else { // use the first one of no host is provided
    const hosts = Object.keys(discoveredDevices);
    if (hosts.length === 0) {
      log(`Send data (no devices found)`);
      if (!discovering) {
        log(`Attempting to discover RM devices for 5s`);

        discoverDevices()
      }

      return
    }

    // Only return device that can Learn Code codes
    if (learnOnly) {
      for (let i = 0; i < hosts.length; i++) {
        let currentDevice = discoveredDevices[hosts[i]];

        if (currentDevice.enterLearning) {
          device = currentDevice

          break;
        }
      }

      if (!device) log(`Learn Code (no device found at ${host})`)
      if (!device && !discovering) {
        log(`Attempting to discover RM devices for 5s`);

        discoverDevices()
      }
    } else {
      device = discoveredDevices[hosts[0]];

      if (!device) log(`Send data (no device found at ${host})`);
      if (!device && !discovering) {
        log(`Attempting to discover RM devices for 5s`);

        discoverDevices()
      }
    }
  }

  return device;
}

module.exports = getDevice;
<|endoftext|>