<commit_before>$(document).ready(function(){
    var nofinv = 1;
    $('#id_invoicenumber').addClass('invoice'+' '+nofinv);
    $('#id_invoicestatus').addClass('invoiceadditional'+' '+nofinv);

    $('#trbutton').on('click', function(){
	$('#trbutton').fadeOut('slow', function(){
	    $('#trform').fadeIn('slow');
	    $('#ptrack').html('Please fill in all the fields.');
	});
    });

    $('#id_reminderdate').datepicker();
    $('.paid:first').datepicker();

    var $name = $('#vclerk').attr('value');
    $('#id_clerk').val($name);

    $('#id_clerk').attr('readonly', true);
    $('#id_actiondate').attr('readonly', true);

    $('#id_market').on('change', function(){
	$('#id_ccode option').each(function(){
	    $(this).show();
	});

	var market = $('#id_market').val();
	if (market == 'IT') {
	    var marketArray = ['', '11', '13', '15', '16'];
	} else if (market == 'DE') {
	    var marketArray = ['', '13', '52', '55', '60', '64', '66'];
	} else if (market == 'PT' || market == 'PL' || market == 'NL' || market == 'NO') {
	    var marketArray = ['', '10'];
	} else if (market == 'BE') {
	    var marketArray = ['', '12', '14', '18', '31'];
	} else if (market == 'SE') {
	    var marketArray = ['', '16'];
	} else if (market == 'FI') {
	    var marketArray = ['', '11'];
	} else if (market == 'DK') {
	    var marketArray = ['', '12'];
	} else {
	    return false;
	}

	$('#id_ccode option').each(function(){
	    var ccodeOpt = $(this).val();
	    if ($.inArray(ccodeOpt, marketArray) > -1){
		;
	    } else {
		$(this).hide();
	    }
	});

    });

    $(document).on('change', '.status', function() {
	var status = $(this).val();

	if ($('#rejpaidform').is(':hidden')){
	    ;
	} else {
	    $('#rejpaidform').hide();
	    if ($('#id_paidon').is(':hidden')) {$('#id_paidon').show()};
	    if ($('#id_rejectreason').is(':hidden')) {$('#id_rejectreason').show()};
	    $('#rejpaidform').find('label').show();
	}

	if (status == 'RJ'){
	    $('#id_paidon').hide();
	    $('#rejpaidform').find('label:last').hide();
	    $('#rejpaidform').fadeIn('slow');
	} else if (status == 'PD') {
	    $('#id_rejectreason').hide();
	    $('#rejpaidform').find('label:first').hide();
	    $('#rejpaidform').fadeIn('slow');
	};
    });
});
<commit_msg>Get the hidden form.  Traversing up to the parent of the non hidden form and going down to the next element (the form we want).<commit_after>$(document).ready(function(){
    var nofinv = 1;
    $('#id_invoicenumber').addClass('invoice'+' '+nofinv);
    $('#id_invoicestatus').addClass('invoiceadditional'+' '+nofinv);

    $('#trbutton').on('click', function(){
	$('#trbutton').fadeOut('slow', function(){
	    $('#trform').fadeIn('slow');
	    $('#ptrack').html('Please fill in all the fields.');
	});
    });

    $('#id_reminderdate').datepicker();
    $('.paid:first').datepicker();

    var $name = $('#vclerk').attr('value');
    $('#id_clerk').val($name);

    $('#id_clerk').attr('readonly', true);
    $('#id_actiondate').attr('readonly', true);

    $('#id_market').on('change', function(){
	$('#id_ccode option').each(function(){
	    $(this).show();
	});

	var market = $('#id_market').val();
	if (market == 'IT') {
	    var marketArray = ['', '11', '13', '15', '16'];
	} else if (market == 'DE') {
	    var marketArray = ['', '13', '52', '55', '60', '64', '66'];
	} else if (market == 'PT' || market == 'PL' || market == 'NL' || market == 'NO') {
	    var marketArray = ['', '10'];
	} else if (market == 'BE') {
	    var marketArray = ['', '12', '14', '18', '31'];
	} else if (market == 'SE') {
	    var marketArray = ['', '16'];
	} else if (market == 'FI') {
	    var marketArray = ['', '11'];
	} else if (market == 'DK') {
	    var marketArray = ['', '12'];
	} else {
	    return false;
	}

	$('#id_ccode option').each(function(){
	    var ccodeOpt = $(this).val();
	    if ($.inArray(ccodeOpt, marketArray) > -1){
		;
	    } else {
		$(this).hide();
	    }
	});

    });

    $(document).on('change', '.status', function() {
	var status = $(this).val();
	var nextform = $(this).parent().parent().parent().next();

	if ($('#rejpaidform').is(':hidden')){
	    ;
	} else {
	    $('#rejpaidform').hide();
	    if ($('#id_paidon').is(':hidden')) {$('#id_paidon').show()};
	    if ($('#id_rejectreason').is(':hidden')) {$('#id_rejectreason').show()};
	    $('#rejpaidform').find('label').show();
	}

	if (status == 'RJ'){
	    $('#id_paidon').hide();
	    $('#rejpaidform').find('label:last').hide();
	    $('#rejpaidform').fadeIn('slow');
	} else if (status == 'PD') {
	    $('#id_rejectreason').hide();
	    $('#rejpaidform').find('label:first').hide();
	    $('#rejpaidform').fadeIn('slow');
	};
    });
});
<|endoftext|>


<commit_before>"use strict";

// TODO: This is a temp solution that will
// be eventually replaced by the restrictions table.

var URI = require('hyperswitch').URI;
var mwUtil = require('./mwUtil');
var entities = require('entities');
var P = require('bluebird');

var redirectRegEx = /<link rel="mw:PageProp\/redirect" href="\.\/([^"#]+)(?:#[^"]*)?"/;

module.exports = function(hyper, req, next, options, specInfo) {
    var rp = req.params;
    var titleName = options.title ? options.title : 'title';
    var checkURIParts = [rp.domain, 'sys', 'page_revisions', 'page', rp[titleName]];
    if (rp.revision) {
        checkURIParts.push('' + rp.revision);
    }

    return hyper.get({ uri: new URI(checkURIParts) })
    .then(function(res) {
        var revision = res.body.items[0];

        if (revision.redirect
                && req.query.redirect !== false
                && !mwUtil.isNoCacheRequest(req)) {
            var htmlPath = [rp.domain, 'sys', 'parsoid', 'html', rp[titleName]];
            if (rp.revision) {
                htmlPath.push('' + rp.revision);
                if (rp.tid) {
                    htmlPath.push('' + rp.tid);
                }
            }
            return hyper.get({
                uri: new URI(htmlPath),
                headers: req.headers
            })
            .then(function(html) {
                var redirectMatch = redirectRegEx.exec(html.body);
                if (redirectMatch) {
                    var newParams = Object.assign({}, rp);
                    newParams[titleName] = decodeURIComponent(entities.decodeXML(redirectMatch[1]));
                    var location = mwUtil.createRelativeTitleRedirect(specInfo.path,
                        req, newParams, titleName);

                    var contentPromise;
                    if (options.attach_body_to_redirect) {
                        if (specInfo.path.indexOf('html') !== -1) {
                            contentPromise = P.resolve(html);
                        } else {
                            contentPromise = next(hyper, req);
                        }
                    } else {
                        contentPromise = P.resolve({
                            headers: {
                                etag: html.headers.etag
                            }
                        });
                    }
                    return contentPromise.then(function(content) {
                        return {
                            status: 302,
                            headers: Object.assign(content.headers, {
                                location: location,
                                'cache-control': options.redirect_cache_control || 'no-cache'
                            }),
                            body: content.body
                        };
                    });
                } else {
                    return next(hyper, req);
                }
            });
        }
        return next(hyper, req);
    });
};
<commit_msg>Bug fix: Don't propagate the cache-control header on redirect detection (#604)<commit_after>"use strict";

// TODO: This is a temp solution that will
// be eventually replaced by the restrictions table.

var URI = require('hyperswitch').URI;
var mwUtil = require('./mwUtil');
var entities = require('entities');
var P = require('bluebird');

var redirectRegEx = /<link rel="mw:PageProp\/redirect" href="\.\/([^"#]+)(?:#[^"]*)?"/;

module.exports = function(hyper, req, next, options, specInfo) {
    var rp = req.params;
    var titleName = options.title ? options.title : 'title';
    var checkURIParts = [rp.domain, 'sys', 'page_revisions', 'page', rp[titleName]];
    if (rp.revision) {
        checkURIParts.push('' + rp.revision);
    }

    return hyper.get({ uri: new URI(checkURIParts) })
    .then(function(res) {
        var revision = res.body.items[0];

        if (revision.redirect
                && req.query.redirect !== false
                && !mwUtil.isNoCacheRequest(req)) {
            var htmlPath = [rp.domain, 'sys', 'parsoid', 'html', rp[titleName]];
            if (rp.revision) {
                htmlPath.push('' + rp.revision);
                if (rp.tid) {
                    htmlPath.push('' + rp.tid);
                }
            }
            return hyper.get({
                uri: new URI(htmlPath),
                /* TODO FIXME TEMP
                 * This removes the cache-control header when requesting the HTML
                 * for redirect inspection. However, this is a temporary hack in
                 * order to avoid re-renders for no-cache requests. We need to
                 * implement a proper header inspection routine.
                 */
                headers: Object.assign({}, req.headers, { 'cache-control': undefined })
            })
            .then(function(html) {
                var redirectMatch = redirectRegEx.exec(html.body);
                if (redirectMatch) {
                    var newParams = Object.assign({}, rp);
                    newParams[titleName] = decodeURIComponent(entities.decodeXML(redirectMatch[1]));
                    var location = mwUtil.createRelativeTitleRedirect(specInfo.path,
                        req, newParams, titleName);

                    var contentPromise;
                    if (options.attach_body_to_redirect) {
                        if (specInfo.path.indexOf('html') !== -1) {
                            contentPromise = P.resolve(html);
                        } else {
                            contentPromise = next(hyper, req);
                        }
                    } else {
                        contentPromise = P.resolve({
                            headers: {
                                etag: html.headers.etag
                            }
                        });
                    }
                    return contentPromise.then(function(content) {
                        return {
                            status: 302,
                            headers: Object.assign(content.headers, {
                                location: location,
                                'cache-control': options.redirect_cache_control || 'no-cache'
                            }),
                            body: content.body
                        };
                    });
                } else {
                    return next(hyper, req);
                }
            });
        }
        return next(hyper, req);
    });
};
<|endoftext|>


<commit_before>const fsStore = require('cache-manager-fs');
const requestPlus = require('request-plus');
const cacheManager = require('cache-manager');
const delay = 10000;
const ttl = 48 * 60 * 60; // seconds
const cacheReady = new Promise(
    function (resolve) {
        const cache = cacheManager.caching({
            store: fsStore,
            options: {
                ttl,
                maxsize: 100e6 /* max size in bytes on disk */,
                fillcallback: () => resolve(cache),
            },
        });
    }
).then(cache => requestPlus({
    cache: {cache},
    retry: {
        attempts: 3,
        delay,
    },
}));

function pause(result) {
    return new Promise(function (resolve) {
        setTimeout(() => resolve(result), delay);
    });
}

module.exports = function (uri, options) {
    if (typeof uri === 'string') {
        options = {uri};
    }
    else {
        options.uri = uri;
    }
    options.transform = pause;
    return cacheReady.then(rp => rp(options));
};
<commit_msg>fix options handling in request.js<commit_after>const fsStore = require('cache-manager-fs');
const requestPlus = require('request-plus');
const cacheManager = require('cache-manager');
const delay = 10000;
const ttl = 48 * 60 * 60; // seconds
const cacheReady = new Promise(
    function (resolve) {
        const cache = cacheManager.caching({
            store: fsStore,
            options: {
                ttl,
                maxsize: 100e6 /* max size in bytes on disk */,
                fillcallback: () => resolve(cache),
            },
        });
    }
).then(cache => requestPlus({
    cache: {cache},
    retry: {
        attempts: 3,
        delay,
    },
}));

function pause(result) {
    return new Promise(function (resolve) {
        setTimeout(() => resolve(result), delay);
    });
}

module.exports = function (uri, options = {}) {
    if (typeof uri === 'string') {
        options.uri = uri;
    }
    else {
        options = uri;
    }
    options.transform = pause;
    return cacheReady.then(rp => rp(options));
};
<|endoftext|>


<commit_before><commit_msg>Deleted unused games.js example<commit_after><|endoftext|>


