<commit_before>//Requires for the other roles and modules

//Roles
var roleHarvester = require('role.harvester');
var roleMiner = require('role.miner');
var roleHauler = require('role.hauler');
var roleUpgrader = require('role.upgrader');
var roleBuilder = require('role.builder');
var roleRepair = require('role.repair');
var roleArchitect = require('role.architect');

//Modules
var modSpawning = require('module.spawning');
var modCommon = require('module.common');
var modStructures = require('module.structures');

//Initial memory JSON for the roles
//includes counters for roles and maxes
var initialRolesMem = {
    "numCreeps":0,
    "numHarvesters":0,
    "maxHarvesters":1,
    "numUpgraders":0,
    "maxUpgraders":0,
    "numBuilders":0,
    "maxBuilders":1,
    "numRepair":0,
    "maxRepair":1,
    "numArchitects":0,
    "betterHarvesters1":0,
    "betterHarvesters2":0,
    "numMiners":0,
    "maxMiners":0,
    "numHaulers":0,
    "maxHaulers":1

};

//Tower initial memory JSON
var initialTowerMem = {
  "target":null,
  "mode":"attack",
  "fixe":null
};

//Set all the above JSONs into memeory on first start
function initialize(){
  //TODO make these per room
  Memory.roles = initialRolesMem;
  Memory.towersMem = initialTowerMem;
  Memory.initialized = true;
  Memory.conservation = false;
  Memory.fortify = false;
}

//Gets the number of living harvester Creeps
function getNumHarvesters(creepList){
  var harvesters = _.filter(creepList, (creep) => creep.memory.role == 'harvester');
  var hL = harvesters.length;
  if(Memory.roles.numHarvesters != hL){
    Memory.roles.numHarvesters = hL;
    console.log('Harvesters: ' + hL);
  }
  return hL;
}

//Gets the number of living upgrader Creeps
function getNumUpgraders(creepList){
  var upgraders = _.filter(creepList, (creep) => creep.memory.role == 'upgrader');
  var uL = upgraders.length;
  if(Memory.roles.numUpgraders != uL){
    Memory.roles.numUpgraders = uL;
    console.log('Upgraders: ' + uL);
  }
  return uL;
}

//Gets the number of living builder Creeps
function getNumBuilders(creepList){
  var builders = _.filter(creepList, (creep) => creep.memory.role == 'builder');
  var bL = builders.length;
  if(Memory.roles.numBuilders != bL){
    Memory.roles.numBuilders = bL;
    console.log('Builders: ' + bL);
  }
  return bL;
}

//Gets the number of living Repair Creeps
function getNumRepair(creepList){
  var repair = _.filter(creepList, (creep) => creep.memory.role == 'repair');
  var rL = repair.length;
  if(Memory.roles.numRepair != rL){
    Memory.roles.numRepair = rL;
    console.log('Repair: ' + rL);
  }
  return rL;
}

//Gets the number of living architect Creeps
function getNumArchitects(creepList){
  var architects = _.filter(creepList, (creep) => creep.memory.role == 'architect');
  var aL = architects.length;
  if(Memory.roles.numArchitects != aL){
    Memory.roles.numArchitects = aL;
    console.log('Architects: ' + aL);
  }
  return aL;
}

//Gets the number of living miner Creeps
function getNumMiners(creepList){
  var miners = _.filter(creepList, (creep) => creep.memory.role == 'miner');
  var mL = miners.length;
  if(Memory.roles.numMiners != mL){
    Memory.roles.numMiners = mL;
    console.log('Miners: ' + mL);
  }
  return mL;
}

//Gets the number of living hauler Creeps
function getNumHaulers(creepList){
  var haulers = _.filter(creepList, (creep) => creep.memory.role == 'hauler');
  var haulL = haulers.length;
  if(Memory.roles.numHaulers != haulL){
    Memory.roles.numHaulers = haulL;
    console.log('Haulers: ' + haulL);
  }
  return haulL;
}

//main loop
module.exports.loop = function () {

  //Only initialize if it hasnt been done (or it was manually set to false)
  if(Memory.initialized!==true){
    initialize();
  }

  //Loop to check each room that is visible to the script
  for(var roomName in Game.rooms){
    var room = Game.rooms[roomName];

    if(Memory.fortify && (!room.controller.safeMode || room.controller.safeMode<1000)){
      Memory.fortify = false;
    }

    //Creep lists in each room, comparing lengths shows if there are 'others'
    //TODO check if filter is faster than just Game.creeps
    var allCreepList = room.find(FIND_CREEPS);
    var myCreepList = _.filter(allCreepList, (creep) => (creep.owner && creep.owner.username ==="PCarton"));
    var enemyPresent = allCreepList.length>myCreepList.length;

    //Al the structures in the room that are controlled by the player
    var allStructs = room.find(FIND_MY_STRUCTURES);
    var towers = _.filter(allStructs, (struct) => struct.structureType === STRUCTURE_TOWER);

    //calculates the breakdown of creeps by roles
    var h  = getNumHarvesters(myCreepList);
    var u = getNumUpgraders(myCreepList);
    var b = getNumBuilders(myCreepList);
    var r = getNumRepair(myCreepList);
    var a = getNumArchitects(myCreepList);
    var m = getNumMiners(myCreepList);
    var ha = getNumHaulers(myCreepList);
    Memory.roles.numCreeps = h + u + b + r + a + m + ha;

    //Clear dead creeps from memory
    modCommon.clearDead();

    //assign the right run method to each creep based on its role
    for(var name in myCreepList) {
        var creep = myCreepList[name];

        //Has the non-military creeps retreat
        //Mining creeps are considered military - like the supply line
        if(enemyPresent && creep.memory.military !== true){
          modCommon.retreat(creep);
        }
        //If there are no enemies, run the appropriate role method
        else if(creep.memory.role == 'harvester') {
            roleHarvester.run(creep);
        }
        else if(creep.memory.role == 'upgrader') {
            roleUpgrader.run(creep);
        }
        else if(creep.memory.role == 'builder'){
          roleBuilder.run(creep);
        }
        else if(creep.memory.role == 'repair'){
          roleRepair.run(creep);
        }
        else if(creep.memory.role == 'architect'){
          roleArchitect.run(creep);
        }
        else if(creep.memory.role == 'miner'){
          roleMiner.run(creep);
        }
        else if(creep.memory.role == 'hauler'){
          roleHauler.run(creep);
        }
    }

    //determine if new creeps need to be spawned and pick an appropriate spawner
    //Spawn logic is in a seperate module
    if(Memory.roles.numCreeps < modSpawning.maxCreeps){
        for(var spawn in Game.spawns){
          var spawner = Game.spawns[spawn];
          var controllerLvl= spawner.room.controller.level;
          var energyCapacity = spawner.room.energyCapacityAvailable;
          modSpawning.spawn(spawner,energyCapacity,controllerLvl);

        }
    }

    var control = room.controller;

    if(enemyPresent && modCommon.playerAttack(allCreepList) && !(control.safeMode || control.safeModeCooldown) && control.safeModeAvailable > 0 ){
      control.activateSafeMode();
      Memory.fortify = true;
      Game.notify("Activated Safe Mode");
    }

    //Variable to keep track of which enemy to shoot
    var target = Game.getObjectById(Memory.towersMem.target);

    //Notify the user on enemies or switch to healing and repairing
    if(enemyPresent){
      Memory.towersMem.mode = "attack";
      Game.notify("EnemyFound at "+ Game.time.toString(),60);
    }else{
      Memory.towersMem.mode = "heal";
    }

    //Run through the towers, picking a target if needed
    for(var towerName in towers){
      var t = towers[towerName];
      if(enemyPresent && (target===null || target.room !== t.room)){
        modStructures.pickTargets(t.room.controller, allCreepList);
      }
      modStructures.runTower(t);
    }
  }
};
<commit_msg>removed old TODO message<commit_after>//Requires for the other roles and modules

//Roles
var roleHarvester = require('role.harvester');
var roleMiner = require('role.miner');
var roleHauler = require('role.hauler');
var roleUpgrader = require('role.upgrader');
var roleBuilder = require('role.builder');
var roleRepair = require('role.repair');
var roleArchitect = require('role.architect');

//Modules
var modSpawning = require('module.spawning');
var modCommon = require('module.common');
var modStructures = require('module.structures');

//Initial memory JSON for the roles
//includes counters for roles and maxes
var initialRolesMem = {
    "numCreeps":0,
    "numHarvesters":0,
    "maxHarvesters":1,
    "numUpgraders":0,
    "maxUpgraders":0,
    "numBuilders":0,
    "maxBuilders":1,
    "numRepair":0,
    "maxRepair":1,
    "numArchitects":0,
    "betterHarvesters1":0,
    "betterHarvesters2":0,
    "numMiners":0,
    "maxMiners":0,
    "numHaulers":0,
    "maxHaulers":1

};

//Tower initial memory JSON
var initialTowerMem = {
  "target":null,
  "mode":"attack",
  "fixe":null
};

//Set all the above JSONs into memeory on first start
function initialize(){
  //TODO make these per room
  Memory.roles = initialRolesMem;
  Memory.towersMem = initialTowerMem;
  Memory.initialized = true;
  Memory.conservation = false;
  Memory.fortify = false;
}

//Gets the number of living harvester Creeps
function getNumHarvesters(creepList){
  var harvesters = _.filter(creepList, (creep) => creep.memory.role == 'harvester');
  var hL = harvesters.length;
  if(Memory.roles.numHarvesters != hL){
    Memory.roles.numHarvesters = hL;
    console.log('Harvesters: ' + hL);
  }
  return hL;
}

//Gets the number of living upgrader Creeps
function getNumUpgraders(creepList){
  var upgraders = _.filter(creepList, (creep) => creep.memory.role == 'upgrader');
  var uL = upgraders.length;
  if(Memory.roles.numUpgraders != uL){
    Memory.roles.numUpgraders = uL;
    console.log('Upgraders: ' + uL);
  }
  return uL;
}

//Gets the number of living builder Creeps
function getNumBuilders(creepList){
  var builders = _.filter(creepList, (creep) => creep.memory.role == 'builder');
  var bL = builders.length;
  if(Memory.roles.numBuilders != bL){
    Memory.roles.numBuilders = bL;
    console.log('Builders: ' + bL);
  }
  return bL;
}