<commit_before>// jQuery Context Menu Plugin
//
// Version 1.01
//
// Cory S.N. LaViska
// A Beautiful Site (http://abeautifulsite.net/)
//
// Modifications by Alexis Deveria
//
// More info: http://abeautifulsite.net/2008/09/jquery-context-menu-plugin/
//
// Terms of Use
//
// This plugin is dual-licensed under the GNU General Public License
//   and the MIT License and is copyright A Beautiful Site, LLC.
//
jQuery&&function(){var i=$(window),e=$(document);$.extend($.fn,{contextMenu:function(a,d){if(a.menu==undefined)return false;if(a.inSpeed==undefined)a.inSpeed=150;if(a.outSpeed==undefined)a.outSpeed=75;if(a.inSpeed==0)a.inSpeed=-1;if(a.outSpeed==0)a.outSpeed=-1;$(this).each(function(){var c=$(this),j=$(c).offset(),b=$("#"+a.menu);b.addClass("contextMenu");$(this).mousedown(function(m){$(this).mouseup(function(f){var k=$(this);k.unbind("mouseup");if(m.button===2||a.allowLeft){f.stopPropagation();$(".contextMenu").hide();
if(c.hasClass("disabled"))return false;var g=f.pageX,h=f.pageY;f=i.width()-b.width();var l=i.height()-b.height();if(g>f-15)g=f-15;if(h>l-30)h=l-30;e.unbind("click");b.css({top:h,left:g}).fadeIn(a.inSpeed);b.find("A").mouseover(function(){b.find("LI.hover").removeClass("hover");$(this).parent().addClass("hover")}).mouseout(function(){b.find("LI.hover").removeClass("hover")});e.keypress(function(n){switch(n.keyCode){case 38:if(b.find("LI.hover").length){b.find("LI.hover").removeClass("hover").prevAll("LI:not(.disabled)").eq(0).addClass("hover");
b.find("LI.hover").length||b.find("LI:last").addClass("hover")}else b.find("LI:last").addClass("hover");break;case 40:if(b.find("LI.hover").length==0)b.find("LI:first").addClass("hover");else{b.find("LI.hover").removeClass("hover").nextAll("LI:not(.disabled)").eq(0).addClass("hover");b.find("LI.hover").length||b.find("LI:first").addClass("hover")}break;case 13:b.find("LI.hover A").trigger("click");break;case 27:e.trigger("click")}});b.find("A").unbind("mouseup");b.find("LI:not(.disabled) A").mouseup(function(){e.unbind("click").unbind("keypress");
$(".contextMenu").hide();d&&d($(this).attr("href").substr(1),$(k),{x:g-j.left,y:h-j.top,docX:g,docY:h});return false});setTimeout(function(){e.click(function(){e.unbind("click").unbind("keypress");b.fadeOut(a.outSpeed);return false})},0)}})});if($.browser.mozilla)$("#"+a.menu).each(function(){$(this).css({MozUserSelect:"none"})});else $.browser.msie?$("#"+a.menu).each(function(){$(this).bind("selectstart.disableTextSelect",function(){return false})}):$("#"+a.menu).each(function(){$(this).bind("mousedown.disableTextSelect",
function(){return false})});$(c).add($("UL.contextMenu")).bind("contextmenu",function(){return false})});return $(this)},disableContextMenuItems:function(a){if(a==undefined){$(this).find("LI").addClass("disabled");return $(this)}$(this).each(function(){if(a!=undefined)for(var d=a.split(","),c=0;c<d.length;c++)$(this).find('A[href="'+d[c]+'"]').parent().addClass("disabled")});return $(this)},enableContextMenuItems:function(a){if(a==undefined){$(this).find("LI.disabled").removeClass("disabled");return $(this)}$(this).each(function(){if(a!=
undefined)for(var d=a.split(","),c=0;c<d.length;c++)$(this).find('A[href="'+d[c]+'"]').parent().removeClass("disabled")});return $(this)},disableContextMenu:function(){$(this).each(function(){$(this).addClass("disabled")});return $(this)},enableContextMenu:function(){$(this).each(function(){$(this).removeClass("disabled")});return $(this)},destroyContextMenu:function(){$(this).each(function(){$(this).unbind("mousedown").unbind("mouseup")});return $(this)}})}(jQuery);<commit_msg>Remove minified file as it is no longer used<commit_after><|endoftext|>


<commit_before>(function() {
  'use strict';

  var globals = typeof window === 'undefined' ? global : window;
  if (typeof globals.require === 'function') return;

  var modules = {};
  var cache = {};
  var aliases = {};
  var has = ({}).hasOwnProperty;

  var expRe = /^\.\.?(\/|$)/;
  var expand = function(root, name) {
    var results = [], part;
    var parts = (expRe.test(name) ? root + '/' + name : name).split('/');
    for (var i = 0, length = parts.length; i < length; i++) {
      part = parts[i];
      if (part === '..') {
        results.pop();
      } else if (part !== '.' && part !== '') {
        results.push(part);
      }
    }
    return results.join('/');
  };

  var dirname = function(path) {
    return path.split('/').slice(0, -1).join('/');
  };

  var localRequire = function(path) {
    return function expanded(name) {
      var absolute = expand(dirname(path), name);
      return globals.require(absolute, path);
    };
  };

  var initModule = function(name, definition) {
    var module = {id: name, exports: {}};
    cache[name] = module;
    definition(module.exports, localRequire(name), module);
    return module.exports;
  };

  var expandAlias = function(name) {
    return aliases[name] ? expandAlias(aliases[name]) : name;
  };

  var require = function(name, loaderPath) {
    if (loaderPath == null) loaderPath = '/';
    var path = expandAlias(name);

    if (has.call(cache, path)) return cache[path].exports;
    if (has.call(modules, path)) return initModule(path, modules[path]);

    throw new Error('Cannot find module "' + name + '" from ' + '"' + loaderPath + '"');
  };

  require.alias = function(from, to) {
    aliases[to] = from;
  };

  require.reset = function() {
    modules = {};
    cache = {};
    aliases = {};
  };

  var extRe = /\.[^.\/]+$/;
  var indexRe = /\/index(\.[^\/]+)?$/;
  var addExtensions = function(bundle) {
    var alias = bundle;
    while (extRe.test(alias)) {
      alias = alias.replace(extRe, '');
      if (!has.call(aliases, alias) || aliases[alias].replace(extRe, '') === alias + '/index' || bundle === alias + '.js') {
        aliases[alias] = bundle;
      }
    }

    if (indexRe.test(bundle)) {
      var iAlias = bundle.replace(indexRe, '');
      if (!has.call(aliases, iAlias)) {
        aliases[iAlias] = bundle;
      }
    }
  };

  require.register = require.define = function(bundle, fn) {
    if (typeof bundle === 'object') {
      for (var key in bundle) {
        if (has.call(bundle, key)) {
          require.register(key, bundle[key]);
        }
      }
    } else {
      modules[bundle] = fn;
      delete cache[bundle];
      addExtensions(bundle);
    }
  };

  require.list = function() {
    var result = [];
    for (var item in modules) {
      if (has.call(modules, item)) {
        result.push(item);
      }
    }
    return result;
  };

  require.brunch = true;
  require._cache = cache;
  globals.require = require;
})();
<commit_msg>Don't drop extensions recursively<commit_after>(function() {
  'use strict';

  var globals = typeof window === 'undefined' ? global : window;
  if (typeof globals.require === 'function') return;

  var modules = {};
  var cache = {};
  var aliases = {};
  var has = ({}).hasOwnProperty;

  var expRe = /^\.\.?(\/|$)/;
  var expand = function(root, name) {
    var results = [], part;
    var parts = (expRe.test(name) ? root + '/' + name : name).split('/');
    for (var i = 0, length = parts.length; i < length; i++) {
      part = parts[i];
      if (part === '..') {
        results.pop();
      } else if (part !== '.' && part !== '') {
        results.push(part);
      }
    }
    return results.join('/');
  };

  var dirname = function(path) {
    return path.split('/').slice(0, -1).join('/');
  };

  var localRequire = function(path) {
    return function expanded(name) {
      var absolute = expand(dirname(path), name);
      return globals.require(absolute, path);
    };
  };

  var initModule = function(name, definition) {
    var module = {id: name, exports: {}};
    cache[name] = module;
    definition(module.exports, localRequire(name), module);
    return module.exports;
  };

  var expandAlias = function(name) {
    return aliases[name] ? expandAlias(aliases[name]) : name;
  };

  var require = function(name, loaderPath) {
    if (loaderPath == null) loaderPath = '/';
    var path = expandAlias(name);

    if (has.call(cache, path)) return cache[path].exports;
    if (has.call(modules, path)) return initModule(path, modules[path]);

    throw new Error('Cannot find module "' + name + '" from ' + '"' + loaderPath + '"');
  };

  require.alias = function(from, to) {
    aliases[to] = from;
  };

  require.reset = function() {
    modules = {};
    cache = {};
    aliases = {};
  };

  var extRe = /\.[^.\/]+$/;
  var indexRe = /\/index(\.[^\/]+)?$/;
  var addExtensions = function(bundle) {
    if (extRe.test(bundle)) {
      var alias = bundle.replace(extRe, '');
      if (!has.call(aliases, alias) || aliases[alias].replace(extRe, '') === alias + '/index') {
        aliases[alias] = bundle;
      }
    }

    if (indexRe.test(bundle)) {
      var iAlias = bundle.replace(indexRe, '');
      if (!has.call(aliases, iAlias)) {
        aliases[iAlias] = bundle;
      }
    }
  };

  require.register = require.define = function(bundle, fn) {
    if (typeof bundle === 'object') {
      for (var key in bundle) {
        if (has.call(bundle, key)) {
          require.register(key, bundle[key]);
        }
      }
    } else {
      modules[bundle] = fn;
      delete cache[bundle];
      addExtensions(bundle);
    }
  };

  require.list = function() {
    var result = [];
    for (var item in modules) {
      if (has.call(modules, item)) {
        result.push(item);
      }
    }
    return result;
  };

  require.brunch = true;
  require._cache = cache;
  globals.require = require;
})();
<|endoftext|>


<commit_before>var meterID = 7813517;
var selectedYear = "2016";
var selectedMonth = "-03"
var selectedDay = "-28"
var selectedDate = "2016-03-28";

var config1 = liquidFillGaugeDefaultSettings();
config1.circleColor = "#0099FF";
config1.textColor = "#0055AA";
config1.waveTextColor = "#55DDFF";
config1.waveColor = "#0099FF";
config1.circleThickness = 0.025;
config1.textVertPosition = 0.8;
config1.waveAnimateTime = 1000;
config1.waveHeight = 0.05;
config1.waveAnimate = true;
//config1.waveRise = false;
//config1.waveHeightScaling = false;
config1.waveOffset = 0.25;
config1.waveCount = 3;
config1.displayPercent = false;
/*
config1.minValue = 0;
config1.maxValue = 5000;
*/
$.get("../api/" + meterID + "/yeartodate/" + selectedYear, function(csvString) {
	// transform the CSV string into an n-dimensional array, where n is the number of columns in the csv
	var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
/*	if( arrayData.length > 1) {
		error check here
	} else {
*/
	config1.maxValue = csvString + 500;
//	config1.maxValue = arrayData[0] + 500;
	var gauge1 = loadLiquidFillGauge("fillgauge1", csvString, config1);
//	var gauge1 = loadLiquidFillGauge("fillgauge1", arrayData[0], config1);
});
//var gauge1 = loadLiquidFillGauge("fillgauge1", 4580, config1);

var config2 = liquidFillGaugeDefaultSettings();
config2.circleColor = "#00CCFF";
config2.textColor = "#0077CC";
config2.waveTextColor = "#0099DD";
config2.waveColor = "#00CCFF";
config2.circleThickness = 0.05;
config2.waveAnimateTime = 2000;
config2.textVertPosition = 0.8;
config2.waveHeight = 0.3;
config2.waveCount = 1;
config2.displayPercent = false;
/*
config2.minValue = 0;
config2.maxValue = 500;
*/
$.get("../api/" + meterID + "/monthtodate/" + selectedYear + selectedMonth, function(csvString) {
	// transform the CSV string into an n-dimensional array, where n is the number of columns in the csv
	var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
/*	if( arrayData.length > 1) {
		error check here
	} else {
*/
//	config2.maxValue = arrayData[0] + 50;
	config2.maxValue = csvString + 50;
//	var gauge2= loadLiquidFillGauge("fillgauge2", arrayData[0], config2);
	var gauge2= loadLiquidFillGauge("fillgauge2", csvString, config2);
});
//var gauge2= loadLiquidFillGauge("fillgauge2", 397, config2);