//Gets the number of living Repair Creeps
function getNumRepair(creepList){
  var repair = _.filter(creepList, (creep) => creep.memory.role == 'repair');
  var rL = repair.length;
  if(Memory.roles.numRepair != rL){
    Memory.roles.numRepair = rL;
    console.log('Repair: ' + rL);
  }
  return rL;
}

//Gets the number of living architect Creeps
function getNumArchitects(creepList){
  var architects = _.filter(creepList, (creep) => creep.memory.role == 'architect');
  var aL = architects.length;
  if(Memory.roles.numArchitects != aL){
    Memory.roles.numArchitects = aL;
    console.log('Architects: ' + aL);
  }
  return aL;
}

//Gets the number of living miner Creeps
function getNumMiners(creepList){
  var miners = _.filter(creepList, (creep) => creep.memory.role == 'miner');
  var mL = miners.length;
  if(Memory.roles.numMiners != mL){
    Memory.roles.numMiners = mL;
    console.log('Miners: ' + mL);
  }
  return mL;
}

//Gets the number of living hauler Creeps
function getNumHaulers(creepList){
  var haulers = _.filter(creepList, (creep) => creep.memory.role == 'hauler');
  var haulL = haulers.length;
  if(Memory.roles.numHaulers != haulL){
    Memory.roles.numHaulers = haulL;
    console.log('Haulers: ' + haulL);
  }
  return haulL;
}

//main loop
module.exports.loop = function () {

  //Only initialize if it hasnt been done (or it was manually set to false)
  if(Memory.initialized!==true){
    initialize();
  }

  //Loop to check each room that is visible to the script
  for(var roomName in Game.rooms){
    var room = Game.rooms[roomName];

    if(Memory.fortify && (!room.controller.safeMode || room.controller.safeMode<1000)){
      Memory.fortify = false;
    }

    //Creep lists in each room, comparing lengths shows if there are 'others'
    var allCreepList = room.find(FIND_CREEPS);
    var myCreepList = _.filter(allCreepList, (creep) => (creep.owner && creep.owner.username ==="PCarton"));
    var enemyPresent = allCreepList.length>myCreepList.length;

    //Al the structures in the room that are controlled by the player
    var allStructs = room.find(FIND_MY_STRUCTURES);
    var towers = _.filter(allStructs, (struct) => struct.structureType === STRUCTURE_TOWER);

    //calculates the breakdown of creeps by roles
    var h  = getNumHarvesters(myCreepList);
    var u = getNumUpgraders(myCreepList);
    var b = getNumBuilders(myCreepList);
    var r = getNumRepair(myCreepList);
    var a = getNumArchitects(myCreepList);
    var m = getNumMiners(myCreepList);
    var ha = getNumHaulers(myCreepList);
    Memory.roles.numCreeps = h + u + b + r + a + m + ha;

    //Clear dead creeps from memory
    modCommon.clearDead();

    //assign the right run method to each creep based on its role
    for(var name in myCreepList) {
        var creep = myCreepList[name];

        //Has the non-military creeps retreat
        //Mining creeps are considered military - like the supply line
        if(enemyPresent && creep.memory.military !== true){
          modCommon.retreat(creep);
        }
        //If there are no enemies, run the appropriate role method
        else if(creep.memory.role == 'harvester') {
            roleHarvester.run(creep);
        }
        else if(creep.memory.role == 'upgrader') {
            roleUpgrader.run(creep);
        }
        else if(creep.memory.role == 'builder'){
          roleBuilder.run(creep);
        }
        else if(creep.memory.role == 'repair'){
          roleRepair.run(creep);
        }
        else if(creep.memory.role == 'architect'){
          roleArchitect.run(creep);
        }
        else if(creep.memory.role == 'miner'){
          roleMiner.run(creep);
        }
        else if(creep.memory.role == 'hauler'){
          roleHauler.run(creep);
        }
    }

    //determine if new creeps need to be spawned and pick an appropriate spawner
    //Spawn logic is in a seperate module
    if(Memory.roles.numCreeps < modSpawning.maxCreeps){
        for(var spawn in Game.spawns){
          var spawner = Game.spawns[spawn];
          var controllerLvl= spawner.room.controller.level;
          var energyCapacity = spawner.room.energyCapacityAvailable;
          modSpawning.spawn(spawner,energyCapacity,controllerLvl);

        }
    }

    var control = room.controller;

    if(enemyPresent && modCommon.playerAttack(allCreepList) && !(control.safeMode || control.safeModeCooldown) && control.safeModeAvailable > 0 ){
      control.activateSafeMode();
      Memory.fortify = true;
      Game.notify("Activated Safe Mode");
    }

    //Variable to keep track of which enemy to shoot
    var target = Game.getObjectById(Memory.towersMem.target);

    //Notify the user on enemies or switch to healing and repairing
    if(enemyPresent){
      Memory.towersMem.mode = "attack";
      Game.notify("EnemyFound at "+ Game.time.toString(),60);
    }else{
      Memory.towersMem.mode = "heal";
    }

    //Run through the towers, picking a target if needed
    for(var towerName in towers){
      var t = towers[towerName];
      if(enemyPresent && (target===null || target.room !== t.room)){
        modStructures.pickTargets(t.room.controller, allCreepList);
      }
      modStructures.runTower(t);
    }
  }
};
<|endoftext|>


<commit_before>openerp.account = function (instance) {
    var _t = instance.web._t,
        _lt = instance.web._lt;
    var QWeb = instance.web.qweb;

    instance.web.account = {};

    instance.web.views.add('account_reconciliation_list', 'instance.web.account.ReconciliationListView');
    instance.web.account.ReconciliationListView = instance.web.ListView.extend({
        init: function() {
            this._super.apply(this, arguments);
        },
        on_loaded: function() {
            var tmp = this._super.apply(this, arguments);
            this.$el.prepend(QWeb.render("AccountReconciliation"));
            return tmp;
        },
        do_search: function(domain, context, group_by) {
            var sup = _.bind(this._super, this);
            var mod = new instance.web.Model(this.model, context, domain);
            return mod.query("partner_id").group_by(["partner_id"]).pipe(function(result) {
                var vals = _.chain(result).pluck("attributes").pluck("value")
                    .filter(function(el) {return !!el;}).value();
                return sup(new instance.web.CompoundDomain(domain, [["partner_id", "in", _.pluck(vals, 0)]]), context, group_by);
            });
        },
    });

    /*instance.web.views.add('form_clone', 'instance.account.extend_form_view');

    instance.account.extend_viewmanager = instance.web.ViewManagerAction.include({
        start: function () {
            this._super();
            if (this.action.context && this.action.context.extended_view_id && this.action.context.extended_model) {
                this.setup_exended_form_view(this.action.context.extended_model, this.action.context.extended_view_id);
            }
        },
        setup_exended_form_view: function (view_model, view_id) {
            var self = this;
            var from_view = this.registry.get_object('form_clone');
            this.dataset_form = new instance.web.DataSetSearch(this, view_model, this.action.context, this.action.domain);
            this.dataset_loaded = this.dataset_form.read_slice();
            var obj_from_view = new from_view(self, self.dataset_form, view_id, {});
            obj_from_view.template = 'ExtendedFormView';
            var view_form = obj_from_view.appendTo(self.$el.find('.oe_extended_form_view'));
            $.when(view_form, this.dataset_loaded).then(function () {
                obj_from_view.on_pager_action('first');
            });
        }
    });

    instance.account.extend_form_view = instance.web.FormView.extend({
        on_loaded: function (data) {
            this._super.apply(this, arguments);
            var self = this;
            this.$el.find(".oe_reconcile").on('click', this.do_reconcilation);
            this.$el.find(".oe_nothing_to_reconcile").on('click', this.do_nothing_to_reconcile);
            this.$el.on('click', 'a[data-pager-action]', function () {
                var action = $(this).data('pager-action');
                self.on_pager_action(action);
            });
        },
        do_reconcilation: function (event) {
            var self = this;
            if (!self.datarecord.id) {
                return false;
            }
            var list_view = this.getParent().views['list'].controller;
            var ids = list_view.get_selected_ids();
            if (ids.length === 0) {
                instance.web.dialog($("<div />").text(_t("You must choose at least one record.")), {
                    title: _t("Warning"),
                    modal: true
                });
                return false;
            }
            var additional_context = _.extend({
                active_id: ids[0],
                active_ids: ids,
                active_model: list_view.dataset.model
            });
            self.rpc("/web/action/load", {
                action_id: py.eval(event.target.name),
                context: additional_context
            }, function (result) {
                result.result.context = _.extend(result.result.context || {},
                additional_context);
                result.result.flags = result.result.flags || {};
                result.result.flags.new_window = true;
                self.do_action(result.result, function () {
                    self.dataset.read_slice().done(function () {
                        self.on_pager_action('next');
                    });
                });
            });
            return true;
        },

        do_nothing_to_reconcile: function () {
            var self = this;
            if (!self.datarecord.id) {
                return false;
            }
            // how do you want this to not fail ???
            var event = null;
            this.dataset.call(event.target.name, [
                [self.datarecord.id], self.dataset.context]).then(function () {
                self.dataset.read_slice().done(function () {
                    self.on_pager_action('next');
                });
            });
            return true;
        },

        do_update_pager: function (hide_index) {
            var index = this.dataset.index + 1;
            if (this.dataset.ids.length === 0) index = 0;
            index = hide_index ? '-' : index;
            this.$el.find('span.oe_pager_index_extend').html(index).end().find('span.oe_pager_count_extend').html(this.dataset.ids.length);
        },

        do_search_move_line: function (partner_ids) {
            var viewmanager = this.getParent();
            viewmanager.action.context.next_partner_only = true;
            viewmanager.action.context.partner_id = partner_ids;
            viewmanager.searchview.do_search();
        },

        on_pager_action: function (action) {
            var self = this;

            if (this.dataset.ids.length === 0) {
                self.datarecord = {};
                _(this.fields).each(function (field, f) {
                    field.set_value(self.datarecord[f] || false);
                });
                self.do_update_pager();
                self.do_search_move_line([]);
            } else {
                $.when(this._super(action)).then(function () {
                    var id = self.get_fields_values().partner_id;
                    self.do_search_move_line([id]);
                });
            }
        },
    });*/

};<commit_msg>wip<commit_after>openerp.account = function (instance) {
    var _t = instance.web._t,
        _lt = instance.web._lt;
    var QWeb = instance.web.qweb;

    instance.web.account = {};

    instance.web.views.add('account_reconciliation_list', 'instance.web.account.ReconciliationListView');
    instance.web.account.ReconciliationListView = instance.web.ListView.extend({
        init: function() {
            this._super.apply(this, arguments);
        },
        on_loaded: function() {
            var tmp = this._super.apply(this, arguments);
            this.$el.prepend(QWeb.render("AccountReconciliation"));
            return tmp;
        },
        do_search: function(domain, context, group_by) {
            var self = this;
            this.last_domain = domain;
            this.last_context = context;
            this.last_group_by = group_by;
            this.old_search = _.bind(this._super, this);
            var mod = new instance.web.Model(this.model, context, domain);
            return mod.query("partner_id").group_by(["partner_id"]).pipe(function(result) {
                self.partners = _.chain(result).pluck("attributes").pluck("value")
                    .filter(function(el) {return !!el;}).value();
                self.current_partner = self.partners.length == 0 ? null : 0;
                return self.search_by_partner(self.current_partner);

            });
        },
        search_by_partner: function(partner) {
            return this.old_search(new instance.web.CompoundDomain(this.last_domain, [["partner_id", "in", partner === null ? [] : [this.partners[partner][0]] ]]),
                this.last_context, this.last_group_by);
        }
    });

    /*instance.web.views.add('form_clone', 'instance.account.extend_form_view');

    instance.account.extend_viewmanager = instance.web.ViewManagerAction.include({
        start: function () {
            this._super();
            if (this.action.context && this.action.context.extended_view_id && this.action.context.extended_model) {
                this.setup_exended_form_view(this.action.context.extended_model, this.action.context.extended_view_id);
            }
        },
        setup_exended_form_view: function (view_model, view_id) {
            var self = this;
            var from_view = this.registry.get_object('form_clone');
            this.dataset_form = new instance.web.DataSetSearch(this, view_model, this.action.context, this.action.domain);
            this.dataset_loaded = this.dataset_form.read_slice();
            var obj_from_view = new from_view(self, self.dataset_form, view_id, {});
            obj_from_view.template = 'ExtendedFormView';
            var view_form = obj_from_view.appendTo(self.$el.find('.oe_extended_form_view'));
            $.when(view_form, this.dataset_loaded).then(function () {
                obj_from_view.on_pager_action('first');
            });
        }
    });

    instance.account.extend_form_view = instance.web.FormView.extend({
        on_loaded: function (data) {
            this._super.apply(this, arguments);
            var self = this;
            this.$el.find(".oe_reconcile").on('click', this.do_reconcilation);
            this.$el.find(".oe_nothing_to_reconcile").on('click', this.do_nothing_to_reconcile);
            this.$el.on('click', 'a[data-pager-action]', function () {
                var action = $(this).data('pager-action');
                self.on_pager_action(action);
            });
        },
        do_reconcilation: function (event) {
            var self = this;
            if (!self.datarecord.id) {
                return false;
            }
            var list_view = this.getParent().views['list'].controller;
            var ids = list_view.get_selected_ids();
            if (ids.length === 0) {
                instance.web.dialog($("<div />").text(_t("You must choose at least one record.")), {
                    title: _t("Warning"),
                    modal: true
                });
                return false;
            }
            var additional_context = _.extend({
                active_id: ids[0],
                active_ids: ids,
                active_model: list_view.dataset.model
            });
            self.rpc("/web/action/load", {
                action_id: py.eval(event.target.name),
                context: additional_context
            }, function (result) {
                result.result.context = _.extend(result.result.context || {},
                additional_context);
                result.result.flags = result.result.flags || {};
                result.result.flags.new_window = true;
                self.do_action(result.result, function () {
                    self.dataset.read_slice().done(function () {
                        self.on_pager_action('next');
                    });
                });
            });
            return true;
        },

        do_nothing_to_reconcile: function () {
            var self = this;
            if (!self.datarecord.id) {
                return false;
            }
            // how do you want this to not fail ???
            var event = null;
            this.dataset.call(event.target.name, [
                [self.datarecord.id], self.dataset.context]).then(function () {
                self.dataset.read_slice().done(function () {
                    self.on_pager_action('next');
                });
            });
            return true;
        },

        do_update_pager: function (hide_index) {
            var index = this.dataset.index + 1;
            if (this.dataset.ids.length === 0) index = 0;
            index = hide_index ? '-' : index;
            this.$el.find('span.oe_pager_index_extend').html(index).end().find('span.oe_pager_count_extend').html(this.dataset.ids.length);
        },

        do_search_move_line: function (partner_ids) {
            var viewmanager = this.getParent();
            viewmanager.action.context.next_partner_only = true;
            viewmanager.action.context.partner_id = partner_ids;
            viewmanager.searchview.do_search();
        },

        on_pager_action: function (action) {
            var self = this;

            if (this.dataset.ids.length === 0) {
                self.datarecord = {};
                _(this.fields).each(function (field, f) {
                    field.set_value(self.datarecord[f] || false);
                });
                self.do_update_pager();
                self.do_search_move_line([]);
            } else {
                $.when(this._super(action)).then(function () {
                    var id = self.get_fields_values().partner_id;
                    self.do_search_move_line([id]);
                });
            }
        },
    });*/

};<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