var config3 = liquidFillGaugeDefaultSettings();
config3.circleThickness = 0.075;
config3.textVertPosition = 0.8;
config3.waveAnimateTime = 5000;
config3.waveHeight = 0.15;
config3.textVertPosition = 0.8;
config3.waveOffset = 0.25;
config3.valueCountUp = false;
config3.displayPercent = false;
/*
config3.minValue = 0;
config3.maxValue = 30;
*/
$.get("../api/" + meterID + "/dayaverage/" + selectedYear + selectedMonth + selectedDay, function(csvString) {
	// transform the CSV string into an n-dimensional array, where n is the number of columns in the csv
	var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
/*	if( arrayData.length > 1) {
		error check here
	} else {
*/
	config3.maxValue = csvString + 5;
//	config3.maxValue = arrayData[0] + 5;
	var gauge3 = loadLiquidFillGauge("fillgauge3", csvString, config3);
//	var gauge3 = loadLiquidFillGauge("fillgauge3", arrayData[0], config3);
});
//var gauge3 = loadLiquidFillGauge("fillgauge3", 12.41666667, config3);

function NewValue(){
	if(Math.random() > .5){
		return Math.round(Math.random()*100);
	} else {
		return (Math.random()*100).toFixed(1);
	}
}
<commit_msg>testing changing gauge<commit_after>var meterID = 7813517;
var selectedYear = "2016";
var selectedMonth = "-03"
var selectedDay = "-28"
var selectedDate = "2016-03-28";

var config1 = liquidFillGaugeDefaultSettings();
config1.circleColor = "#0099FF";
config1.textColor = "#0055AA";
config1.waveTextColor = "#55DDFF";
config1.waveColor = "#0099FF";
config1.circleThickness = 0.025;
config1.textVertPosition = 0.8;
config1.waveAnimateTime = 1000;
config1.waveHeight = 0.05;
config1.waveAnimate = true;
//config1.waveRise = false;
//config1.waveHeightScaling = false;
config1.waveOffset = 0.25;
config1.waveCount = 3;
config1.displayPercent = false;
/*
config1.minValue = 0;
config1.maxValue = 5000;
*/
$.get("../api/" + meterID + "/yeartodate/" + selectedYear, function(csvString) {
	// transform the CSV string into an n-dimensional array, where n is the number of columns in the csv
	var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
/*	if( arrayData.length > 1) {
		error check here
	} else {
*/
	config1.maxValue = csvString + 500;
//	config1.maxValue = arrayData[0] + 500;
	var gauge1 = loadLiquidFillGauge("fillgauge1", csvString, config1);
//	var gauge1 = loadLiquidFillGauge("fillgauge1", arrayData[0], config1);
});
//var gauge1 = loadLiquidFillGauge("fillgauge1", 4580, config1);

var config2 = liquidFillGaugeDefaultSettings();
config2.circleColor = "#00CCFF";
config2.textColor = "#0077CC";
config2.waveTextColor = "#0099DD";
config2.waveColor = "#00CCFF";
config2.circleThickness = 0.05;
config2.waveAnimateTime = 2000;
config2.textVertPosition = 0.8;
config2.waveHeight = 0.3;
config2.waveCount = 1;
config2.displayPercent = false;
/*
config2.minValue = 0;
config2.maxValue = 500;
*/
$.get("../api/" + meterID + "/monthtodate/" + selectedYear + selectedMonth, function(csvString) {
	// transform the CSV string into an n-dimensional array, where n is the number of columns in the csv
	var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
/*	if( arrayData.length > 1) {
		error check here
	} else {
*/
//	config2.maxValue = arrayData[0] + 50;
	config2.maxValue = csvString + "50";
//	var gauge2= loadLiquidFillGauge("fillgauge2", arrayData[0], config2);
	var gauge2= loadLiquidFillGauge("fillgauge2", csvString, config2);
});
//var gauge2= loadLiquidFillGauge("fillgauge2", 397, config2);

var config3 = liquidFillGaugeDefaultSettings();
config3.circleThickness = 0.075;
config3.textVertPosition = 0.8;
config3.waveAnimateTime = 5000;
config3.waveHeight = 0.15;
config3.textVertPosition = 0.8;
config3.waveOffset = 0.25;
config3.valueCountUp = false;
config3.displayPercent = false;
/*
config3.minValue = 0;
config3.maxValue = 30;
*/
$.get("../api/" + meterID + "/dayaverage/" + selectedYear + selectedMonth + selectedDay, function(csvString) {
	// transform the CSV string into an n-dimensional array, where n is the number of columns in the csv
	var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
/*	if( arrayData.length > 1) {
		error check here
	} else {
*/
	config3.maxValue = csvString + 5;
//	config3.maxValue = arrayData[0] + 5;
	var gauge3 = loadLiquidFillGauge("fillgauge3", csvString, config3);
//	var gauge3 = loadLiquidFillGauge("fillgauge3", arrayData[0], config3);
});
//var gauge3 = loadLiquidFillGauge("fillgauge3", 12.41666667, config3);

function NewValue(){
	if(Math.random() > .5){
		return Math.round(Math.random()*100);
	} else {
		return (Math.random()*100).toFixed(1);
	}
}
<|endoftext|>


<commit_before>'use strict';

// ---------------------------------------------------------------------------

const huobipro = require ('./huobipro.js');
const { PermissionDenied } = require ('./base/errors');

// ---------------------------------------------------------------------------

module.exports = class hadax extends huobipro {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'hadax',
            'name': 'HADAX',
            'countries': [ 'CN' ],
            'hostname': 'api.hadax.com',
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/38059952-4756c49e-32f1-11e8-90b9-45c1eccba9cd.jpg',
                'api': 'https://api.hadax.com',
                'www': 'https://www.hadax.com',
                'doc': 'https://github.com/huobiapi/API_Docs/wiki',
            },
            'has': {
                'fetchCurrencies': false,
            },
            'api': {
                'public': {
                    'get': [
                        'hadax/common/symbols', // 查询系统支持的所有交易对
                        'hadax/common/currencys', // 查询系统支持的所有币种
                        'common/timestamp', // 查询系统当前时间
                        'hadax/settings/currencys', // ?language=en-US
                    ],
                },
                'private': {
                    'get': [
                        'account/accounts', // 查询当前用户的所有账户(即account-id)
                        'hadax/account/accounts/{id}/balance', // 查询指定账户的余额
                        'order/orders/{id}', // 查询某个订单详情
                        'order/orders/{id}/matchresults', // 查询某个订单的成交明细
                        'order/orders', // 查询当前委托、历史委托
                        'order/matchresults', // 查询当前成交、历史成交
                        'dw/withdraw-virtual/addresses', // 查询虚拟币提现地址
                        'dw/deposit-virtual/addresses',
                        'query/deposit-withdraw',
                        'margin/loan-orders', // 借贷订单
                        'margin/accounts/balance', // 借贷账户详情
                    ],
                    'post': [
                        'hadax/order/orders/place', // 创建并执行一个新订单 (一步下单， 推荐使用)
                        'order/orders', // 创建一个新的订单请求 （仅创建订单，不执行下单）
                        'order/orders/{id}/place', // 执行一个订单 （仅执行已创建的订单）
                        'order/orders/{id}/submitcancel', // 申请撤销一个订单请求
                        'order/orders/batchcancel', // 批量撤销订单
                        'dw/balance/transfer', // 资产划转
                        'dw/withdraw/api/create', // 申请提现虚拟币
                        'dw/withdraw-virtual/create', // 申请提现虚拟币
                        'dw/withdraw-virtual/{id}/place', // 确认申请虚拟币提现
                        'dw/withdraw-virtual/{id}/cancel', // 申请取消提现虚拟币
                        'dw/transfer-in/margin', // 现货账户划入至借贷账户
                        'dw/transfer-out/margin', // 借贷账户划出至现货账户
                        'margin/orders', // 申请借贷
                        'margin/orders/{id}/repay', // 归还借贷
                    ],
                },
            },
            'exceptions': {
                'not-allow-entry-hadax': PermissionDenied,
            },
            'options': {
                'fetchMarketsMethod': 'publicGetHadaxCommonSymbols',
                'fetchBalanceMethod': 'privateGetHadaxAccountAccountsIdBalance',
                'createOrderMethod': 'privatePostHadaxOrderOrdersPlace',
            },
            'commonCurrencies': {
                'FAIR': 'FairCoin',
                'GET': 'Themis',
            },
        });
    }
};
<commit_msg>hadax FAIR → FairGame refix #3364<commit_after>'use strict';

// ---------------------------------------------------------------------------

const huobipro = require ('./huobipro.js');
const { PermissionDenied } = require ('./base/errors');

// ---------------------------------------------------------------------------

module.exports = class hadax extends huobipro {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'hadax',
            'name': 'HADAX',
            'countries': [ 'CN' ],
            'hostname': 'api.hadax.com',
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/38059952-4756c49e-32f1-11e8-90b9-45c1eccba9cd.jpg',
                'api': 'https://api.hadax.com',
                'www': 'https://www.hadax.com',
                'doc': 'https://github.com/huobiapi/API_Docs/wiki',
            },
            'has': {
                'fetchCurrencies': false,
            },
            'api': {
                'public': {
                    'get': [
                        'hadax/common/symbols', // 查询系统支持的所有交易对
                        'hadax/common/currencys', // 查询系统支持的所有币种
                        'common/timestamp', // 查询系统当前时间
                        'hadax/settings/currencys', // ?language=en-US
                    ],
                },
                'private': {
                    'get': [
                        'account/accounts', // 查询当前用户的所有账户(即account-id)
                        'hadax/account/accounts/{id}/balance', // 查询指定账户的余额
                        'order/orders/{id}', // 查询某个订单详情
                        'order/orders/{id}/matchresults', // 查询某个订单的成交明细
                        'order/orders', // 查询当前委托、历史委托
                        'order/matchresults', // 查询当前成交、历史成交
                        'dw/withdraw-virtual/addresses', // 查询虚拟币提现地址
                        'dw/deposit-virtual/addresses',
                        'query/deposit-withdraw',
                        'margin/loan-orders', // 借贷订单
                        'margin/accounts/balance', // 借贷账户详情
                    ],
                    'post': [
                        'hadax/order/orders/place', // 创建并执行一个新订单 (一步下单， 推荐使用)
                        'order/orders', // 创建一个新的订单请求 （仅创建订单，不执行下单）
                        'order/orders/{id}/place', // 执行一个订单 （仅执行已创建的订单）
                        'order/orders/{id}/submitcancel', // 申请撤销一个订单请求
                        'order/orders/batchcancel', // 批量撤销订单
                        'dw/balance/transfer', // 资产划转
                        'dw/withdraw/api/create', // 申请提现虚拟币
                        'dw/withdraw-virtual/create', // 申请提现虚拟币
                        'dw/withdraw-virtual/{id}/place', // 确认申请虚拟币提现
                        'dw/withdraw-virtual/{id}/cancel', // 申请取消提现虚拟币
                        'dw/transfer-in/margin', // 现货账户划入至借贷账户
                        'dw/transfer-out/margin', // 借贷账户划出至现货账户
                        'margin/orders', // 申请借贷
                        'margin/orders/{id}/repay', // 归还借贷
                    ],
                },
            },
            'exceptions': {
                'not-allow-entry-hadax': PermissionDenied,
            },
            'options': {
                'fetchMarketsMethod': 'publicGetHadaxCommonSymbols',
                'fetchBalanceMethod': 'privateGetHadaxAccountAccountsIdBalance',
                'createOrderMethod': 'privatePostHadaxOrderOrdersPlace',
            },
            'commonCurrencies': {
                'FAIR': 'FairGame',
                'GET': 'Themis',
            },
        });
    }
};
<|endoftext|>


<commit_before><commit_msg>Fixed pre-opening time interval bug<commit_after><|endoftext|>


<commit_before>
const LEFT = 1;
const RIGHT = 2;
const UP = 3;
const DOWN = 4;
const FLY = 5;
const RESPAWN_TIME = 300;

export class Human {

    constructor(npc, map) {

        this.npc = npc;
        this.map = map;
        this.pos = { x: 4, y: 20 };
        this.respawnPos = { x: 4, y: 4 };
        this.alive = false;
        this.direction = LEFT;
        this.keyFound = false;
        this.deathTimer = 0;
        this.finished = false;
    }

    kill() {
        this.alive = false;
    }

    isDead() {
        return !this.alive;
    }

    // Distance to other human.
    getDistance(otherHuman) {
        return Math.floor(Math.sqrt(Math.pow(this.pos.x - otherHuman.getPos().x, 2) + Math.pow(this.pos.y - otherHuman.getPos().y, 2)));
    }