(function () {
    "use strict";

    var fs = require("fs"),
        resolve = require("path").resolve,
        mkdirp = require("mkdirp"),
        temp = require("temp"),
        Q = require("q"),
        convert = require("./lib/convert"),
        xpm2png = require("./lib/xpm2png");

    var assetGenerationDir = null;
    var latestRequestIdPerPath = {};

    function getUserHomeDirectory() {
        return process.env[(process.platform === "win32") ? "USERPROFILE" : "HOME"];
    }

    var _generator = null;

    function savePixmap(pixmap, filename) {
        var deferred = Q.defer();

        _generator.publish("assets.debug.dump", "dumping " + filename);

        var args = ["-", "-size", pixmap.width + "x" + pixmap.height, "png:-"];
        var proc = convert(args, _generator._photoshop._applicationPath);
        var fileStream = fs.createWriteStream(filename);
        var stderr = "";

        proc.stderr.on("data", function (chunk) { stderr += chunk; });
        proc.stdout.on("close", function () {
            deferred.resolve(filename);
        });

        xpm2png(pixmap, proc.stdin.end.bind(proc.stdin));
        proc.stdout.pipe(fileStream);

        proc.stderr.on("close", function () {
            if (stderr) {
                var error = "error from ImageMagick: " + stderr;
                _generator.publish("assets.error.convert", error);
                deferred.reject(error);
            }
        });

        return deferred.promise;
    }

    function handleImageChanged(message) {
        console.log("Image changed", JSON.stringify(message, null, "\t"));
        if (message.documentID && message.layerEvents) {
            message.layerEvents.forEach(function (e) {
                console.log("Layer change", e);
                handleImageChangedForLayer(message, e.layerID);
            });
        }
    }

    function handleImageChangedForLayer(message, layerID) {
        console.log("Updating layer " + layerID);
        _generator.getPixmap(layerID, 100).then(
            function (pixmap) {
                if (assetGenerationDir) {
                    var fileName = message.documentID + "-" + layerID + ".png",
                        path     = resolve(assetGenerationDir, fileName),
                        tmpPath  = temp.path({ suffix: ".png" });

                    // First time this path is used
                    if (!latestRequestIdPerPath[path]) {
                        latestRequestIdPerPath[path] = 0;
                    }
                    // Increment and store the current request ID
                    var requestId = ++latestRequestIdPerPath[path];

                    // Prevent an error after deleting a layer's contents, resulting in a 0x0 pixmap
                    if (pixmap.width === 0 || pixmap.height === 0) {
                        // Delete the image for the empty layer
                        fs.unlink(path);
                    }
                    else {
                        // Save the image in a temporary file
                        savePixmap(pixmap, tmpPath)
                            // When ImageMagick is done
                            .done(function () {
                                // If no other conversion has been started in the meantime...
                                if (requestId === latestRequestIdPerPath[path]) {
                                    // ...move the temporary file to the desired location
                                    fs.rename(tmpPath, path);
                                }
                            });
                    }

                }
            }, function (err) {
                _generator.publish("assets.error.getPixmap", "Error: " + err);
            });
    }

    function init(generator) {
        _generator = generator;
        _generator.subscribe("photoshop.event.imageChanged", handleImageChanged);

        // create a place to save assets
        var homeDir = getUserHomeDirectory();
        if (homeDir) {
            var newDir = resolve(homeDir, "Desktop", "generator-assets");
            mkdirp(newDir, function (err) {
                if (err) {
                    _generator.publish(
                        "assets.error.init",
                        "Could not create directory '" + newDir + "', no assets will be dumped"
                    );
                } else {
                    assetGenerationDir = newDir;
                }
            });
        } else {
            _generator.publish(
                "assets.error.init",
                "Could not locate home directory in env vars, no assets will be dumped"
            );
        }
    }

    exports.init = init;

}());<commit_msg>Only process one change of a layer at a time<commit_after>/*
 * Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

(function () {
    "use strict";

    var fs = require("fs"),
        resolve = require("path").resolve,
        mkdirp = require("mkdirp"),
        temp = require("temp"),
        Q = require("q"),
        convert = require("./lib/convert"),
        xpm2png = require("./lib/xpm2png");

    var assetGenerationDir = null;
    var contextPerLayer = {};

    function getUserHomeDirectory() {
        return process.env[(process.platform === "win32") ? "USERPROFILE" : "HOME"];
    }

    var _generator = null;

    function savePixmap(pixmap, filename) {
        var deferred = Q.defer();

        _generator.publish("assets.debug.dump", "dumping " + filename);

        var args = ["-", "-size", pixmap.width + "x" + pixmap.height, "png:-"];
        var proc = convert(args, _generator._photoshop._applicationPath);
        var fileStream = fs.createWriteStream(filename);
        var stderr = "";

        proc.stderr.on("data", function (chunk) { stderr += chunk; });
        proc.stdout.on("close", function () {
            deferred.resolve(filename);
        });

        xpm2png(pixmap, proc.stdin.end.bind(proc.stdin));
        proc.stdout.pipe(fileStream);

        proc.stderr.on("close", function () {
            if (stderr) {
                var error = "error from ImageMagick: " + stderr;
                _generator.publish("assets.error.convert", error);
                deferred.reject(error);
            }
        });

        return deferred.promise;
    }

    function handleImageChanged(message) {
        // console.log("Image changed", JSON.stringify(message, null, "\t"));
        if (message.documentID && message.layerEvents) {
            // Will eventually not be named layerEvents => use variable name layer instead of e for event
            message.layerEvents.forEach(function (layer) {
                handleImageChangedForLayer(message, layer);
            });
        }
    }

    function handleImageChangedForLayer(message, layer) {
        if (!assetGenerationDir) {
            return;
        }

        var contextID    = message.documentID + "-" + layer.layerID,
            layerContext = contextPerLayer[contextID];

        if (!contextPerLayer[contextID]) {
            // Initialize the context object for this layer.
            // It will be deleted again once an update has finished
            // without the image changing during the update.
            contextPerLayer[contextID] = {
                // Store the context ID here so the context can be deleted by finishLayerUpdate
                contextID:        contextID,
                documentID:       message.documentID,
                layerID:          layer.layerID,
                updateInProgress: false,
                updateIsObsolete: false
            };
        }

        scheduleLayerUpdate(contextPerLayer[contextID]);
    }

    // Run the update now if none is in progress, or wait until the current one is finished
    function scheduleLayerUpdate(layerContext) {
        if (!layerContext.updateInProgress) {
            layerContext.updateInProgress = true;
            startLayerUpdate(layerContext);
        } else if (!layerContext.updateIsObsolete) {
            layerContext.updateIsObsolete = true;
        }
    }

    // Start a new update
    function startLayerUpdate(layerContext) {
        _generator.getPixmap(layerContext.layerID, 100).then(
            function (pixmap) {
                var fileName = layerContext.documentID + "-" + layerContext.layerID + ".png",
                    path     = resolve(assetGenerationDir, fileName),
                    tmpPath  = temp.path({ suffix: ".png" });

                // Prevent an error after deleting a layer's contents, resulting in a 0x0 pixmap
                if (pixmap.width === 0 || pixmap.height === 0) {
                    // Delete the image for the empty layer
                    fs.unlink(path, function (err) {
                        // TODO: handle errors?
                        finishLayerUpdate(layerContext);
                    });
                }
                else {
                    // Save the image in a temporary file
                    savePixmap(pixmap, tmpPath)
                        .fail(function (err) {
                            console.log("Save pixmap failed:", err);
                            finishLayerUpdate(layerContext);
                        })
                        // When ImageMagick is done
                        .done(function () {
                            // ...move the temporary file to the desired location
                            fs.rename(tmpPath, path, function (err) {
                                // TODO: handle errors?`
                                finishLayerUpdate(layerContext);
                            });
                        });
                }
            },
            function (err) {
                console.log("Get pixmap failed:", err);
                _generator.publish("assets.error.getPixmap", "Error: " + err);
                finishLayerUpdate(layerContext);
            }
        );
    }

    // Run a pending update if necessary
    function finishLayerUpdate(layerContext) {
        if (layerContext.updateIsObsolete) {
            layerContext.updateIsObsolete = false;
            startLayerUpdate(layerContext);
        } else {
            layerContext.updateInProgress = false;
            delete contextPerLayer[layerContext.contextID];
        }
    }

    function init(generator) {
        _generator = generator;
        _generator.subscribe("photoshop.event.imageChanged", handleImageChanged);

        // create a place to save assets
        var homeDir = getUserHomeDirectory();
        if (homeDir) {
            var newDir = resolve(homeDir, "Desktop", "generator-assets");
            mkdirp(newDir, function (err) {
                if (err) {
                    _generator.publish(
                        "assets.error.init",
                        "Could not create directory '" + newDir + "', no assets will be dumped"
                    );
                } else {
                    assetGenerationDir = newDir;
                }
            });
        } else {
            _generator.publish(
                "assets.error.init",
                "Could not locate home directory in env vars, no assets will be dumped"
            );
        }
    }

    exports.init = init;

}());<|endoftext|>


<commit_before>define(function (require, exports, module) {
  module.exports = {
    Tabs: require('./src/tabs.js'),
    Pane: require('./src/pane.js')
  };
});
<commit_msg>Modify main export statement<commit_after>import Tabs from './src/tabs.js';
import Pane from './src/pane.js';

export default Tabs;
export default Pane;
<|endoftext|>


<commit_before>$('#search1').hideseek({
    list: '.list1',
  });
  var addPostionClass = function(){
  $("li:contains('WR')").addClass("receiver");
  $("li:contains('RB')").addClass("rback");
  $("li:contains('QB')").addClass("qback");
  $("li:contains('TE-')").addClass("tend");
  $("li:contains('DST')").addClass("dst");
  $("li:contains('K-')").addClass("kicker");
}

if(document.getElementById('parent')){
var theList = document.getElementById('parent');
if(localStorage.getItem('parent')){
theList.innerHTML = localStorage.getItem('parent');
}
}
if(document.getElementById('parent-ppr')){
var theListPpr = document.getElementById('parent-ppr');
if(localStorage.getItem('parent-ppr')){
theListPpr.innerHTML = localStorage.getItem('parent-ppr');
}
}
if(document.getElementById('parent-pprhalf')){
var theListHalfPpr = document.getElementById('parent-pprhalf');
if(localStorage.getItem('parent-pprhalf')){
theListHalfPpr.innerHTML = localStorage.getItem('parent-pprhalf');
}
}

addPostionClass();

//Toggles classes of list items on click eventsf
$(".listitem1").click(function(e) {
  $(this).toggleClass('listitem2');
});
$(".listitem1").dblclick(function(f) {
  $(this).toggleClass('listitem3');
});

$(".quarterbackbt").click(function(g) {
  //$("li:contains('QB'),li:contains('WR'),li:contains('RB'),li:contains('TE'),li:contains('DST'),li:contains('K')").removeClass("hiddenbt");

  $("li:contains('QB')").toggleClass("hiddenbt");
  $(".quarterbackbt").toggleClass("btshrink");

});
$(".runningbackbt").click(function(g) {
  $("li:contains('RB')").toggleClass("hiddenbt");
  $(".runningbackbt").toggleClass("btshrink");

});
$(".tightendbt").click(function(g) {

  $("li:contains('TE-')").toggleClass("hiddenbt");
  $(".tightendbt").toggleClass("btshrink");
});
$(".receiverbt").click(function(g) {

  $("li:contains('WR')").toggleClass("hiddenbt");
  $(".receiverbt").toggleClass("btshrink");
});

$(".defensebt").click(function(g) {

  $("li:contains('DST')").toggleClass("hiddenbt");
  $(".defensebt").toggleClass("btshrink");
});

$(".kickerbt").click(function(g) {

  $("li:contains('K-')").toggleClass("hiddenbt");
  $(".kickerbt").toggleClass("btshrink");
});

var wrap = $("#wrap");

$(window).on("scroll", function() {

  if ($(window).scrollTop() > 125) {
    wrap.addClass("positionsbartop");
  } else {
    wrap.removeClass("positionsbartop");
  }
});

$(function() {
  var url = window.location.href;
  var page = url.substr(url.lastIndexOf('/') + 1);
  $('a[href*="' + page + '"], a[href*=index]').addClass('active');
});

  $("#parent").sortable({
    axis:"y",
    handle: '.handle',
    update: function( ) {

      localStorage.setItem('parent', theList.innerHTML);
    }
  });
  $("#parent-ppr").sortable({
    axis:"y",
    handle: '.handle',
    update: function( ) {

      localStorage.setItem('parent-ppr', theListPpr.innerHTML);
    }
  });
  $("#parent-pprhalf").sortable({
    axis:"y",
    handle: '.handle',
    update: function( ) {

      localStorage.setItem('parent-pprhalf', theListHalfPpr.innerHTML);
    }
  });
<commit_msg>updated comments. Cleaned up line breaks and spaces.<commit_after>//Hideseek.js .list1 is the searchable list
$('#search1').hideseek({
  list: '.list1',
});
  //adds positions classes to list item based on player position
var addPostionClass = function(){
  $("li:contains('WR')").addClass("receiver");
  $("li:contains('RB')").addClass("rback");
  $("li:contains('QB')").addClass("qback");
  $("li:contains('TE-')").addClass("tend");
  $("li:contains('DST')").addClass("dst");
  $("li:contains('K-')").addClass("kicker");
}
//gets list from local storage if it exists there
if(document.getElementById('parent')){
var theList = document.getElementById('parent');
if(localStorage.getItem('parent')){
theList.innerHTML = localStorage.getItem('parent');
}
}
if(document.getElementById('parent-ppr')){
var theListPpr = document.getElementById('parent-ppr');
if(localStorage.getItem('parent-ppr')){
theListPpr.innerHTML = localStorage.getItem('parent-ppr');
}
}
if(document.getElementById('parent-pprhalf')){
var theListHalfPpr = document.getElementById('parent-pprhalf');
if(localStorage.getItem('parent-pprhalf')){
theListHalfPpr.innerHTML = localStorage.getItem('parent-pprhalf');
}
}
//Calls function to add classes to positions
addPostionClass();
//Toggles classes of list items on click eventsf
$(".listitem1").click(function(e) {
  $(this).toggleClass('listitem2');
});
$(".listitem1").dblclick(function(f) {
  $(this).toggleClass('listitem3');
});
//Hides list items when position buttons are clicked
$(".quarterbackbt").click(function(g) {
  $("li:contains('QB')").toggleClass("hiddenbt");
  $(".quarterbackbt").toggleClass("btshrink");
});
$(".runningbackbt").click(function(g) {
  $("li:contains('RB')").toggleClass("hiddenbt");
  $(".runningbackbt").toggleClass("btshrink");
});
$(".tightendbt").click(function(g) {
  $("li:contains('TE-')").toggleClass("hiddenbt");
  $(".tightendbt").toggleClass("btshrink");
});
$(".receiverbt").click(function(g) {
  $("li:contains('WR')").toggleClass("hiddenbt");
  $(".receiverbt").toggleClass("btshrink");
});
$(".defensebt").click(function(g) {
  $("li:contains('DST')").toggleClass("hiddenbt");
  $(".defensebt").toggleClass("btshrink");
});
$(".kickerbt").click(function(g) {
  $("li:contains('K-')").toggleClass("hiddenbt");
  $(".kickerbt").toggleClass("btshrink");
});
//fixes positions bar to top on scoll down
var wrap = $("#wrap");
$(window).on("scroll", function() {
  if ($(window).scrollTop() > 125) {
    wrap.addClass("positionsbartop");
  } else {
    wrap.removeClass("positionsbartop");
  }
});
//Changes nav link to active when on that page. Stores list locally on change.
$(function() {
  var url = window.location.href;
  var page = url.substr(url.lastIndexOf('/') + 1);
  $('a[href*="' + page + '"], a[href*=index]').addClass('active');
});
//Uses jquery-ui to make list sortable
$("#parent").sortable({
  axis:"y",
  handle: '.handle',
  update: function( ) {
    localStorage.setItem('parent', theList.innerHTML);
  }
});
$("#parent-ppr").sortable({
  axis:"y",
  handle: '.handle',
  update: function( ) {
    localStorage.setItem('parent-ppr', theListPpr.innerHTML);
  }
});
$("#parent-pprhalf").sortable({
  axis:"y",
  handle: '.handle',
  update: function( ) {
    localStorage.setItem('parent-pprhalf', theListHalfPpr.innerHTML);
  }
});
<|endoftext|>


<commit_before>import elementUtils from 'src/helpers/elementUtils';
import defaultConfig from './defaultConfig';
import renderCore from './core';
import helper from './helper';

/**
 * Constructor for the PageRenderer instance that is used to contain the
 * source HTML and CSS data and the render target's id and page size
 * @param {string|Element} renderDomTarget - Accept either a ID string
 *                                           of a HTML Element or HTML Element reference
 * @param {Object} page - A page config containing information about the page sizing
 * @param {string} page.width - in css width.
 * @param {string} page.height - in css height.
 * @param {Object} page.padding - for setting the inner the padding size used on the page.
 * @param {Array} postProcessingPlugins - an optional array of plugins that contain a `.process` function.
 *                                        These functions are to be executed on the referenceFrame.
 *                                        These functions will receive the referenceFrame object and
 *                                        should return a promise when it is done.
 */