    isKeyFound() {
        return this.keyFound;
    }

    caught(otherHuman) {
        return (this.getDistance(otherHuman) < 3);
    }

    resetKeyFound() {
        this.keyFound = false;
    }

    freeSquare(x, y) {
        var p = this.map.get(x, y),
            result = this.map.isSpace(p) || (p === this.map.LADDER) || (p === this.map.KLAD) || (p === this.map.KEY) ||
                (p === this.map.DOOR_OPENED) || (p === this.map.BRIDGE);

        if (!this.npc) {
            if (p === this.map.KLAD) {
                this.map.set(x, y, this.map.SPACE);
            }
            if (p === this.map.KEY) {
                this.keyFound = true;
                this.map.setKeyFound();
            }
            if ((p === this.map.DOOR) && this.keyFound) {
                this.map.set(x, y, this.map.DOOR_OPENED);
                result = true;
            }
            if (y < 0) {
                this.finished = true;
            }
        }

        if ((p === this.map.WATER) && (this.pos.y % 4) === 2) {
            this.kill();
        }

        return result;
    };

    getPos() {
        return this.pos;
    }

    moveLeft() {
        if (((this.pos.x % 4) === 0) && (!this.freeSquare(Math.floor(this.pos.x / 4) - 1, Math.floor((this.pos.y + 2) / 4)))) {
            return false;
        }
        if ((this.pos.y % 4) !== 0) {
            if ((this.pos.y % 4) > 1) {
                return this.moveDown();
            }
            return this.moveUp();
        }
        this.pos.x -= 1;
        this.direction = LEFT;
        return true;
    }

    moveRight() {
        if (((this.pos.x % 4) === 0) && (!this.freeSquare(Math.floor(this.pos.x / 4) + 1, Math.floor((this.pos.y + 2) / 4)))) {
            return false;
        }
        if ((this.pos.y % 4) !== 0) {
            if ((this.pos.y % 4) > 1) {
                return this.moveDown();
            }
            return this.moveUp();
        }
        this.pos.x += 1;
        this.direction = RIGHT;
        return true;
    }

    moveUp() {
        var x = Math.floor((this.pos.x + 2) / 4),
            y = Math.floor(this.pos.y / 4);
        if (((this.pos.y % 4) === 0) && (!(this.freeSquare(x, y - 1) && (this.map.get(x, y) === this.map.LADDER)))) {
            return false;
        }
        if ((this.pos.x % 4) !== 0) {
            if (!this.npc) {
                if ((this.pos.x % 4) > 1) {
                    this.moveRight();
                } else {
                    this.moveLeft();
                }
            }
            return false;
        }
        this.pos.y -= 1;
        this.direction = UP;
        return true;
    }

    moveDown() {
        if (((this.pos.y % 4) === 0) && (!this.freeSquare(Math.floor((this.pos.x + 2) / 4), Math.floor(this.pos.y / 4) + 1) ||
            (this.map.get(Math.floor((this.pos.x + 2) / 4), Math.floor(this.pos.y / 4) + 1) === this.map.BRIDGE))) {
            return false;
        }
        if ((this.pos.x % 4) !== 0) {
            if (!this.npc) {
                if ((this.pos.x % 4) > 1) {
                    this.moveRight();
                } else {
                    this.moveLeft();
                }
            }
            return false;
        }
        this.pos.y += 1;
        this.direction = DOWN;
        return true;
    }

    render(ctx, images) {

        var pic = 8,
            img,
            HUMAN_SPRITES = [images.runner0, images.runner1, images.runner2, images.runner3,
                images.runner4, images.runner5, images.runner6, images.runner7,
                images.runner8, images.runner9,
                images.runner10, images.runner11, images.runner12, images.runner13,
                images.runner14, images.runner15, images.runner16, images.runner17,
                images.runner18, images.runner19];

        if ((this.direction === LEFT) || (this.direction === RIGHT)) {
            pic = this.pos.x % 4;
        }
        if (this.direction === LEFT) {
            pic += 4;
        }
        if ((this.direction === UP) || (this.direction === DOWN)) {
            pic = (this.pos.y % 2) + 8;
        }
        if (this.npc) {
            pic += 10;
        }
        img = HUMAN_SPRITES[pic];

        ctx.drawImage(img, this.pos.x * (this.map.CELL_WIDTH / 4), this.pos.y * (this.map.CELL_HEIGHT / 4));
    }

    respawn(x, y) {
        this.respawnPos.x = x;
        this.respawnPos.y = y;
        this.pos.x = this.respawnPos.x * 4;
        this.pos.y = this.respawnPos.y * 4;
        this.alive = true;
        this.deathTimer = 0;
    }

    freeFly() {
        var x = Math.floor((this.pos.x + 2) / 4),
            y = Math.floor(this.pos.y / 4),
            p,
            flying;

        this.freeSquare(x, y + 1);
        if (this.map.get(x, y) === this.map.LADDER) {
            return false;
        }
        p = this.map.get(x, y + 1);
        flying = (this.map.isSpace(p) || (p === this.map.WATER) || ((p === this.map.BRIDGE) && (this.direction === FLY)));
        if (!flying) {
            return false;
        }

        if ((this.pos.x % 4) !== 0) {
            if ((this.pos.x % 4) > 1) {
                this.moveRight();
            } else {
                this.moveLeft();
            }
        } else {
            this.pos.y += 1;
        }

        this.direction = FLY;
        return true;
    }

    isFinished() {
        return this.finished;
    }

    resetFinished() {
        this.finished = false;
    }

    moveToHuman(otherHuman) {
        var toLeft = false,
            toRight = false,
            toUp = false,
            toDown = false;

        if (otherHuman.getPos().x < this.getPos().x) {
            toLeft = true;
        }
        if (otherHuman.getPos().x > this.getPos().x) {
            toRight = true;
        }
        if (otherHuman.getPos().y > this.getPos().y) {
            toDown = true;
        }
        if (otherHuman.getPos().y < this.getPos().y) {
            toUp = true;
        }

        this.move(toLeft, toRight, toUp, toDown);
    }

    move(toLeft, toRight, toUp, toDown) {
        if (this.npc) {
            if (!this.alive) {
                this.deathTimer += 1;
                if (this.deathTimer >= RESPAWN_TIME) {
                    this.respawn(this.respawnPos.x, this.respawnPos.y);
                }
                return false;
            }
        }

        if (this.freeFly()) {
            return false;
        }

        var moved = false;
        if (toLeft) {
            if (this.moveLeft()) {
                moved = true;
            }
        }
        if (toRight) {
            if (this.moveRight()) {
                moved = true;
            }
        }

        if (!moved) {
            if (toUp) {
                this.moveUp();
            }
            if (toDown) {
                this.moveDown();
            }
        }

        if (this.map.get(Math.floor((this.pos.x + 2) / 4), Math.floor((this.pos.y + 2) / 4)) === this.map.BRICK)
		{
            this.kill();
        }

        return true;
    }
}
<commit_msg>Replace 'var' to 'let' in Human class<commit_after>
const LEFT = 1;
const RIGHT = 2;
const UP = 3;
const DOWN = 4;
const FLY = 5;
const RESPAWN_TIME = 300;

export class Human {

    constructor(npc, map) {

        this.npc = npc;
        this.map = map;
        this.pos = { x: 4, y: 20 };
        this.respawnPos = { x: 4, y: 4 };
        this.alive = false;
        this.direction = LEFT;
        this.keyFound = false;
        this.deathTimer = 0;
        this.finished = false;
    }

    kill() {
        this.alive = false;
    }

    isDead() {
        return !this.alive;
    }

    // Distance to other human.
    getDistance(otherHuman) {
        return Math.floor(Math.sqrt(Math.pow(this.pos.x - otherHuman.getPos().x, 2) + Math.pow(this.pos.y - otherHuman.getPos().y, 2)));
    }

    isKeyFound() {
        return this.keyFound;
    }

    caught(otherHuman) {
        return (this.getDistance(otherHuman) < 3);
    }

    resetKeyFound() {
        this.keyFound = false;
    }

    freeSquare(x, y) {
        let p = this.map.get(x, y);
        let result = this.map.isSpace(p) || (p === this.map.LADDER) || (p === this.map.KLAD) || (p === this.map.KEY) ||
                (p === this.map.DOOR_OPENED) || (p === this.map.BRIDGE);

        if (!this.npc) {
            if (p === this.map.KLAD) {
                this.map.set(x, y, this.map.SPACE);
            }
            if (p === this.map.KEY) {
                this.keyFound = true;
                this.map.setKeyFound();
            }
            if ((p === this.map.DOOR) && this.keyFound) {
                this.map.set(x, y, this.map.DOOR_OPENED);
                result = true;
            }
            if (y < 0) {
                this.finished = true;
            }
        }

        if ((p === this.map.WATER) && (this.pos.y % 4) === 2) {
            this.kill();
        }

        return result;
    };

    getPos() {
        return this.pos;
    }

    moveLeft() {
        if (((this.pos.x % 4) === 0) && (!this.freeSquare(Math.floor(this.pos.x / 4) - 1, Math.floor((this.pos.y + 2) / 4)))) {
            return false;
        }
        if ((this.pos.y % 4) !== 0) {
            if ((this.pos.y % 4) > 1) {
                return this.moveDown();
            }
            return this.moveUp();
        }
        this.pos.x -= 1;
        this.direction = LEFT;
        return true;
    }

    moveRight() {
        if (((this.pos.x % 4) === 0) && (!this.freeSquare(Math.floor(this.pos.x / 4) + 1, Math.floor((this.pos.y + 2) / 4)))) {
            return false;
        }
        if ((this.pos.y % 4) !== 0) {
            if ((this.pos.y % 4) > 1) {
                return this.moveDown();
            }
            return this.moveUp();
        }
        this.pos.x += 1;
        this.direction = RIGHT;
        return true;
    }

    moveUp() {
        let x = Math.floor((this.pos.x + 2) / 4);
        let y = Math.floor(this.pos.y / 4);
        if (((this.pos.y % 4) === 0) && (!(this.freeSquare(x, y - 1) && (this.map.get(x, y) === this.map.LADDER)))) {
            return false;
        }
        if ((this.pos.x % 4) !== 0) {
            if (!this.npc) {
                if ((this.pos.x % 4) > 1) {
                    this.moveRight();
                } else {
                    this.moveLeft();
                }
            }
            return false;
        }
        this.pos.y -= 1;
        this.direction = UP;
        return true;
    }

    moveDown() {
        if (((this.pos.y % 4) === 0) && (!this.freeSquare(Math.floor((this.pos.x + 2) / 4), Math.floor(this.pos.y / 4) + 1) ||
            (this.map.get(Math.floor((this.pos.x + 2) / 4), Math.floor(this.pos.y / 4) + 1) === this.map.BRIDGE))) {
            return false;
        }
        if ((this.pos.x % 4) !== 0) {
            if (!this.npc) {
                if ((this.pos.x % 4) > 1) {
                    this.moveRight();
                } else {
                    this.moveLeft();
                }
            }
            return false;
        }
        this.pos.y += 1;
        this.direction = DOWN;
        return true;
    }

    render(ctx, images) {
        let pic = 8;
        if ((this.direction === LEFT) || (this.direction === RIGHT)) {
            pic = this.pos.x % 4;
        }
        if (this.direction === LEFT) {
            pic += 4;
        }
        if ((this.direction === UP) || (this.direction === DOWN)) {
            pic = (this.pos.y % 2) + 8;
        }
        if (this.npc) {
            pic += 10;
        }

        const HUMAN_SPRITES = [images.runner0, images.runner1, images.runner2, images.runner3,
            images.runner4, images.runner5, images.runner6, images.runner7,
            images.runner8, images.runner9,
            images.runner10, images.runner11, images.runner12, images.runner13,
            images.runner14, images.runner15, images.runner16, images.runner17,
            images.runner18, images.runner19];
        let img = HUMAN_SPRITES[pic];

        ctx.drawImage(img, this.pos.x * (this.map.CELL_WIDTH / 4), this.pos.y * (this.map.CELL_HEIGHT / 4));
    }

    respawn(x, y) {
        this.respawnPos.x = x;
        this.respawnPos.y = y;
        this.pos.x = this.respawnPos.x * 4;
        this.pos.y = this.respawnPos.y * 4;
        this.alive = true;
        this.deathTimer = 0;
    }