export default function PageRenderer(renderDomTarget, page, postProcessPromiseFns) {
  // Set page sizing. Use default if not provided
  this.page = page || defaultConfig.page;
  this.renderHeight = helper.computeRenderHeight(this.page);

  // Set renderFrame and id
  this.renderDomId = (typeof renderDomTarget === 'string') ? renderDomTarget : 'paginated-view';
  this.renderFrame = elementUtils.resolveElement(renderDomTarget);
  if (!this.renderFrame) {
    throw new Error('Element provided to PageRenderer is not found at this moment');
  }
  this.ownerDocument = renderDomTarget.ownerDocument;

  // Set reference frame
  this.referenceFrame = this.getReferenceFrame();
  this.postProcessPromiseFns = postProcessPromiseFns || [];

  // Set sourceHTML
  this.sourceHTML = null;
}

/**
 * Obtain the reference frame of the rendering instance.
 * The reference frame will be created if it does not exist.
 * The width and padding size of the reference frame will be
 * configured here.
 * @return {Element} referenceFrame - a reference to the reference frame object
 */
PageRenderer.prototype.getReferenceFrame = function getReferenceFrame() {
  const idOfReferenceFrame = defaultConfig.prefix.reference + this.renderDomId;
  let referenceFrame = this.ownerDocument.getElementById(idOfReferenceFrame);

  // Create a new reference frame if doesn't exist
  if (!referenceFrame) {
    referenceFrame = this.ownerDocument.createElement('DIV');
    referenceFrame.setAttribute('id', idOfReferenceFrame);

    // Set reference frame styling by iterate through the refStyle
    const refStyle = {
      // CSS to hide the reference frame from the user
      position: 'absolute',
      top: 0,
      left: '-99999px',
      zIndex: -99999,
      visibility: 'hidden',
      overflow: 'hidden',
      height: 0,
      boxSizing: 'border-box',

      // CSS to set up the page sizing
      width: this.page.width,
      paddingTop: this.page.padding.top,
      paddingBottom: this.page.padding.bottom,
      paddingLeft: this.page.padding.left,
      paddingRight: this.page.padding.right
    };
    helper.overwriteStyle(referenceFrame.style, refStyle);

    // Render reference frame to DOM
    if (!this.ownerDocument.body) {
      throw new Error('Unable to append referenceFrame to document body');
    }
    this.ownerDocument.body.appendChild(referenceFrame);
  }

  return referenceFrame;
};

// Public instance methods
/**
 * Trigger the rendering process of the pageRenderer instance
 * @return {Promise} promise - to indicate the completion of the rendering process
 */
PageRenderer.prototype.render = function render() {
  return renderCore.updateReferenceFrame(this)
  .then(renderCore.getChildHeights)
  .then(childHeights => renderCore.getPaginationVirtualDom(this, childHeights))
  .then(virtualDom => renderCore.renderPage(this, virtualDom));
};

/**
 * Update the HTML content of the page renderer.
 * This will trigger the rendering process.
 * @param {string} htmlString
 * @return {Promise} promise - to indicate the completion of the rendering process
 */
PageRenderer.prototype.write = function write(htmlString) {
  this.sourceHTML = htmlString;
  return this.render();
};

/**
 * Update the page size of the page renderer.
 * This will trigger the rendering process.
 * @param {pageConfig} htmlString
 * @return {Promise} promise - to indicate the completion of the rendering process
 */
PageRenderer.prototype.updatePageSize = function write(pageConfig) {
  this.page = pageConfig;
  this.renderHeight = helper.computeRenderHeight(this.page);
  return this.render();
};
<commit_msg>Remove additional space<commit_after>import elementUtils from 'src/helpers/elementUtils';
import defaultConfig from './defaultConfig';
import renderCore from './core';
import helper from './helper';

/**
 * Constructor for the PageRenderer instance that is used to contain the
 * source HTML and CSS data and the render target's id and page size
 * @param {string|Element} renderDomTarget - Accept either a ID string
 *                                           of a HTML Element or HTML Element reference
 * @param {Object} page - A page config containing information about the page sizing
 * @param {string} page.width - in css width.
 * @param {string} page.height - in css height.
 * @param {Object} page.padding - for setting the inner the padding size used on the page.
 * @param {Array} postProcessingPlugins - an optional array of plugins that contain a `.process` function.
 *                                        These functions are to be executed on the referenceFrame.
 *                                        These functions will receive the referenceFrame object and
 *                                        should return a promise when it is done.
 */
export default function PageRenderer(renderDomTarget, page, postProcessPromiseFns) {
  // Set page sizing. Use default if not provided
  this.page = page || defaultConfig.page;
  this.renderHeight = helper.computeRenderHeight(this.page);

  // Set renderFrame and id
  this.renderDomId = (typeof renderDomTarget === 'string') ? renderDomTarget : 'paginated-view';
  this.renderFrame = elementUtils.resolveElement(renderDomTarget);
  if (!this.renderFrame) {
    throw new Error('Element provided to PageRenderer is not found at this moment');
  }
  this.ownerDocument = renderDomTarget.ownerDocument;

  // Set reference frame
  this.referenceFrame = this.getReferenceFrame();
  this.postProcessPromiseFns = postProcessPromiseFns || [];

  // Set sourceHTML
  this.sourceHTML = null;
}

/**
 * Obtain the reference frame of the rendering instance.
 * The reference frame will be created if it does not exist.
 * The width and padding size of the reference frame will be
 * configured here.
 * @return {Element} referenceFrame - a reference to the reference frame object
 */
PageRenderer.prototype.getReferenceFrame = function getReferenceFrame() {
  const idOfReferenceFrame = defaultConfig.prefix.reference + this.renderDomId;
  let referenceFrame = this.ownerDocument.getElementById(idOfReferenceFrame);

  // Create a new reference frame if doesn't exist
  if (!referenceFrame) {
    referenceFrame = this.ownerDocument.createElement('DIV');
    referenceFrame.setAttribute('id', idOfReferenceFrame);

    // Set reference frame styling by iterate through the refStyle
    const refStyle = {
      // CSS to hide the reference frame from the user
      position: 'absolute',
      top: 0,
      left: '-99999px',
      zIndex: -99999,
      visibility: 'hidden',
      overflow: 'hidden',
      height: 0,
      boxSizing: 'border-box',

      // CSS to set up the page sizing
      width: this.page.width,
      paddingTop: this.page.padding.top,
      paddingBottom: this.page.padding.bottom,
      paddingLeft: this.page.padding.left,
      paddingRight: this.page.padding.right
    };
    helper.overwriteStyle(referenceFrame.style, refStyle);

    // Render reference frame to DOM
    if (!this.ownerDocument.body) {
      throw new Error('Unable to append referenceFrame to document body');
    }
    this.ownerDocument.body.appendChild(referenceFrame);
  }

  return referenceFrame;
};

// Public instance methods
/**
 * Trigger the rendering process of the pageRenderer instance
 * @return {Promise} promise - to indicate the completion of the rendering process
 */
PageRenderer.prototype.render = function render() {
  return renderCore.updateReferenceFrame(this)
  .then(renderCore.getChildHeights)
  .then(childHeights => renderCore.getPaginationVirtualDom(this, childHeights))
  .then(virtualDom => renderCore.renderPage(this, virtualDom));
};

/**
 * Update the HTML content of the page renderer.
 * This will trigger the rendering process.
 * @param {string} htmlString
 * @return {Promise} promise - to indicate the completion of the rendering process
 */
PageRenderer.prototype.write = function write(htmlString) {
  this.sourceHTML = htmlString;
  return this.render();
};

/**
 * Update the page size of the page renderer.
 * This will trigger the rendering process.
 * @param {pageConfig} htmlString
 * @return {Promise} promise - to indicate the completion of the rendering process
 */
PageRenderer.prototype.updatePageSize = function write(pageConfig) {
  this.page = pageConfig;
  this.renderHeight = helper.computeRenderHeight(this.page);
  return this.render();
};
<|endoftext|>