    freeFly() {
        let x = Math.floor((this.pos.x + 2) / 4);
        let y = Math.floor(this.pos.y / 4);

        this.freeSquare(x, y + 1);
        if (this.map.get(x, y) === this.map.LADDER) {
            return false;
        }

        let p = this.map.get(x, y + 1);
        let flying = (this.map.isSpace(p) || (p === this.map.WATER) || ((p === this.map.BRIDGE) && (this.direction === FLY)));
        if (!flying) {
            return false;
        }

        if ((this.pos.x % 4) !== 0) {
            if ((this.pos.x % 4) > 1) {
                this.moveRight();
            } else {
                this.moveLeft();
            }
        } else {
            this.pos.y += 1;
        }

        this.direction = FLY;
        return true;
    }

    isFinished() {
        return this.finished;
    }

    resetFinished() {
        this.finished = false;
    }

    moveToHuman(otherHuman) {
        let toLeft = false;
        let toRight = false;
        let toUp = false;
        let toDown = false;

        if (otherHuman.getPos().x < this.getPos().x) {
            toLeft = true;
        }
        if (otherHuman.getPos().x > this.getPos().x) {
            toRight = true;
        }
        if (otherHuman.getPos().y > this.getPos().y) {
            toDown = true;
        }
        if (otherHuman.getPos().y < this.getPos().y) {
            toUp = true;
        }

        this.move(toLeft, toRight, toUp, toDown);
    }

    move(toLeft, toRight, toUp, toDown) {
        if (this.npc) {
            if (!this.alive) {
                this.deathTimer += 1;
                if (this.deathTimer >= RESPAWN_TIME) {
                    this.respawn(this.respawnPos.x, this.respawnPos.y);
                }
                return false;
            }
        }

        if (this.freeFly()) {
            return false;
        }

        var moved = false;
        if (toLeft) {
            if (this.moveLeft()) {
                moved = true;
            }
        }
        if (toRight) {
            if (this.moveRight()) {
                moved = true;
            }
        }

        if (!moved) {
            if (toUp) {
                this.moveUp();
            }
            if (toDown) {
                this.moveDown();
            }
        }

        if (this.map.get(Math.floor((this.pos.x + 2) / 4), Math.floor((this.pos.y + 2) / 4)) === this.map.BRICK) {
            this.kill();
        }

        return true;
    }
}
<|endoftext|>


<commit_before>var cost = function(body){
	var mycost = 0;
	for(var bodypart of body){
		mycost += BODYPART_COST[bodypart]
	}
	return mycost
}

var bodies = {
	miner : function(maxEnergy){
		var body=[WORK];
		var minEnergy = cost([WORK,MOVE])
		if(maxEnergy > minEnergy){
			var n = Math.min(Math.floor((maxEnergy - minEnergy)/BODYPART_COST[WORK]),4); //a maximum of 5 WORK parts
			for(i=0; i<n; i++){
				body.push(WORK);
			}
		}
		body.push(MOVE);
		return body
	},
	upgrader : function(maxEnergy){
		var template = [WORK,CARRY,MOVE];
		var intervalEnergy = cost(template);
		var n = Math.floor(maxEnergy/intervalEnergy);
		if(n >= 10){
			n=10
		}
		else if(n>=5){
			n=5
		}
		var body = [];
		for(i=0;i<n;i++){
			body.push(WORK,CARRY,MOVE);
		}
		return body
	},
	builder : function(maxEnergy){
		var template = [WORK,CARRY,MOVE];
		var intervalEnergy = cost(template);
		var n = Math.min(Math.floor(maxEnergy/intervalEnergy),6); //hardcapped at 6
		var body = [];
		for(i=0;i<n;i++){
			body.push(WORK,CARRY,MOVE);
		}
		return body
	},
	repairer : function(maxEnergy){
		return this.builder(maxEnergy);
	},
	runner : function(maxEnergy){
		var template = [CARRY,MOVE];
		var intervalEnergy=cost(template);
		var n = Math.min(Math.floor(maxEnergy/intervalEnergy),10); //currently hardcapped at 10
		var body = [];
		for(i=0;i<n;i++){
			body.push(CARRY,MOVE);
		}
		return body
	}
}

module.exports = {
    run : function(myrooms) {
    	// room based spawning
		for(var room of myrooms){
			var spawn = room.find(FIND_STRUCTURES,{filter : (s) => s.structureType == STRUCTURE_SPAWN})[0];
			var maxEnergy = room.energyCapacityAvailable;

			var harvester_target = 2; //harvesters per remote site
			var upgrader_target = Math.min(Math.ceil(20/(bodies.upgrader.length(maxEnergy)/3)),4); //should be around 500 energy per 50 ticks
			var builder_target = 2;
			var repairer_target = 1; //repairer is a builder that prioritises repairing non-wall structures
			var miner_target = 2;
			var runner_target = 2;
			var thief_target = 0;
			var hunter_target = 0;

			var hostiles = room.find(FIND_HOSTILE_CREEPS);
			if(hostiles.length){
				hunter_target=Math.ceil(hostiles.length/2)
			}

			var upgraders = room.find(FIND_MY_CREEPS,{filter: (creep) => creep.memory.role == 'upgrader'});
			var builders = room.find(FIND_MY_CREEPS,{filter: (creep) => creep.memory.role == 'builder'});
			var repairers = room.find(FIND_MY_CREEPS,{filter: (creep) => creep.memory.role == 'repairer'});
			var miners = room.find(FIND_MY_CREEPS,{filter: (creep) => creep.memory.role == 'miner'});
			var runners = room.find(FIND_MY_CREEPS,{filter: (creep) => creep.memory.role == 'runner'});
			var hunters = room.find(FIND_MY_CREEPS,{filter: (creep) => creep.memory.role == 'hunter'});
			// var thiefs = room.find(FIND_MY_CREEPS,{filter: (creep) => creep.memory.role == 'thief'});
	       // console.log(miners.length + ' ' + runners.length + ' ' + upgraders.length + ' ' + repairers.length)

			//first ensure 1 miner, 1 runner, 1 upgrader are always available
			if(miners.length < 1){
				spawn.createCreep(bodies.miner(room.energyAvailable),undefined,{role:'miner'});
			}
			else if(runners.length < 1){
				spawn.createCreep(bodies.runner(room.energyAvailable),undefined,{role:'runner'});
			}
			else if(upgraders.length < 1 && room.controller.ticksToDowngrade < 500){
				spawn.createCreep(bodies.upgrader(room.energyAvailable),undefined,{role:'upgrader'});
			}
			//prioritize first repairer so we have something to build early on
			else if(repairers.length < 1){
				spawn.createCreep(bodies.repairer(room.energyAvailable),undefined,{role:'repairer'});
			}
			//now proceed with the rest in priority order
			else if(miners.length < miner_target){
				spawn.createCreep(bodies.miner(maxEnergy),undefined,{role:'miner'});
			}
			else if(runners.length < runner_target){
				spawn.createCreep(bodies.runner(maxEnergy/2),undefined,{role:'runner'});
			}
			else if(upgraders.length < upgrader_target) {
				spawn.createCreep(bodies.upgrader(maxEnergy),undefined,{role:'upgrader'});
			}
			else if(builders.length < builder_target) {
				spawn.createCreep(bodies.builder(maxEnergy),undefined,{role:'builder'});
			}
			else if(repairers.length < repairer_target) {
				spawn.createCreep(bodies.repairer(maxEnergy),undefined,{role: 'repairer'});
			}
			else if(hunters.length < hunter_target) {
				if (spawn.room.energyAvailable > 600){
					spawn.createCreep([TOUGH,TOUGH,TOUGH,MOVE,MOVE,MOVE,MOVE,MOVE,ATTACK,ATTACK,ATTACK,MOVE],undefined,{role: 'hunter'});
				}
			}
			// if(thiefs.length < thief_target) {
				// if (spawn.room.energyAvailable > 600){
					// spawn.createCreep([CARRY,CARRY,CARRY,CARRY,MOVE,MOVE,MOVE,MOVE],undefined,{role: 'thief'});
				// }
			// }
		}
		//flag based spawning
		for (var flag in Game.flags){
			if(/harvest/.test(flag)){ //see that every remote site has enough harvesters
				var harvesters = _.filter(Game.creeps, (creep) =>
					creep.memory.role == 'harvester' && creep.memory.myflag == flag
				);
				if (harvesters.length < harvester_target){
					Game.spawns['Spawn1'].createCreep([MOVE,CARRY,WORK,MOVE,CARRY,WORK,MOVE,CARRY,WORK,MOVE,CARRY,WORK,MOVE,CARRY,WORK,MOVE,CARRY,WORK,MOVE,CARRY,WORK,MOVE,CARRY,WORK,MOVE,CARRY,WORK,MOVE,CARRY,WORK],undefined,{
						role: 'harvester', myflag: flag, home: Game.spawns['Spawn1'].room.name
					});
				}
			}
			if(/reserve/.test(flag)){ //logic to spawn reservers
				var reservers = _.filter(Game.creeps, (creep) =>
					creep.memory.role == 'reserver' && creep.memory.myflag == flag
				);
				if (reservers.length < 1){
					var tospawn = false
					if (Game.flags[flag].memory.reserved && Game.flags[flag].pos.roomName in Game.rooms){ //second check is to prevent breaking from no vision
						var con = Game.flags[flag].pos.lookFor(LOOK_STRUCTURES,{filter: (s) => s.structureType == STRUCTURE_CONTROLLER})[0];
						if(con.reservation == undefined){ //yet more failsafes
							Game.flags[flag].memory.reserved = false;
						}
						else if(con.reservation.ticksToEnd < 500){
							tospawn = true;
						}
					}
					else{
						if(Game.spawns['Spawn1'].canCreateCreep([MOVE,CLAIM,CLAIM,MOVE],undefined,{
								role: 'reserver', myflag: flag}) == OK){
							tospawn = true;
							Game.flags[flag].memory.reserved = true; //should have some kind of check to prevent breaking
						}
					}
					if(tospawn){
						Game.spawns['Spawn1'].createCreep([MOVE,CLAIM,CLAIM,MOVE],undefined,{
							role: 'reserver', myflag: flag
						});
					}
				}
			}
			if(/claim/.test(flag)){ //continously respawn remoteUpgraders to help establish the new room until flag is removed
				var remoteUpgraders = _.filter(Game.creeps,(creep) =>
					creep.memory.role == 'remoteUpgrader' && creep.memory.myflag == flag
				);
				if (remoteUpgraders.length < 1){
					Game.spawns['Spawn1'].createCreep([WORK,WORK,WORK,WORK,CARRY,CARRY,CARRY,CARRY,MOVE,MOVE,MOVE,MOVE],undefined,{
						role : 'remoteUpgrader' , myflag : flag
					});
				}
			}
		}

    }
};
<commit_msg>hotfix<commit_after>var cost = function(body){
	var mycost = 0;
	for(var bodypart of body){
		mycost += BODYPART_COST[bodypart]
	}
	return mycost
}

var bodies = {
	miner : function(maxEnergy){
		var body=[WORK];
		var minEnergy = cost([WORK,MOVE])
		if(maxEnergy > minEnergy){
			var n = Math.min(Math.floor((maxEnergy - minEnergy)/BODYPART_COST[WORK]),4); //a maximum of 5 WORK parts
			for(i=0; i<n; i++){
				body.push(WORK);
			}
		}
		body.push(MOVE);
		return body
	},
	upgrader : function(maxEnergy){
		var template = [WORK,CARRY,MOVE];
		var intervalEnergy = cost(template);
		var n = Math.floor(maxEnergy/intervalEnergy);
		if(n >= 10){
			n=10
		}
		else if(n>=5){
			n=5
		}
		var body = [];
		for(i=0;i<n;i++){
			body.push(WORK,CARRY,MOVE);
		}
		return body
	},
	builder : function(maxEnergy){
		var template = [WORK,CARRY,MOVE];
		var intervalEnergy = cost(template);
		var n = Math.min(Math.floor(maxEnergy/intervalEnergy),6); //hardcapped at 6
		var body = [];
		for(i=0;i<n;i++){
			body.push(WORK,CARRY,MOVE);
		}
		return body
	},
	repairer : function(maxEnergy){
		return this.builder(maxEnergy);
	},
	runner : function(maxEnergy){
		var template = [CARRY,MOVE];
		var intervalEnergy=cost(template);
		var n = Math.min(Math.floor(maxEnergy/intervalEnergy),10); //currently hardcapped at 10
		var body = [];
		for(i=0;i<n;i++){
			body.push(CARRY,MOVE);
		}
		return body
	}
}