<commit_before>var roleHarvester = require('role.harvester');
var roleUpgrader = require('role.upgrader');
var roleCivilian = require('role.civilian');
var roleHunter = require('role.hunter');
var roleMiner = require('role.miner');
var roleRunner = require('role.runner');
var roleReserver = require('role.reserver');
var roleRepairer = require('role.repairer');
var remoteUpgrader = require('remote.upgrader');
var remoteHunter = require('remote.hunter');
var roleClaimer = require('role.claimer');
var roleRecycler = require('role.recycler');
var respawn = require('respawn');
var tasks = require('tasks');

module.exports.loop = function(){

    for(var i in Memory.creeps) {
		if(!Game.creeps[i]) {
			delete Memory.creeps[i];
		}
	}

	var myrooms = _.filter(Game.rooms, (r) => r.find(FIND_MY_STRUCTURES, {filter: (s) => s.structureType == STRUCTURE_SPAWN}).length > 0 );
	for(var room of myrooms){
		var towers = room.find(FIND_STRUCTURES, {filter : (structure) => structure.structureType == STRUCTURE_TOWER});
		if(towers.length){
            for(i=0;i<towers.length;i++){
                var tower = towers[i];
                tower.attack(tower.pos.findClosestByRange(FIND_HOSTILE_CREEPS));
                if(tower.energy > 800){
                    tower.repair(tower.pos.findClosestByRange(FIND_STRUCTURES,{filter: (s) => s.structureType == STRUCTURE_RAMPART && s.hits < 5000}));
                    // tower.repair(tower.pos.findClosestByRange(FIND_STRUCTURES, {filter : (structure) => (
                        // structure.structureType != STRUCTURE_WALL && structure.structureType != STRUCTURE_RAMPART && structure.hits < structure.hitsMax) || (
                        // (structure.structureType == STRUCTURE_WALL || structure.structureType == STRUCTURE_RAMPART) && structure.hits < 5000)
                       // })
                    // );
                }
            }
        }
	}

    for(var name in Game.creeps){
        var creep = Game.creeps[name];
		if(creep.memory.role == 'runner'){
			roleRunner.run(creep);
		}
		if(creep.memory.role == 'miner'){
			roleMiner.run(creep);
		}
		if(creep.memory.role == 'upgrader'){
			roleUpgrader.run(creep);
		}
        if(creep.memory.role == 'civilian'){
            roleCivilian.run(creep);
        }
        if(creep.memory.role == 'repairer'){
            roleRepairer.run(creep);
        }
		if(creep.memory.role == 'hunter'){
			roleHunter.run(creep);
		}
		if(creep.memory.role == 'harvester'){
            roleHarvester.run(creep);
        }
		if(creep.memory.role == 'reserver'){
			roleReserver.run(creep);
		}
		if(creep.memroy.role == 'remoteHunter'){
			remoteHunter.run(creep);
		}

		if(creep.memory.role == 'shield'){
		    creep.moveTo(Game.flags['Rally']);
		}
		if(creep.memory.role == 'raider'){
		    if(creep.room.name==Game.flags['Raid'].pos.roomName){
    			targets=Game.flags['Raid'].pos.findInRange(FIND_HOSTILE_STRUCTURES,0,{filter:(s) => s.structureType != STRUCTURE_ROAD && s.structureType != STRUCTURE_CONTROLLER});
    			if (targets.length){
    				target=targets[0]
    			}
    			else{
    				target=Game.flags['Raid'].pos.findClosestByRange(FIND_HOSTILE_CREEPS);
    			}
    			// if(target==null){
    			// 	target=Game.flags['Raid'].pos.findClosestByRange(FIND_HOSTILE_STRUCTURES,{filter:(s) => s.structureType != STRUCTURE_ROAD && s.structureType != STRUCTURE_CONTROLLER});
    			// }
    			if(creep.attack(target) == ERR_NOT_IN_RANGE){
    				creep.moveTo(target);
    			}
		    }
		    else{
		        creep.moveTo(Game.flags['Raid']);
		    }
		}
		if(creep.memory.role == 'thief'){
		    if(creep.carry.energy == creep.carryCapacity && creep.room.name != Game.spawns['Spawn1'].room.name){
			    creep.moveTo(Game.flags['home'],{reusePath:5})
			}
			else if(creep.room.name == Game.spawns['Spawn1'].room.name && creep.carry.energy > 0){
			    tasks.fill(creep,[STRUCTURE_SPAWN,STRUCTURE_EXTENSION,STRUCTURE_STORAGE,STRUCTURE_CONTAINER])
			}
			else if(creep.room.name != Game.flags['Steal'].pos.roomName){
				creep.moveTo(Game.flags['Steal'],{reusePath:5});
			}
			else{
				target=Game.flags['Steal'].pos.findClosestByRange(FIND_HOSTILE_STRUCTURES,{
					filter: (s) => s.energy > 25 || ((s.structureType == STRUCTURE_CONTAINER || s.structureType == STRUCTURE_STORAGE) && s.store.energy > 25)
				});
				if(creep.withdraw(target,RESOURCE_ENERGY) == ERR_NOT_IN_RANGE){
					creep.moveTo(target);
				}
			}
			// creep.say(creep.room.name)
	    }
	    if(creep.memory.role == 'remoteUpgrader'){
	    	remoteUpgrader.run(creep);
	    }
	    if(creep.memory.role == 'claimer'){
	    	roleClaimer.run(creep);
	    }
		if(creep.memory.role == 'recycler'){
			roleRecycler.run(creep);
		}
    }

	respawn.run(myrooms);
}
<commit_msg>minor fix<commit_after>var roleHarvester = require('role.harvester');
var roleUpgrader = require('role.upgrader');
var roleCivilian = require('role.civilian');
var roleHunter = require('role.hunter');
var roleMiner = require('role.miner');
var roleRunner = require('role.runner');
var roleReserver = require('role.reserver');
var roleRepairer = require('role.repairer');
var remoteUpgrader = require('remote.upgrader');
var remoteHunter = require('remote.hunter');
var roleClaimer = require('role.claimer');
var roleRecycler = require('role.recycler');
var respawn = require('respawn');
var tasks = require('tasks');

module.exports.loop = function(){

    for(var i in Memory.creeps) {
		if(!Game.creeps[i]) {
			delete Memory.creeps[i];
		}
	}

	var myrooms = _.filter(Game.rooms, (r) => r.find(FIND_MY_STRUCTURES, {filter: (s) => s.structureType == STRUCTURE_SPAWN}).length > 0 );
	for(var room of myrooms){
		var towers = room.find(FIND_STRUCTURES, {filter : (structure) => structure.structureType == STRUCTURE_TOWER});
		if(towers.length){
            for(i=0;i<towers.length;i++){
                var tower = towers[i];
                tower.attack(tower.pos.findClosestByRange(FIND_HOSTILE_CREEPS));
                if(tower.energy > 800){
                    tower.repair(tower.pos.findClosestByRange(FIND_STRUCTURES,{filter: (s) => s.structureType == STRUCTURE_RAMPART && s.hits < 5000}));
                    // tower.repair(tower.pos.findClosestByRange(FIND_STRUCTURES, {filter : (structure) => (
                        // structure.structureType != STRUCTURE_WALL && structure.structureType != STRUCTURE_RAMPART && structure.hits < structure.hitsMax) || (
                        // (structure.structureType == STRUCTURE_WALL || structure.structureType == STRUCTURE_RAMPART) && structure.hits < 5000)
                       // })
                    // );
                }
            }
        }
	}

    for(var name in Game.creeps){
        var creep = Game.creeps[name];
		if(creep.memory.role == 'runner'){
			roleRunner.run(creep);
		}
		if(creep.memory.role == 'miner'){
			roleMiner.run(creep);
		}
		if(creep.memory.role == 'upgrader'){
			roleUpgrader.run(creep);
		}
        if(creep.memory.role == 'civilian'){
            roleCivilian.run(creep);
        }
        if(creep.memory.role == 'repairer'){
            roleRepairer.run(creep);
        }
		if(creep.memory.role == 'hunter'){
			roleHunter.run(creep);
		}
		if(creep.memory.role == 'harvester'){
            roleHarvester.run(creep);
        }
		if(creep.memory.role == 'reserver'){
			roleReserver.run(creep);
		}
		if(creep.memory.role == 'remoteHunter'){
			remoteHunter.run(creep);
		}

		if(creep.memory.role == 'shield'){
		    creep.moveTo(Game.flags['Rally']);
		}
		if(creep.memory.role == 'raider'){
		    if(creep.room.name==Game.flags['Raid'].pos.roomName){
    			targets=Game.flags['Raid'].pos.findInRange(FIND_HOSTILE_STRUCTURES,0,{filter:(s) => s.structureType != STRUCTURE_ROAD && s.structureType != STRUCTURE_CONTROLLER});
    			if (targets.length){
    				target=targets[0]
    			}
    			else{
    				target=Game.flags['Raid'].pos.findClosestByRange(FIND_HOSTILE_CREEPS);
    			}
    			// if(target==null){
    			// 	target=Game.flags['Raid'].pos.findClosestByRange(FIND_HOSTILE_STRUCTURES,{filter:(s) => s.structureType != STRUCTURE_ROAD && s.structureType != STRUCTURE_CONTROLLER});
    			// }
    			if(creep.attack(target) == ERR_NOT_IN_RANGE){
    				creep.moveTo(target);
    			}
		    }
		    else{
		        creep.moveTo(Game.flags['Raid']);
		    }
		}
		if(creep.memory.role == 'thief'){
		    if(creep.carry.energy == creep.carryCapacity && creep.room.name != Game.spawns['Spawn1'].room.name){
			    creep.moveTo(Game.flags['home'],{reusePath:5})
			}
			else if(creep.room.name == Game.spawns['Spawn1'].room.name && creep.carry.energy > 0){
			    tasks.fill(creep,[STRUCTURE_SPAWN,STRUCTURE_EXTENSION,STRUCTURE_STORAGE,STRUCTURE_CONTAINER])
			}
			else if(creep.room.name != Game.flags['Steal'].pos.roomName){
				creep.moveTo(Game.flags['Steal'],{reusePath:5});
			}
			else{
				target=Game.flags['Steal'].pos.findClosestByRange(FIND_HOSTILE_STRUCTURES,{
					filter: (s) => s.energy > 25 || ((s.structureType == STRUCTURE_CONTAINER || s.structureType == STRUCTURE_STORAGE) && s.store.energy > 25)
				});
				if(creep.withdraw(target,RESOURCE_ENERGY) == ERR_NOT_IN_RANGE){
					creep.moveTo(target);
				}
			}
			// creep.say(creep.room.name)
	    }
	    if(creep.memory.role == 'remoteUpgrader'){
	    	remoteUpgrader.run(creep);
	    }
	    if(creep.memory.role == 'claimer'){
	    	roleClaimer.run(creep);
	    }
		if(creep.memory.role == 'recycler'){
			roleRecycler.run(creep);
		}
    }

	respawn.run(myrooms);
}
<|endoftext|>