module.exports = {
    run : function(myrooms) {
    	// room based spawning
		for(var room of myrooms){
			var spawn = room.find(FIND_STRUCTURES,{filter : (s) => s.structureType == STRUCTURE_SPAWN})[0];
			var maxEnergy = room.energyCapacityAvailable;

			var harvester_target = 2; //harvesters per remote site
			var upgrader_target = Math.min(Math.ceil(20/(bodies.upgrader(maxEnergy).length/3)),4); //should be around 500 energy per 50 ticks
			var builder_target = 2;
			var repairer_target = 1; //repairer is a builder that prioritises repairing non-wall structures
			var miner_target = 2;
			var runner_target = 2;
			var thief_target = 0;
			var hunter_target = 0;

			var hostiles = room.find(FIND_HOSTILE_CREEPS);
			if(hostiles.length){
				hunter_target=Math.ceil(hostiles.length/2)
			}

			var upgraders = room.find(FIND_MY_CREEPS,{filter: (creep) => creep.memory.role == 'upgrader'});
			var builders = room.find(FIND_MY_CREEPS,{filter: (creep) => creep.memory.role == 'builder'});
			var repairers = room.find(FIND_MY_CREEPS,{filter: (creep) => creep.memory.role == 'repairer'});
			var miners = room.find(FIND_MY_CREEPS,{filter: (creep) => creep.memory.role == 'miner'});
			var runners = room.find(FIND_MY_CREEPS,{filter: (creep) => creep.memory.role == 'runner'});
			var hunters = room.find(FIND_MY_CREEPS,{filter: (creep) => creep.memory.role == 'hunter'});
			// var thiefs = room.find(FIND_MY_CREEPS,{filter: (creep) => creep.memory.role == 'thief'});
	       // console.log(miners.length + ' ' + runners.length + ' ' + upgraders.length + ' ' + repairers.length)

			//first ensure 1 miner, 1 runner, 1 upgrader are always available
			if(miners.length < 1){
				spawn.createCreep(bodies.miner(room.energyAvailable),undefined,{role:'miner'});
			}
			else if(runners.length < 1){
				spawn.createCreep(bodies.runner(room.energyAvailable),undefined,{role:'runner'});
			}
			else if(upgraders.length < 1 && room.controller.ticksToDowngrade < 500){
				spawn.createCreep(bodies.upgrader(room.energyAvailable),undefined,{role:'upgrader'});
			}
			//prioritize first repairer so we have something to build early on
			else if(repairers.length < 1){
				spawn.createCreep(bodies.repairer(room.energyAvailable),undefined,{role:'repairer'});
			}
			//now proceed with the rest in priority order
			else if(miners.length < miner_target){
				spawn.createCreep(bodies.miner(maxEnergy),undefined,{role:'miner'});
			}
			else if(runners.length < runner_target){
				spawn.createCreep(bodies.runner(maxEnergy/2),undefined,{role:'runner'});
			}
			else if(upgraders.length < upgrader_target) {
				spawn.createCreep(bodies.upgrader(maxEnergy),undefined,{role:'upgrader'});
			}
			else if(builders.length < builder_target) {
				spawn.createCreep(bodies.builder(maxEnergy),undefined,{role:'builder'});
			}
			else if(repairers.length < repairer_target) {
				spawn.createCreep(bodies.repairer(maxEnergy),undefined,{role: 'repairer'});
			}
			else if(hunters.length < hunter_target) {
				if (spawn.room.energyAvailable > 600){
					spawn.createCreep([TOUGH,TOUGH,TOUGH,MOVE,MOVE,MOVE,MOVE,MOVE,ATTACK,ATTACK,ATTACK,MOVE],undefined,{role: 'hunter'});
				}
			}
			// if(thiefs.length < thief_target) {
				// if (spawn.room.energyAvailable > 600){
					// spawn.createCreep([CARRY,CARRY,CARRY,CARRY,MOVE,MOVE,MOVE,MOVE],undefined,{role: 'thief'});
				// }
			// }
		}
		//flag based spawning
		for (var flag in Game.flags){
			if(/harvest/.test(flag)){ //see that every remote site has enough harvesters
				var harvesters = _.filter(Game.creeps, (creep) =>
					creep.memory.role == 'harvester' && creep.memory.myflag == flag
				);
				if (harvesters.length < harvester_target){
					Game.spawns['Spawn1'].createCreep([MOVE,CARRY,WORK,MOVE,CARRY,WORK,MOVE,CARRY,WORK,MOVE,CARRY,WORK,MOVE,CARRY,WORK,MOVE,CARRY,WORK,MOVE,CARRY,WORK,MOVE,CARRY,WORK,MOVE,CARRY,WORK,MOVE,CARRY,WORK],undefined,{
						role: 'harvester', myflag: flag, home: Game.spawns['Spawn1'].room.name
					});
				}
			}
			if(/reserve/.test(flag)){ //logic to spawn reservers
				var reservers = _.filter(Game.creeps, (creep) =>
					creep.memory.role == 'reserver' && creep.memory.myflag == flag
				);
				if (reservers.length < 1){
					var tospawn = false
					if (Game.flags[flag].memory.reserved && Game.flags[flag].pos.roomName in Game.rooms){ //second check is to prevent breaking from no vision
						var con = Game.flags[flag].pos.lookFor(LOOK_STRUCTURES,{filter: (s) => s.structureType == STRUCTURE_CONTROLLER})[0];
						if(con.reservation == undefined){ //yet more failsafes
							Game.flags[flag].memory.reserved = false;
						}
						else if(con.reservation.ticksToEnd < 500){
							tospawn = true;
						}
					}
					else{
						if(Game.spawns['Spawn1'].canCreateCreep([MOVE,CLAIM,CLAIM,MOVE],undefined,{
								role: 'reserver', myflag: flag}) == OK){
							tospawn = true;
							Game.flags[flag].memory.reserved = true; //should have some kind of check to prevent breaking
						}
					}
					if(tospawn){
						Game.spawns['Spawn1'].createCreep([MOVE,CLAIM,CLAIM,MOVE],undefined,{
							role: 'reserver', myflag: flag
						});
					}
				}
			}
			if(/claim/.test(flag)){ //continously respawn remoteUpgraders to help establish the new room until flag is removed
				var remoteUpgraders = _.filter(Game.creeps,(creep) =>
					creep.memory.role == 'remoteUpgrader' && creep.memory.myflag == flag
				);
				if (remoteUpgraders.length < 1){
					Game.spawns['Spawn1'].createCreep([WORK,WORK,WORK,WORK,CARRY,CARRY,CARRY,CARRY,MOVE,MOVE,MOVE,MOVE],undefined,{
						role : 'remoteUpgrader' , myflag : flag
					});
				}
			}
		}

    }
};
<|endoftext|>


<commit_before>/*
 * Module code goes here. Use 'module.exports' to export things:
 * module.exports.thing = 'a thing';
 *
 * You can import it from another modules like this:
 * var mod = require('respawn');
 * mod.thing == 'a thing'; // true
 */

module.exports = {
    run : function() {
        var harvester_target = 2; //harvesters per remote site
        var upgrader_target = 4;
        var builder_target = 3;
        var miner_target = 2;
        var runner_target = 2;
		var thief_target = 0;
        var hunter_target = 0;

		var hostiles = Game.spawns['Spawn1'].room.find(FIND_HOSTILE_CREEPS)
		if(hostiles.length){
			hunter_target=Math.ceil(hostiles.length/2)
		}

        var upgraders = _.filter(Game.creeps, (creep) => creep.memory.role == 'upgrader');
        var builders = _.filter(Game.creeps, (creep) => creep.memory.role == 'builder');
        var miners = _.filter(Game.creeps, (creep) => creep.memory.role == 'miner');
		var runners = _.filter(Game.creeps, (creep) => creep.memory.role == 'runner');
		var hunters = _.filter(Game.creeps, (creep) => creep.memory.role == 'hunter');
		var thiefs = _.filter(Game.creeps, (creep) => creep.memory.role == 'thief');
//        console.log(harvesters.length + ' ' + upgraders.length + ' ' + builders.length)

		if(miners.length < miner_target){
			Game.spawns['Spawn1'].createCreep([WORK,WORK,WORK,WORK,WORK,MOVE],undefined,{role:'miner'});
		}
		if(runners.length < runner_target){
			Game.spawns['Spawn1'].createCreep([CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE],undefined,{role:'runner'});
		}
        if(upgraders.length < upgrader_target) {
            if (Game.spawns['Spawn1'].room.energyAvailable < 600 && upgraders.length < 1){
                Game.spawns['Spawn1'].createCreep([WORK,CARRY,MOVE],undefined,{role: 'upgrader'});
            }
            else {
				Game.spawns['Spawn1'].createCreep([WORK,WORK,WORK,WORK,CARRY,CARRY,CARRY,CARRY,MOVE,MOVE,MOVE,MOVE],undefined,{role: 'upgrader'});
            }
        }
        if(builders.length < builder_target) {
			if (Game.spawns['Spawn1'].room.energyAvailable < 600 && builders.length < 1){
                Game.spawns['Spawn1'].createCreep([WORK,CARRY,MOVE],undefined,{role: 'builder'});
            }
            else {
				Game.spawns['Spawn1'].createCreep([WORK,WORK,WORK,CARRY,CARRY,CARRY,MOVE,MOVE,MOVE],undefined,{role: 'builder'});
            }
        }
		if(hunters.length < hunter_target) {
			if (Game.spawns['Spawn1'].room.energyAvailable > 600){
                Game.spawns['Spawn1'].createCreep([TOUGH,TOUGH,TOUGH,MOVE,MOVE,MOVE,MOVE,MOVE,ATTACK,ATTACK,ATTACK,MOVE],undefined,{role: 'hunter'});
            }
        }
		if(thiefs.length < thief_target) {
			if (Game.spawns['Spawn1'].room.energyAvailable > 600){
                Game.spawns['Spawn1'].createCreep([CARRY,CARRY,CARRY,CARRY,MOVE,MOVE,MOVE,MOVE],undefined,{role: 'thief'});
            }
        }

		for (var flag in Game.flags){
			if(/harvest/.test(flag)){ //see that every remote site has enough harvesters
				var harvesters = _.filter(Game.creeps, (creep) =>
					creep.memory.role == 'harvester' && creep.memory.myflag == flag
				);
				if (harvesters < harvester_target){
					Game.spawns['Spawn1'].createCreep([MOVE,MOVE,MOVE,WORK,WORK,WORK,CARRY,CARRY,CARRY],undefined,{
						role: 'harvester', myflag: flag, home: Game.spawns['Spawn1'].room.name
					});
				}
			}
			if(/reserve/.test(flag)){ //logic to spawn reservers
				var reservers = _.filter(Game.creeps, (creep) =>
					creep.memory.role == 'reserver' && creep.memory.myflag == flag
				);
				if (reservers.length < 1){
					var tospawn = false
					if (Game.flags[flag].memory.reserved){
						var con = Game.flags[flag].pos.lookFor(LOOK_STRUCTURES,{filter: (s) => s.structureType == STRUCTURE_CONTROLLER})[0];
						if(con.reservation.ticksToEnd < 500){
							tospawn = true;
						}
					}
					else{
						tospawn = true;
						Game.flags[flag].memory.reserved = true;
					}
					if(tospawn){
						Game.spawns['Spawn1'].createCreep([MOVE,CLAIM,CLAIM,MOVE],undefined,{
							role: 'reserver', myflag: flag
						});
					}
				}
			}
		}

    }
};<commit_msg>now spawns right amount of harvesters<commit_after>/*
 * Module code goes here. Use 'module.exports' to export things:
 * module.exports.thing = 'a thing';
 *
 * You can import it from another modules like this:
 * var mod = require('respawn');
 * mod.thing == 'a thing'; // true
 */