<commit_before>//Requires for the other roles and modules

//Roles
var roleHarvester = require('role.harvester');
var roleMiner = require('role.miner');
var roleHauler = require('role.hauler');
var roleUpgrader = require('role.upgrader');
var roleBuilder = require('role.builder');
var roleRepair = require('role.repair');
var roleArchitect = require('role.architect');

//Modules
var modSpawning = require('module.spawning');
var modCommon = require('module.common');
var modStructures = require('module.structures');

//Initial memory JSON for the roles
//includes counters for roles and maxes
var initialRolesMem = {
    "numCreeps":0,
    "numHarvesters":0,
    "maxHarvesters":1,
    "numUpgraders":0,
    "maxUpgraders":0,
    "numBuilders":0,
    "maxBuilders":1,
    "numRepair":0,
    "maxRepair":1,
    "numArchitects":0,
    "betterHarvesters1":0,
    "betterHarvesters2":0,
    "numMiners":0,
    "maxMiners":0,
    "numHaulers":0,
    "maxHaulers":1,
    "conservation":false

};

//Tower initial memory JSON
var initialTowerMem = {
  "target":null,
  "mode":"attack",
  "fixe":null
};

//Set all the above JSONs into memeory on first start
function initialize(){
  Memory.roles = initialRolesMem;
  Memory.towersMem = initialTowerMem;
  Memory.initialized = true;
}

//Gets the number of living harvester Creeps
function getNumHarvesters(creepList){
  var harvesters = _.filter(creepList, (creep) => creep.memory.role == 'harvester');
  var hL = harvesters.length;
  if(Memory.roles.numHarvesters != hL){
    Memory.roles.numHarvesters = hL;
    console.log('Harvesters: ' + hL);
  }
  return hL;
}

//Gets the number of living upgrader Creeps
function getNumUpgraders(creepList){
  var upgraders = _.filter(creepList, (creep) => creep.memory.role == 'upgrader');
  var uL = upgraders.length;
  if(Memory.roles.numUpgraders != uL){
    Memory.roles.numUpgraders = uL;
    console.log('Upgraders: ' + uL);
  }
  return uL;
}

//Gets the number of living builder Creeps
function getNumBuilders(creepList){
  var builders = _.filter(creepList, (creep) => creep.memory.role == 'builder');
  var bL = builders.length;
  if(Memory.roles.numBuilders != bL){
    Memory.roles.numBuilders = bL;
    console.log('Builders: ' + bL);
  }
  return bL;
}

//Gets the number of living Repair Creeps
function getNumRepair(creepList){
  var repair = _.filter(creepList, (creep) => creep.memory.role == 'repair');
  var rL = repair.length;
  if(Memory.roles.numRepair != rL){
    Memory.roles.numRepair = rL;
    console.log('Repair: ' + rL);
  }
  return rL;
}

//Gets the number of living architect Creeps
function getNumArchitects(creepList){
  var architects = _.filter(creepList, (creep) => creep.memory.role == 'architect');
  var aL = architects.length;
  if(Memory.roles.numArchitects != aL){
    Memory.roles.numArchitects = aL;
    console.log('Architects: ' + aL);
  }
  return aL;
}

//Gets the number of living miner Creeps
function getNumMiners(creepList){
  var miners = _.filter(creepList, (creep) => creep.memory.role == 'miner');
  var mL = miners.length;
  if(Memory.roles.numMiners != mL){
    Memory.roles.numMiners = mL;
    console.log('Miners: ' + mL);
  }
  return mL;
}

//Gets the number of living hauler Creeps
function getNumHaulers(creepList){
  var haulers = _.filter(creepList, (creep) => creep.memory.role == 'hauler');
  var haulL = haulers.length;
  if(Memory.roles.numHaulers != haulL){
    Memory.roles.numHaulers = haulL;
    console.log('Haulers: ' + haulL);
  }
  return haulL;
}

//main loop
module.exports.loop = function () {

  //Only initialize if it hasnt been done (or it was manually set to false)
  if(Memory.initialized!==true){
    initialize();
  }

  //Loop to check each room that is visible to the script
  for(var roomName in Game.rooms){
    var room = Game.rooms[roomName];

    //Creep lists in each room, comparing lengths shows if there are 'others'
    //TODO check if filter is faster than just Game.creeps
    var allCreepList = room.find(FIND_CREEPS);
    var myCreepList = _.filter(allCreepList, (creep) => (creep.owner && creep.owner.username ==="PCarton"));
    var enemyPresent = allCreepList.length>myCreepList.length;

    //Al the structures in the room that are controlled by the player
    var allStructs = room.find(FIND_MY_STRUCTURES);
    var towers = _.filter(allStructs, (struct) => struct.structureType === STRUCTURE_TOWER);

    //calculates the breakdown of creeps by roles
    var h  = getNumHarvesters(myCreepList);
    var u = getNumUpgraders(myCreepList);
    var b = getNumBuilders(myCreepList);
    var r = getNumRepair(myCreepList);
    var a = getNumArchitects(myCreepList);
    var m = getNumMiners(myCreepList);
    var ha = getNumHaulers(myCreepList);
    Memory.roles.numCreeps = h + u + b + r + a + m + ha;

    //Clear dead creeps from memory
    modCommon.clearDead();

    //assign the right run method to each creep based on its role
    for(var name in myCreepList) {
        var creep = myCreepList[name];

        //Has the non-military creeps retreat
        //Mining creeps are considered military - like the supply line
        if(enemyPresent && creep.memory.military !== true){
          modCommon.retreat(creep);
        }
        //If there are no enemies, run the appropriate role method
        else if(creep.memory.role == 'harvester') {
            roleHarvester.run(creep);
        }
        else if(creep.memory.role == 'upgrader') {
            roleUpgrader.run(creep);
        }
        else if(creep.memory.role == 'builder'){
          roleBuilder.run(creep);
        }
        else if(creep.memory.role == 'repair'){
          roleRepair.run(creep);
        }
        else if(creep.memory.role == 'architect'){
          roleArchitect.run(creep);
        }
        else if(creep.memory.role == 'miner'){
          roleMiner.run(creep);
        }
        else if(creep.memory.role == 'hauler'){
          roleHauler.run(creep);
        }
    }

    //determine if new creeps need to be spawned and pick an appropriate spawner
    //Spawn logic is in a seperate module
    if(Memory.roles.numCreeps < modSpawning.maxCreeps){
        for(var spawn in Game.spawns){
          var spawner = Game.spawns[spawn];
          var controllerLvl= spawner.room.controller.level;
          var energyCapacity = spawner.room.energyCapacityAvailable;
          modSpawning.spawn(spawner,energyCapacity,controllerLvl);

        }
    }

    var control = room.controller;

    if(enemyPresent && modCommon.playerAttack(allCreepList) && !(control.safeMode || control.safeModeCooldown) && control.safeModeAvailable > 0 ){
      control.activateSafeMode();
    }

    //Variable to keep track of which enemy to shoot
    var target = Game.getObjectById(Memory.towersMem.target);

    //Notify the user on enemies or switch to healing and repairing
    if(enemyPresent){
      Memory.towersMem.mode = "attack";
      Game.notify("EnemyFound at "+ Game.time.toString(),60);
    }else{
      Memory.towersMem.mode = "heal";
    }

    //Run through the towers, picking a target if needed
    for(var towerName in towers){
      var t = towers[towerName];
      if(enemyPresent && (target===null || target.room !== t.room)){
        modStructures.pickTargets(t.room.controller, allCreepList);
      }
      modStructures.runTower(t);
    }
  }
};
<commit_msg>fixed wrong placement of conservation memory value<commit_after>//Requires for the other roles and modules

//Roles
var roleHarvester = require('role.harvester');
var roleMiner = require('role.miner');
var roleHauler = require('role.hauler');
var roleUpgrader = require('role.upgrader');
var roleBuilder = require('role.builder');
var roleRepair = require('role.repair');
var roleArchitect = require('role.architect');

//Modules
var modSpawning = require('module.spawning');
var modCommon = require('module.common');
var modStructures = require('module.structures');

//Initial memory JSON for the roles
//includes counters for roles and maxes
var initialRolesMem = {
    "numCreeps":0,
    "numHarvesters":0,
    "maxHarvesters":1,
    "numUpgraders":0,
    "maxUpgraders":0,
    "numBuilders":0,
    "maxBuilders":1,
    "numRepair":0,
    "maxRepair":1,
    "numArchitects":0,
    "betterHarvesters1":0,
    "betterHarvesters2":0,
    "numMiners":0,
    "maxMiners":0,
    "numHaulers":0,
    "maxHaulers":1

};

//Tower initial memory JSON
var initialTowerMem = {
  "target":null,
  "mode":"attack",
  "fixe":null
};

//Set all the above JSONs into memeory on first start
function initialize(){
  Memory.roles = initialRolesMem;
  Memory.towersMem = initialTowerMem;
  Memory.initialized = true;
  Memory.conservation = false;
}

//Gets the number of living harvester Creeps
function getNumHarvesters(creepList){
  var harvesters = _.filter(creepList, (creep) => creep.memory.role == 'harvester');
  var hL = harvesters.length;
  if(Memory.roles.numHarvesters != hL){
    Memory.roles.numHarvesters = hL;
    console.log('Harvesters: ' + hL);
  }
  return hL;
}

//Gets the number of living upgrader Creeps
function getNumUpgraders(creepList){
  var upgraders = _.filter(creepList, (creep) => creep.memory.role == 'upgrader');
  var uL = upgraders.length;
  if(Memory.roles.numUpgraders != uL){
    Memory.roles.numUpgraders = uL;
    console.log('Upgraders: ' + uL);
  }
  return uL;
}