module.exports = {
    run : function() {
        var harvester_target = 2; //harvesters per remote site
        var upgrader_target = 4;
        var builder_target = 3;
        var miner_target = 2;
        var runner_target = 2;
		var thief_target = 0;
        var hunter_target = 0;

		var hostiles = Game.spawns['Spawn1'].room.find(FIND_HOSTILE_CREEPS)
		if(hostiles.length){
			hunter_target=Math.ceil(hostiles.length/2)
		}

        var upgraders = _.filter(Game.creeps, (creep) => creep.memory.role == 'upgrader');
        var builders = _.filter(Game.creeps, (creep) => creep.memory.role == 'builder');
        var miners = _.filter(Game.creeps, (creep) => creep.memory.role == 'miner');
		var runners = _.filter(Game.creeps, (creep) => creep.memory.role == 'runner');
		var hunters = _.filter(Game.creeps, (creep) => creep.memory.role == 'hunter');
		var thiefs = _.filter(Game.creeps, (creep) => creep.memory.role == 'thief');
//        console.log(harvesters.length + ' ' + upgraders.length + ' ' + builders.length)

		if(miners.length < miner_target){
			Game.spawns['Spawn1'].createCreep([WORK,WORK,WORK,WORK,WORK,MOVE],undefined,{role:'miner'});
		}
		if(runners.length < runner_target){
			Game.spawns['Spawn1'].createCreep([CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE],undefined,{role:'runner'});
		}
        if(upgraders.length < upgrader_target) {
            if (Game.spawns['Spawn1'].room.energyAvailable < 600 && upgraders.length < 1){
                Game.spawns['Spawn1'].createCreep([WORK,CARRY,MOVE],undefined,{role: 'upgrader'});
            }
            else {
				Game.spawns['Spawn1'].createCreep([WORK,WORK,WORK,WORK,CARRY,CARRY,CARRY,CARRY,MOVE,MOVE,MOVE,MOVE],undefined,{role: 'upgrader'});
            }
        }
        if(builders.length < builder_target) {
			if (Game.spawns['Spawn1'].room.energyAvailable < 600 && builders.length < 1){
                Game.spawns['Spawn1'].createCreep([WORK,CARRY,MOVE],undefined,{role: 'builder'});
            }
            else {
				Game.spawns['Spawn1'].createCreep([WORK,WORK,WORK,CARRY,CARRY,CARRY,MOVE,MOVE,MOVE],undefined,{role: 'builder'});
            }
        }
		if(hunters.length < hunter_target) {
			if (Game.spawns['Spawn1'].room.energyAvailable > 600){
                Game.spawns['Spawn1'].createCreep([TOUGH,TOUGH,TOUGH,MOVE,MOVE,MOVE,MOVE,MOVE,ATTACK,ATTACK,ATTACK,MOVE],undefined,{role: 'hunter'});
            }
        }
		if(thiefs.length < thief_target) {
			if (Game.spawns['Spawn1'].room.energyAvailable > 600){
                Game.spawns['Spawn1'].createCreep([CARRY,CARRY,CARRY,CARRY,MOVE,MOVE,MOVE,MOVE],undefined,{role: 'thief'});
            }
        }

		for (var flag in Game.flags){
			if(/harvest/.test(flag)){ //see that every remote site has enough harvesters
				var harvesters = _.filter(Game.creeps, (creep) =>
					creep.memory.role == 'harvester' && creep.memory.myflag == flag
				);
				if (harvesters.length < harvester_target){
					Game.spawns['Spawn1'].createCreep([MOVE,MOVE,MOVE,WORK,WORK,WORK,CARRY,CARRY,CARRY],undefined,{
						role: 'harvester', myflag: flag, home: Game.spawns['Spawn1'].room.name
					});
				}
			}
			if(/reserve/.test(flag)){ //logic to spawn reservers
				var reservers = _.filter(Game.creeps, (creep) =>
					creep.memory.role == 'reserver' && creep.memory.myflag == flag
				);
				if (reservers.length < 1){
					var tospawn = false
					if (Game.flags[flag].memory.reserved){
						var con = Game.flags[flag].pos.lookFor(LOOK_STRUCTURES,{filter: (s) => s.structureType == STRUCTURE_CONTROLLER})[0];
						if(con.reservation.ticksToEnd < 500){
							tospawn = true;
						}
					}
					else{
						tospawn = true;
						Game.flags[flag].memory.reserved = true;
					}
					if(tospawn){
						Game.spawns['Spawn1'].createCreep([MOVE,CLAIM,CLAIM,MOVE],undefined,{
							role: 'reserver', myflag: flag
						});
					}
				}
			}
		}

    }
};<|endoftext|>


<commit_before>// Copyright (c) 2012-2017, Jared Wyles
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

define(function (require) {
    "use strict";

    var FontScale = require('fontscale');
    var monaco = require('monaco');
    var options = require('options');

    require('asm-mode');
    require('selectize');

    function Opt(hub, container, state) {
        this.container = container;
        this.eventHub = hub.createEventHub();
        this.domRoot = container.getElement();
        this.domRoot.html($('#opt').html());
        this.compilers = {};
        this._currentDecorations = [];
        this.optEditor = monaco.editor.create(this.domRoot.find(".monaco-placeholder")[0], {
            value: state.source || "",
            scrollBeyondLastLine: false,
            language: 'cpp', //we only support cpp for now
            readOnly: true,
            glyphMargin: true,
            quickSuggestions: false,
            fixedOverflowWidgets: true
        });

        this._compilerid = state.id;
        this._compilerName = state.compilerName;
        this._editorid = state.editorid;
        this.fontScale = new FontScale(this.domRoot, state, this.optEditor);
        this.fontScale.on('change', _.bind(this.updateState, this));

        this.eventHub.on('compileResult', this.onCompileResult, this);
        this.eventHub.on('compiler', this.onCompiler, this);
        this.eventHub.on('compilerClose', this.onCompilerClose, this);
        this.eventHub.on('editorChange', this.onEditorChange, this);
        this.eventHub.on('themeChange', this.onThemeChange, this);
        this.eventHub.emit('requestTheme');

        this.container.on('destroy', function () {
            this.eventHub.emit("optViewClosed", this._compilerid);
            this.eventHub.unsubscribe();
            this.optEditor.dispose();
        }, this);

        container.on('resize', this.resize, this);
        container.on('shown', this.resize, this);
        if(state && state.optOutput) {
              this.showOptResults(state.optOutput);
        }
        this.setTitle();
    }

    // TODO: de-dupe with compiler etc
    Opt.prototype.resize = function () {
        var topBarHeight = this.domRoot.find(".top-bar").outerHeight(true);
        this.optEditor.layout({
            width: this.domRoot.width(),
            height: this.domRoot.height() - topBarHeight
        });
    };

    Opt.prototype.onEditorChange = function(id, source) {
        if (this._editorid == id) {
            this.optEditor.setValue(source);
        }
    };
    Opt.prototype.onCompileResult = function (id, compiler, result) {
        if(result.hasOptOutput && this._compilerid == id) {
            this.showOptResults(result.optOutput);
        }
    };
    Opt.prototype.setTitle = function () {
          this.container.setTitle(this._compilerName + " Opt Viewer (Editor #" + this._editorid + ", Compiler #" + this._compilerid + ")");
    };

    Opt.prototype.getDisplayableOpt = function (optResult) {
       return "**" + optResult.optType + "** - " + optResult.displayString;
    };

    Opt.prototype.showOptResults = function(results) {
        var opt = [];

        hoverContent = {};
        results = _.filter(results, function(x) {
            return x.DebugLoc !== undefined;
        });

        results = _.groupBy(results, function(x) {
            return x.DebugLoc.Line;
        });

        _.mapObject(results, function(value, key) {
            var linenumber = Number(key);
            var className = value.reduce(function(acc, x) {
                if(acc && acc !== "Analysis" && x.optType !== acc) {
                    return "Mixed";
                } else {
                    return x.optType;
                }
            },"");
            var contents = _.map(value, this.getDisplayableOpt, this);
            opt.push({
                range: new monaco.Range(linenumber,1,linenumber,Infinity),
                options: {
                    isWholeLine: true,
                    glyphMarginClassName: "opt-decoration." + className.toLowerCase(),
                    hoverMessage: contents,
                    glyphMarginHoverMessage: contents
                }
            });
        }, this);

        this._currentDecorations = this.optEditor.deltaDecorations(this._currentDecorations, opt);
    };

    Opt.prototype.onCompiler = function (id, compiler, options, editorid) {
        if(id == this._compilerid) {
            this._compilerName = compiler.name;
            this._editorid = editorid;
            this.setTitle();
        }
    };

    Opt.prototype.onCompilerClose = function (id) {
        delete this.compilers[id];
    };

    Opt.prototype.onThemeChange = function (newTheme) {
        if (this.optEditor) {
            this.optEditor.updateOptions({theme: newTheme.monaco});
        }
    };

    Opt.prototype.updateState = function () {
    };

    return {
        Opt: Opt
    };
});
<commit_msg>Improvements<commit_after>// Copyright (c) 2012-2017, Jared Wyles
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

define(function (require) {
    "use strict";

    var FontScale = require('fontscale');
    var monaco = require('monaco');
    var options = require('options');

    require('asm-mode');
    require('selectize');

    function Opt(hub, container, state) {
        this.container = container;
        this.eventHub = hub.createEventHub();
        this.domRoot = container.getElement();
        this.domRoot.html($('#opt').html());
        this.compilers = {};
        this._currentDecorations = [];
        this.optEditor = monaco.editor.create(this.domRoot.find(".monaco-placeholder")[0], {
            value: state.source || "",
            scrollBeyondLastLine: false,
            language: 'cpp', //we only support cpp for now
            readOnly: true,
            glyphMargin: true,
            quickSuggestions: false,
            fixedOverflowWidgets: true
        });

        this._compilerid = state.id;
        this._compilerName = state.compilerName;
        this._editorid = state.editorid;
        this.fontScale = new FontScale(this.domRoot, state, this.optEditor);
        this.fontScale.on('change', _.bind(this.updateState, this));

        this.eventHub.on('compileResult', this.onCompileResult, this);
        this.eventHub.on('compiler', this.onCompiler, this);
        this.eventHub.on('compilerClose', this.onCompilerClose, this);
        this.eventHub.on('editorChange', this.onEditorChange, this);
        this.eventHub.on('themeChange', this.onThemeChange, this);
        this.eventHub.emit('requestTheme');

        this.container.on('destroy', function () {
            this.eventHub.emit("optViewClosed", this._compilerid);
            this.eventHub.unsubscribe();
            this.optEditor.dispose();
        }, this);

        container.on('resize', this.resize, this);
        container.on('shown', this.resize, this);
        if(state && state.optOutput) {
              this.showOptResults(state.optOutput);
        }
        this.setTitle();
    }

    // TODO: de-dupe with compiler etc
    Opt.prototype.resize = function () {
        var topBarHeight = this.domRoot.find(".top-bar").outerHeight(true);
        this.optEditor.layout({
            width: this.domRoot.width(),
            height: this.domRoot.height() - topBarHeight
        });
    };

    Opt.prototype.onEditorChange = function(id, source) {
        if (this._editorid == id) {
            this.optEditor.setValue(source);
        }
    };
    Opt.prototype.onCompileResult = function (id, compiler, result) {
        if(result.hasOptOutput && this._compilerid == id) {
            this.showOptResults(result.optOutput);
        }
    };
    Opt.prototype.setTitle = function () {
          this.container.setTitle(this._compilerName + " Opt Viewer (Editor #" + this._editorid + ", Compiler #" + this._compilerid + ")");
    };

    Opt.prototype.getDisplayableOpt = function (optResult) {
       return "**" + optResult.optType + "** - " + optResult.displayString;
    };

    Opt.prototype.showOptResults = function(results) {
        var opt = [];

        results = _.filter(results, function(x) {
            return x.DebugLoc !== undefined;
        });

        results = _.groupBy(results, function(x) {
            return x.DebugLoc.Line;
        });

        _.mapObject(results, function(value, key) {
            var linenumber = Number(key);
            var className = value.reduce(function(acc, x) {
                if(acc && acc !== "Analysis" && x.optType !== acc) {
                    return "Mixed";
                } else {
                    return x.optType;
                }
            },"");
            var contents = _.map(value, this.getDisplayableOpt, this);
            opt.push({
                // Infinity also works here as a column limit
                range: new monaco.Range(linenumber,1,linenumber,this.optEditor.getModel().getLineMaxColumn(linenumber)),
                options: {
                    isWholeLine: true,
                    glyphMarginClassName: "opt-decoration." + className.toLowerCase(),
                    hoverMessage: contents,
                    glyphMarginHoverMessage: contents
                }
            });
        }, this);

        this._currentDecorations = this.optEditor.deltaDecorations(this._currentDecorations, opt);
    };

    Opt.prototype.onCompiler = function (id, compiler, options, editorid) {
        if(id == this._compilerid) {
            this._compilerName = compiler.name;
            this._editorid = editorid;
            this.setTitle();
        }
    };

    Opt.prototype.onCompilerClose = function (id) {
        delete this.compilers[id];
    };

    Opt.prototype.onThemeChange = function (newTheme) {
        if (this.optEditor) {
            this.optEditor.updateOptions({theme: newTheme.monaco});
        }
    };

    Opt.prototype.updateState = function () {
    };

    return {
        Opt: Opt
    };
});
<|endoftext|>


<commit_before>"use strict";

var cost = function(body){
	var mycost = 0;
	for(var bodypart of body){
		mycost += BODYPART_COST[bodypart]
	}
	return mycost
}