//Gets the number of living builder Creeps
function getNumBuilders(creepList){
  var builders = _.filter(creepList, (creep) => creep.memory.role == 'builder');
  var bL = builders.length;
  if(Memory.roles.numBuilders != bL){
    Memory.roles.numBuilders = bL;
    console.log('Builders: ' + bL);
  }
  return bL;
}

//Gets the number of living Repair Creeps
function getNumRepair(creepList){
  var repair = _.filter(creepList, (creep) => creep.memory.role == 'repair');
  var rL = repair.length;
  if(Memory.roles.numRepair != rL){
    Memory.roles.numRepair = rL;
    console.log('Repair: ' + rL);
  }
  return rL;
}

//Gets the number of living architect Creeps
function getNumArchitects(creepList){
  var architects = _.filter(creepList, (creep) => creep.memory.role == 'architect');
  var aL = architects.length;
  if(Memory.roles.numArchitects != aL){
    Memory.roles.numArchitects = aL;
    console.log('Architects: ' + aL);
  }
  return aL;
}

//Gets the number of living miner Creeps
function getNumMiners(creepList){
  var miners = _.filter(creepList, (creep) => creep.memory.role == 'miner');
  var mL = miners.length;
  if(Memory.roles.numMiners != mL){
    Memory.roles.numMiners = mL;
    console.log('Miners: ' + mL);
  }
  return mL;
}

//Gets the number of living hauler Creeps
function getNumHaulers(creepList){
  var haulers = _.filter(creepList, (creep) => creep.memory.role == 'hauler');
  var haulL = haulers.length;
  if(Memory.roles.numHaulers != haulL){
    Memory.roles.numHaulers = haulL;
    console.log('Haulers: ' + haulL);
  }
  return haulL;
}

//main loop
module.exports.loop = function () {

  //Only initialize if it hasnt been done (or it was manually set to false)
  if(Memory.initialized!==true){
    initialize();
  }

  //Loop to check each room that is visible to the script
  for(var roomName in Game.rooms){
    var room = Game.rooms[roomName];

    //Creep lists in each room, comparing lengths shows if there are 'others'
    //TODO check if filter is faster than just Game.creeps
    var allCreepList = room.find(FIND_CREEPS);
    var myCreepList = _.filter(allCreepList, (creep) => (creep.owner && creep.owner.username ==="PCarton"));
    var enemyPresent = allCreepList.length>myCreepList.length;

    //Al the structures in the room that are controlled by the player
    var allStructs = room.find(FIND_MY_STRUCTURES);
    var towers = _.filter(allStructs, (struct) => struct.structureType === STRUCTURE_TOWER);

    //calculates the breakdown of creeps by roles
    var h  = getNumHarvesters(myCreepList);
    var u = getNumUpgraders(myCreepList);
    var b = getNumBuilders(myCreepList);
    var r = getNumRepair(myCreepList);
    var a = getNumArchitects(myCreepList);
    var m = getNumMiners(myCreepList);
    var ha = getNumHaulers(myCreepList);
    Memory.roles.numCreeps = h + u + b + r + a + m + ha;

    //Clear dead creeps from memory
    modCommon.clearDead();

    //assign the right run method to each creep based on its role
    for(var name in myCreepList) {
        var creep = myCreepList[name];

        //Has the non-military creeps retreat
        //Mining creeps are considered military - like the supply line
        if(enemyPresent && creep.memory.military !== true){
          modCommon.retreat(creep);
        }
        //If there are no enemies, run the appropriate role method
        else if(creep.memory.role == 'harvester') {
            roleHarvester.run(creep);
        }
        else if(creep.memory.role == 'upgrader') {
            roleUpgrader.run(creep);
        }
        else if(creep.memory.role == 'builder'){
          roleBuilder.run(creep);
        }
        else if(creep.memory.role == 'repair'){
          roleRepair.run(creep);
        }
        else if(creep.memory.role == 'architect'){
          roleArchitect.run(creep);
        }
        else if(creep.memory.role == 'miner'){
          roleMiner.run(creep);
        }
        else if(creep.memory.role == 'hauler'){
          roleHauler.run(creep);
        }
    }

    //determine if new creeps need to be spawned and pick an appropriate spawner
    //Spawn logic is in a seperate module
    if(Memory.roles.numCreeps < modSpawning.maxCreeps){
        for(var spawn in Game.spawns){
          var spawner = Game.spawns[spawn];
          var controllerLvl= spawner.room.controller.level;
          var energyCapacity = spawner.room.energyCapacityAvailable;
          modSpawning.spawn(spawner,energyCapacity,controllerLvl);

        }
    }

    var control = room.controller;

    if(enemyPresent && modCommon.playerAttack(allCreepList) && !(control.safeMode || control.safeModeCooldown) && control.safeModeAvailable > 0 ){
      control.activateSafeMode();
    }

    //Variable to keep track of which enemy to shoot
    var target = Game.getObjectById(Memory.towersMem.target);

    //Notify the user on enemies or switch to healing and repairing
    if(enemyPresent){
      Memory.towersMem.mode = "attack";
      Game.notify("EnemyFound at "+ Game.time.toString(),60);
    }else{
      Memory.towersMem.mode = "heal";
    }

    //Run through the towers, picking a target if needed
    for(var towerName in towers){
      var t = towers[towerName];
      if(enemyPresent && (target===null || target.room !== t.room)){
        modStructures.pickTargets(t.room.controller, allCreepList);
      }
      modStructures.runTower(t);
    }
  }
};
<|endoftext|>


<commit_before>/**
 * Created by phinome on 3/31/15.
 * @description: A collection of snippets functions
 *
 */

"use strict";

var proxy = function(func , thisObject) {
    return (
        function() {
            return func.apply(thisObject,arguments);
        }
    )
};

/**
 * 循环遍历数组集合
 *
 * @inner
 * @param {Array} source 数组源
 * @param {function(Array,Number):boolean} iterator 遍历函数
 */
var each = function(source, iterator) {
    if (source instanceof Array) {
        for (var i = 0, len = source.length; i < len; i++) {
            if (iterator(source[i], i) === false) {
                break;
            }
        }
    }
};

var currentlyAddingScript;
var interactiveScript;
var headElement = document.getELementsByTagNames( 'head' )[0];
var baseElement = document.getElementsByTagNames( 'base' )[0];

if( baseElement ) {
    headElement = baseElement.parentNode;
}

var createScript = function( id , onload ) {
// 创建 script 标签
//
// 不再挂接 onerror 的错误处理
// 因为高级浏览器在 devtool 的 console 面板会报错
// 再 throw 一个 Error 多此一举了
var script = document.createElement('script');
script.setAttribute( 'data-require-id', id );
script.src = toUrl( id + '.js' );
script.async = true;

if( script.readystate ) {
    script.onreadystatechange = innerOnload;
} else {
    script.onload = innerOnload;
}

function innerOnload() {
    var readyState = script.readyState;

    if(
        typeof readyState === 'undefined'
        || /^( loaded|complete )$.test( readyState )
    ) {
        script.onload = script.onreadystatechange = null;
        script = null;
    }

    currentlyAddingScript = script;

    // if BASE tag is in play, using appendChild is a problem for IE6
    // see: http://dev.jquery.com/ticket/2709
   baseElement
        ? headElement.insertBefore( script, baseElement )
        : headElement.appendChild( script );

   currentlyAddingScript = null;

};

/**
 * 获取当前script标签
 * 用于ie下define未指定module id时获取id
 *
 * @inner
 * @return {HTMLScriptElement} 当前script标签
 */

<commit_msg>add inherits & extend function<commit_after>/**
 * Created by phinome on 3/31/15.
 * @description: A collection of snippets functions
 *
 */

"use strict";

var proxy = function(func , thisObject) {
    return (
        function() {
            return func.apply(thisObject,arguments);
        }
    )
};

var extend = function(source, target) {
    for(var p in source) {
        target[p] = source[p];
    }

    return target;
};

var inherits = function(subClazz, superClazz, type) {
    var key,
        proto,
        selfProps = subClazz.prototype,
        clazz = new Function();

    clazz.prototype = superClazz.prototype;
    proto = subClazz.prototype = new clazz();

    for(key in selfProps) {
        clazz[key] = selfProps[key];
    }

    subClazz.prototype.constructor = subClazz;
    subClazz.superClass = superClazz.prototype;

    typeof type === "string" && (proto.__type = type);

    subClazz.extend = function(json) {
        for(var i in json) {
            proto[i] = json[i];
        }
        return subClazz;
    }
    return subClazz;
};

/**
 * 循环遍历数组集合
 *
 * @inner
 * @param {Array} source 数组源
 * @param {function(Array,Number):boolean} iterator 遍历函数
 */
var each = function(source, iterator) {
    if (source instanceof Array) {
        for (var i = 0, len = source.length; i < len; i++) {
            if (iterator(source[i], i) === false) {
                break;
            }
        }
    }
};

var currentlyAddingScript;
var interactiveScript;
var headElement = document.getELementsByTagNames( 'head' )[0];
var baseElement = document.getElementsByTagNames( 'base' )[0];

if( baseElement ) {
    headElement = baseElement.parentNode;
}

var createScript = function( id , onload ) {
// 创建 script 标签
//
// 不再挂接 onerror 的错误处理
// 因为高级浏览器在 devtool 的 console 面板会报错
// 再 throw 一个 Error 多此一举了
var script = document.createElement('script');
script.setAttribute( 'data-require-id', id );
script.src = toUrl( id + '.js' );
script.async = true;

if( script.readystate ) {
    script.onreadystatechange = innerOnload;
} else {
    script.onload = innerOnload;
}

function innerOnload() {
    var readyState = script.readyState;

    if(
        typeof readyState === 'undefined'
        || /^( loaded|complete )$.test( readyState )
    ) {
        script.onload = script.onreadystatechange = null;
        script = null;
    }

    currentlyAddingScript = script;

    // if BASE tag is in play, using appendChild is a problem for IE6
    // see: http://dev.jquery.com/ticket/2709
   baseElement
        ? headElement.insertBefore( script, baseElement )
        : headElement.appendChild( script );

   currentlyAddingScript = null;

};

/**
 * 获取当前script标签
 * 用于ie下define未指定module id时获取id
 *
 * @inner
 * @return {HTMLScriptElement} 当前script标签
 */

<|endoftext|>