var bodies = {
	miner : function(maxEnergy){
		var body=[WORK];
		var minEnergy = cost([WORK,MOVE])
		if(maxEnergy > minEnergy){
			var n = Math.min(Math.floor((maxEnergy - minEnergy)/BODYPART_COST[WORK]),4); //a maximum of 5 WORK parts
			for(var i=0; i<n; i++){
				body.push(WORK);
			}
		}
		body.push(MOVE);
		return body
	},

	runner : function(maxEnergy){
		var template = [CARRY,MOVE];
		var intervalEnergy=cost(template);
		var n = Math.min(Math.floor(maxEnergy/intervalEnergy),10); //currently hardcapped at 10
		var body = [];
		for(var i=0;i<n;i++){
			body.push(CARRY,MOVE);
		}
		return body
	},

	civilian : function(maxEnergy){
		var template = [WORK,CARRY,MOVE];
		var intervalEnergy = cost(template);
		var n = Math.min(Math.floor(maxEnergy/intervalEnergy),10); //hardcapped at 10
		var body = [];
		for(var i=0;i<n;i++){
			body.push(WORK,CARRY,MOVE);
		}
		return body
	},

	hunter : function(maxEnergy){
		var toughTemplate = [TOUGH,MOVE];
		var toughCost = cost(toughTemplate);
		var attackTemplate = [ATTACK,MOVE];
		var attackCost = cost(attackTemplate);
		var toughNo = Math.min(Math.floor(maxEnergy/12/toughCost),6); //at most 1/12 of energy should go towards TOUGH parts
		var energyLeft = maxEnergy - toughNo * toughCost;
		var attackNo = Math.min(Math.floor(energyLeft/attackCost),19); //no more than 50 body parts
		var body = [];
		for(var i=0;i<toughNo;i++){
			body.push(TOUGH);
		}
		for(i=0;i<toughNo;i++){
			body.push(MOVE);
		}
		for(i=0;i<attackNo;i++){
			body.push(...attackTemplate);
		}
		return body
	},

	reserver : function(maxEnergy){
		return [MOVE,CLAIM,CLAIM,MOVE];
	}
}

module.exports = {
	run : function(room){
		var spawn = room.find(FIND_STRUCTURES,{filter : (s) => s.structureType == STRUCTURE_SPAWN && s.spawning == null})[0];
		if(spawn==undefined){
			return;
		}
		var maxEnergy = room.energyCapacityAvailable;
		let storage = room.storage;

		var miner_target = room.find(FIND_SOURCES).length;
		var runner_target = 2;
		var civilian_target = 6;
		if(room.controller.level > 3){
			civilian_target = Math.max(Math.min(Math.ceil(20/(bodies.civilian(maxEnergy).length/3))-1,7),2) + ( room.storage != undefined ? Math.floor(room.storage.store.energy/200000) : 0 );
		}
		var hunter_target = 0;
		if(room.memory.underAttack){
			var hostiles = room.find(FIND_HOSTILE_CREEPS,{filter: (c) => !_.contains(playerWhiteList,c.owner.username) }).length;
			hunter_target=Math.ceil(hostiles/2);
		}

		var creepsByRole = _.groupBy(_.filter(Game.creeps,(c) => c.pos.roomName == room.name),'memory.role'); //this also counts spawning creeps
		var miners = creepsByRole.miner != undefined ? creepsByRole.miner.length : 0;
		var runners = creepsByRole.runner != undefined ? creepsByRole.runner.length : 0;
		var civilians = creepsByRole.civilian != undefined ? creepsByRole.civilian.length : 0;
		var hunters = creepsByRole.hunter != undefined ? creepsByRole.hunter.length : 0;

		if(room.memory.requestList === undefined){ //checking this every tick is a waste
			room.memory.requestList = [];
		}
		var requestList = room.memory.requestList;

		//first ensure that at least one miner, one runner and one upgrader is always active
		if(miners < 1){
			spawn.createCreep(bodies.miner(room.energyAvailable),undefined,{role:ROLE_MINER});
		}
		else if(runners < 1){
			spawn.createCreep(bodies.runner(room.energyAvailable),undefined,{role:ROLE_RUNNER});
		}
		else if(civilians < 1 && room.controller.ticksToDowngrade < 500){
			spawn.createCreep(bodies.civilian(room.energyAvailable),undefined,{role:ROLE_CIVILIAN});
		}
		//after essentials are ensured, work on the requestList
		else if(requestList.length > 0){
			if(spawn.canCreateCreep(...requestList[0]) == OK){
				spawn.createCreep(...requestList.shift()) //spawns the first creep in the list and deletes it from the list
				room.memory.requestList = requestList;
			}
		}
		else if(miners < miner_target){
			spawn.createCreep(bodies.miner(maxEnergy),undefined,{role:ROLE_MINER});
		}
		else if(runners < runner_target){
			spawn.createCreep(bodies.runner(maxEnergy),undefined,{role:ROLE_RUNNER});
		}
		else if(hunters < hunter_target){
			spawn.createCreep(bodies.hunter(maxEnergy),undefined,{role:ROLE_HUNTER});
		}
		else if(civilians < civilian_target) {
			spawn.createCreep(bodies.civilian(maxEnergy),undefined,{role:ROLE_CIVILIAN});
		}
		else{
			//do spawning for remoteRooms
			for(remoteRoomName of room.memory.remoteRooms){
				var remoteCreepsByRole = _.groupBy(_.filter(Game.creeps,(c) => c.task && c.task.roomName == remoteRoomName), "memory.role");
				var reservers = remoteCreepsByRole.reserver != undefined ? creepsByRole.reserver.length : 0;
				if(reservers < 1){
					var reservetask = Game.rooms[remoteRoomName].memory.controller
					var controllerId = reservetask.id;
					var controller = Game.getObjectById(controllerId);
					if(controller = null || controller.reservation.ticksToEnd < 500){
						spawn.createCreep(bodies.reserver,undefined,{role:ROLE_RESERVER, task : reservetask});
						return;
					}
				}
				//add more remoteRoomLogic
			}
		}
	}
}
<commit_msg>bugfix<commit_after>"use strict";

var cost = function(body){
	var mycost = 0;
	for(var bodypart of body){
		mycost += BODYPART_COST[bodypart]
	}
	return mycost
}

var bodies = {
	miner : function(maxEnergy){
		var body=[WORK];
		var minEnergy = cost([WORK,MOVE])
		if(maxEnergy > minEnergy){
			var n = Math.min(Math.floor((maxEnergy - minEnergy)/BODYPART_COST[WORK]),4); //a maximum of 5 WORK parts
			for(var i=0; i<n; i++){
				body.push(WORK);
			}
		}
		body.push(MOVE);
		return body
	},

	runner : function(maxEnergy){
		var template = [CARRY,MOVE];
		var intervalEnergy=cost(template);
		var n = Math.min(Math.floor(maxEnergy/intervalEnergy),10); //currently hardcapped at 10
		var body = [];
		for(var i=0;i<n;i++){
			body.push(CARRY,MOVE);
		}
		return body
	},

	civilian : function(maxEnergy){
		var template = [WORK,CARRY,MOVE];
		var intervalEnergy = cost(template);
		var n = Math.min(Math.floor(maxEnergy/intervalEnergy),10); //hardcapped at 10
		var body = [];
		for(var i=0;i<n;i++){
			body.push(WORK,CARRY,MOVE);
		}
		return body
	},

	hunter : function(maxEnergy){
		var toughTemplate = [TOUGH,MOVE];
		var toughCost = cost(toughTemplate);
		var attackTemplate = [ATTACK,MOVE];
		var attackCost = cost(attackTemplate);
		var toughNo = Math.min(Math.floor(maxEnergy/12/toughCost),6); //at most 1/12 of energy should go towards TOUGH parts
		var energyLeft = maxEnergy - toughNo * toughCost;
		var attackNo = Math.min(Math.floor(energyLeft/attackCost),19); //no more than 50 body parts
		var body = [];
		for(var i=0;i<toughNo;i++){
			body.push(TOUGH);
		}
		for(i=0;i<toughNo;i++){
			body.push(MOVE);
		}
		for(i=0;i<attackNo;i++){
			body.push(...attackTemplate);
		}
		return body
	},

	reserver : function(maxEnergy){
		return [MOVE,CLAIM,CLAIM,MOVE];
	}
}

module.exports = {
	run : function(room){
		var spawn = room.find(FIND_STRUCTURES,{filter : (s) => s.structureType == STRUCTURE_SPAWN && s.spawning == null})[0];
		if(spawn==undefined){
			return;
		}
		var maxEnergy = room.energyCapacityAvailable;
		let storage = room.storage;

		var miner_target = room.find(FIND_SOURCES).length;
		var runner_target = 2;
		var civilian_target = 6;
		if(room.controller.level > 3){
			civilian_target = Math.max(Math.min(Math.ceil(20/(bodies.civilian(maxEnergy).length/3))-1,7),2) + ( room.storage != undefined ? Math.floor(room.storage.store.energy/200000) : 0 );
		}
		var hunter_target = 0;
		if(room.memory.underAttack){
			var hostiles = room.find(FIND_HOSTILE_CREEPS,{filter: (c) => !_.contains(playerWhiteList,c.owner.username) }).length;
			hunter_target=Math.ceil(hostiles/2);
		}

		var creepsByRole = _.groupBy(_.filter(Game.creeps,(c) => c.pos.roomName == room.name),'memory.role'); //this also counts spawning creeps
		var miners = creepsByRole.miner != undefined ? creepsByRole.miner.length : 0;
		var runners = creepsByRole.runner != undefined ? creepsByRole.runner.length : 0;
		var civilians = creepsByRole.civilian != undefined ? creepsByRole.civilian.length : 0;
		var hunters = creepsByRole.hunter != undefined ? creepsByRole.hunter.length : 0;

		if(room.memory.requestList === undefined){ //checking this every tick is a waste
			room.memory.requestList = [];
		}
		var requestList = room.memory.requestList;

		//first ensure that at least one miner, one runner and one upgrader is always active
		if(miners < 1){
			spawn.createCreep(bodies.miner(room.energyAvailable),undefined,{role:ROLE_MINER});
		}
		else if(runners < 1){
			spawn.createCreep(bodies.runner(room.energyAvailable),undefined,{role:ROLE_RUNNER});
		}
		else if(civilians < 1 && room.controller.ticksToDowngrade < 500){
			spawn.createCreep(bodies.civilian(room.energyAvailable),undefined,{role:ROLE_CIVILIAN});
		}
		//after essentials are ensured, work on the requestList
		else if(requestList.length > 0){
			if(spawn.canCreateCreep(...requestList[0]) == OK){
				spawn.createCreep(...requestList.shift()) //spawns the first creep in the list and deletes it from the list
				room.memory.requestList = requestList;
			}
		}
		else if(miners < miner_target){
			spawn.createCreep(bodies.miner(maxEnergy),undefined,{role:ROLE_MINER});
		}
		else if(runners < runner_target){
			spawn.createCreep(bodies.runner(maxEnergy),undefined,{role:ROLE_RUNNER});
		}
		else if(hunters < hunter_target){
			spawn.createCreep(bodies.hunter(maxEnergy),undefined,{role:ROLE_HUNTER});
		}
		else if(civilians < civilian_target) {
			spawn.createCreep(bodies.civilian(maxEnergy),undefined,{role:ROLE_CIVILIAN});
		}
		else{
			//do spawning for remoteRooms
			for(var remoteRoomName of room.memory.remoteRooms){
				var remoteCreepsByRole = _.groupBy(_.filter(Game.creeps,(c) => c.task && c.task.roomName == remoteRoomName), "memory.role");
				var reservers = remoteCreepsByRole.reserver != undefined ? creepsByRole.reserver.length : 0;
				if(reservers < 1){
					var reservetask = Game.rooms[remoteRoomName].memory.controller
					var controllerId = reservetask.id;
					var controller = Game.getObjectById(controllerId);
					if(controller = null || controller.reservation.ticksToEnd < 500){
						spawn.createCreep(bodies.reserver,undefined,{role:ROLE_RESERVER, task : reservetask});
						return;
					}
				}
				//add more remoteRoomLogic
			}
		}
	}
}
<|endoftext|>


<commit_before>$.getJSON("../assets/english.json", function(data){
  var treasures = data.treasures;
  $(document).ready(function(){
    for (treasure in treasures)
    {
      opt = $('</option>', {value: treasure.id, text: treasure.name});
      $('#select-item').append(opt);
    }
  });
});
<commit_msg>Update index.js<commit_after>$.getJSON("assets/english.json", function(data){
  var treasures = data.treasures;
  $(document).ready(function(){
    for (treasure in treasures)
    {
      opt = $('</option>', {value: treasure.id, text: treasure.name});
      $('#select-item').append(opt);
    }
  });
});
<|endoftext|>