Removed old Aegis folder.

This was SVN commit r13687.
This commit is contained in:
Michael D. Hafer 2013-08-17 14:12:25 +00:00
parent 42d77129cc
commit 998dc21676
23 changed files with 0 additions and 7034 deletions

View File

@ -1,13 +0,0 @@
Aegis. AI for 0 A.D. ( http://play0ad.com/ ). An effort to improve over two bots: qBot (by Quantumstate, based on TestBot) and Marilyn (by Wraitii, itself based on qBot).
Install by placing files into the data/mods/public/simulation/ai/qbot-wc folder.
You may want to set "debug : true" in config.js if you are developping, you will get a better understanding of what the AI does. There are also many commented debug outputs, and many commented map outputs that you may want to uncomment.
This bot has been made default as of Alpha 13. It features some technological support, early naval support, better economic management, better defense and better attack management (over qBot). It is generally much stronger than the former, and should hopefully be able to handle more situations properly. It is, however, not faultless.
Please report any error to the wildfire games forum ( http://www.wildfiregames.com/forum/index.php?act=idx ), and thanks for playing!
Requires common-api-v3.
(note: no saved game support as of yet).

View File

@ -1 +0,0 @@
Engine.IncludeModule("common-api-v3");

File diff suppressed because it is too large Load Diff

View File

@ -1,123 +0,0 @@
// Baseconfig is the highest difficulty.
var baseConfig = {
"Military" : {
"fortressLapseTime" : 540, // Time to wait between building 2 fortresses
"defenceBuildingTime" : 600, // Time to wait before building towers or fortresses
"attackPlansStartTime" : 0 // time to wait before attacking. Start as soon as possible (first barracks)
},
"Economy" : {
"townPhase" : 180, // time to start trying to reach town phase (might be a while after. Still need the requirements + ress )
"cityPhase" : 540, // time to start trying to reach city phase
"farmsteadStartTime" : 400, // Time to wait before building a farmstead.
"dockStartTime" : 240, // Time to wait before building the dock
"techStartTime" : 600, // time to wait before teching.
"targetNumBuilders" : 1.5, // Base number of builders per foundation. Later updated, but this remains a multiplier.
"femaleRatio" : 0.6 // percent of females among the workforce.
},
// Note: attack settings are set directly in attack_plan.js
// defence
"Defence" : {
"defenceRatio" : 5, // see defence.js for more info.
"armyCompactSize" : 700, // squared. Half-diameter of an army.
"armyBreakawaySize" : 900 // squared.
},
// military
"buildings" : {
"moderate" : {
"default" : [ "structures/{civ}_barracks" ]
},
"advanced" : {
"default" : [],
"hele" : [ "structures/{civ}_gymnasion" ],
"athen" : [ "structures/{civ}_gymnasion" ],
"spart" : [ "structures/{civ}_syssiton" ],
"cart" : [ "structures/{civ}_embassy_celtic",
"structures/{civ}_embassy_iberian", "structures/{civ}_embassy_italiote" ],
"celt" : [ "structures/{civ}_kennel" ],
"pers" : [ "structures/{civ}_fortress", "structures/{civ}_stables", "structures/{civ}_apadana" ],
"rome" : [ "structures/{civ}_army_camp" ],
"maur" : [ "structures/{civ}_elephant_stables"]
},
"fort" : {
"default" : [ "structures/{civ}_fortress" ],
"celt" : [ "structures/{civ}_fortress_b", "structures/{civ}_fortress_g" ]
}
},
// qbot
"priorities" : { // Note these are dynamic, you are only setting the initial values
"house" : 200,
"citizenSoldier" : 70,
"villager" : 55,
"economicBuilding" : 70,
"dropsites" : 120,
"field" : 1000,
"militaryBuilding" : 90,
"defenceBuilding" : 70,
"majorTech" : 400,
"minorTech" : 40,
"civilCentre" : 10000 // will hog all resources
},
"difficulty" : 2, // for now 2 is "hard", ie default. 1 is normal, 0 is easy. 3 is very hard
"debug" : false
};
var Config = {
"debug": false,
"difficulty" : 2, // overriden by the GUI
updateDifficulty: function(difficulty)
{
Config.difficulty = difficulty;
// changing settings based on difficulty.
if (Config.difficulty === 1 && 0) // deactivated for the time being. Medium is basic mode.
{
Config["Military"] = {
"fortressLapseTime" : 900,
"defenceBuildingTime" : 720,
"attackPlansStartTime" : 600
};
Config["Economy"] = {
"townPhase" : 360,
"cityPhase" : 900,
"farmsteadStartTime" : 600,
"dockStartTime" : 240,
"techStartTime" : 1320,
"targetNumBuilders" : 2,
"femaleRatio" : 0.5,
"targetNumWorkers" : 110 // should not make more than 2 barracks.
};
Config["Defence"] = {
"defenceRatio" : 4.0,
"armyCompactSize" : 700,
"armyBreakawaySize" : 900
};
} else if (Config.difficulty === 0)
{
Config["Military"] = {
"fortressLapseTime" : 1000000, // never
"defenceBuildingTime" : 900,
"attackPlansStartTime" : 1200 // 20 minutes ought to give enough times for beginners
};
Config["Economy"] = {
"townPhase" : 480,
"cityPhase" : 1200,
"farmsteadStartTime" : 1200,
"dockStartTime" : 240,
"techStartTime" : 600000, // never
"targetNumBuilders" : 1,
"femaleRatio" : 0.0, // makes us slower, but also less sucky at defending so it's still fun to attack it.
"targetNumWorkers" : 80 // we will make advanced buildings and a fortress (and a market), but nothing more.
};
Config["Defence"] = {
"defenceRatio" : 2.0,
"armyCompactSize" : 700,
"armyBreakawaySize" : 900
};
}
}
};
Config.__proto__ = baseConfig;

View File

@ -1,6 +0,0 @@
{
"name": "Aegis Bot",
"description": "Wraitii's improvement of qBot. It is more reliable and generally a better player. Note that it doesn't support saved games yet, and there may be other bugs. Please report issues to Wildfire Games (see the link in the main menu).",
"constructor": "QBotAI",
"useShared": true
}

View File

@ -1,830 +0,0 @@
// directly imported from Marilyn, with slight modifications to work with qBot.
function Defence(){
this.defenceRatio = Config.Defence.defenceRatio;// How many defenders we want per attacker. Need to balance fewer losses vs. lost economy
// note: the choice should be a no-brainer most of the time: better deflect the attack.
// This is also sometimes forcebly overcome by the defense manager.
this.armyCompactSize = Config.Defence.armyCompactSize; // a bit more than 40 wide in diameter
this.armyBreakawaySize = Config.Defence.armyBreakawaySize; // a bit more than 45 wide in diameter
this.totalAttackNb = 0; // used for attack IDs
this.attacks = [];
this.toKill = [];
// keeps a list of targeted enemy at instant T
this.enemyArmy = {}; // array of players, storing for each an array of armies.
this.attackerCache = {};
this.listOfEnemies = {};
this.listedEnemyCollection = null; // entity collection of this.listOfEnemies
// Some Stats
this.nbAttackers = 0;
this.nbDefenders = 0;
// Caching variables
this.totalArmyNB = 0;
this.enemyUnits = {};
this.enemyArmyLoop = {};
// boolean 0/1 that's for optimization
this.attackerCacheLoopIndicator = 0;
// this is a list of units to kill. They should be gaia animals, or lonely units. Works the same as listOfEnemies, ie an entityColelction which I'll have to cleanup
this.listOfWantedUnits = {};
this.WantedUnitsAttacker = {}; // same as attackerCache.
this.defenders = null;
this.idleDefs = null;
}
// DO NOTE: the Defence manager, when it calls for Defence, makes the military manager go into "Defence mode"... This makes it not update any plan that's started or not.
// This allows the Defence manager to take units from the plans for Defence.
// Defcon levels
// 5: no danger whatsoever detected
// 4: a few enemy units are being dealt with, but nothing too dangerous.
// 3: A reasonnably sized enemy army is being dealt with, but it should not be a problem.
// 2: A big enemy army is in the base, but we are not outnumbered
// 1: Huge army in the base, outnumbering us.
Defence.prototype.update = function(gameState, events, militaryManager){
Engine.ProfileStart("Defence Manager");
// a litlle cache-ing
if (!this.idleDefs) {
var filter = Filters.and(Filters.byMetadata(PlayerID, "role", "defence"), Filters.isIdle());
this.idleDefs = gameState.getOwnEntities().filter(filter);
this.idleDefs.registerUpdates();
}
if (!this.defenders) {
var filter = Filters.byMetadata(PlayerID, "role", "defence");
this.defenders = gameState.getOwnEntities().filter(filter);
this.defenders.registerUpdates();
}
/*if (!this.listedEnemyCollection) {
var filter = Filters.byMetadata(PlayerID, "listed-enemy", true);
this.listedEnemyCollection = gameState.getEnemyEntities().filter(filter);
this.listedEnemyCollection.registerUpdates();
}
this.myBuildings = gameState.getOwnEntities().filter(Filters.byClass("Structure")).toEntityArray();
this.myUnits = gameState.getOwnEntities().filter(Filters.byClass("Unit"));
*/
var filter = Filters.and(Filters.byClassesOr(["CitizenSoldier", "Hero", "Champion", "Siege"]), Filters.byOwner(PlayerID));
this.myUnits = gameState.updatingGlobalCollection("player-" +PlayerID + "-soldiers", filter);
filter = Filters.and(Filters.byClass("Structure"), Filters.byOwner(PlayerID));
this.myBuildings = gameState.updatingGlobalCollection("player-" +PlayerID + "-structures", filter);
this.territoryMap = Map.createTerritoryMap(gameState); // used by many func
// First step: we deal with enemy armies, those are the highest priority.
this.defendFromEnemies(gameState, events, militaryManager);
// second step: we loop through messages, and sort things as needed (dangerous buildings, attack by animals, ships, lone units, whatever).
// TODO : a lot.
this.MessageProcess(gameState,events,militaryManager);
this.DealWithWantedUnits(gameState,events,militaryManager);
/*
var self = this;
// putting unneeded units at rest
this.idleDefs.forEach(function(ent) {
if (ent.getMetadata(PlayerID, "formerrole"))
ent.setMetadata(PlayerID, "role", ent.getMetadata(PlayerID, "formerrole") );
else
ent.setMetadata(PlayerID, "role", "worker");
ent.setMetadata(PlayerID, "subrole", undefined);
self.nbDefenders--;
});*/
Engine.ProfileStop();
return;
};
/*
// returns armies that are still seen as dangerous (in the LOS of any of my buildings for now)
Defence.prototype.reevaluateDangerousArmies = function(gameState, armies) {
var stillDangerousArmies = {};
for (var i in armies) {
var pos = armies[i].getCentrePosition();
if (pos === undefined)
if (+this.territoryMap.point(pos) - 64 === +PlayerID) {
stillDangerousArmies[i] = armies[i];
continue;
}
for (var o in this.myBuildings) {
// if the armies out of my buildings LOS (with a little more, because we're cheating right now and big armies could go undetected)
if (inRange(pos, this.myBuildings[o].position(),this.myBuildings[o].visionRange()*this.myBuildings[o].visionRange() + 2500)) {
stillDangerousArmies[i] = armies[i];
break;
}
}
}
return stillDangerousArmies;
}
// returns armies we now see as dangerous, ie in my territory
Defence.prototype.evaluateArmies = function(gameState, armies) {
var DangerousArmies = {};
for (var i in armies) {
if (armies[i].getCentrePosition() && +this.territoryMap.point(armies[i].getCentrePosition()) - 64 === +PlayerID) {
DangerousArmies[i] = armies[i];
}
}
return DangerousArmies;
}*/
// Incorporates an entity in an army. If no army fits, it creates a new one around this one.
// an army is basically an entity collection.
Defence.prototype.armify = function(gameState, entity, militaryManager, minNBForArmy) {
if (entity.position() === undefined)
return;
if (this.enemyArmy[entity.owner()] === undefined)
{
this.enemyArmy[entity.owner()] = {};
} else {
for (var armyIndex in this.enemyArmy[entity.owner()])
{
var army = this.enemyArmy[entity.owner()][armyIndex];
if (army.getCentrePosition() === undefined)
{
} else {
if (SquareVectorDistance(army.getCentrePosition(), entity.position()) < this.armyCompactSize)
{
entity.setMetadata(PlayerID, "inArmy", armyIndex);
army.addEnt(entity);
return;
}
}
}
}
if (militaryManager)
{
var self = this;
var close = militaryManager.enemyWatchers[entity.owner()].enemySoldiers.filter(Filters.byDistance(entity.position(), self.armyCompactSize));
if (!minNBForArmy || close.length >= minNBForArmy)
{
// if we're here, we need to create an army for it, and freeze it to make sure no unit will be added automatically
var newArmy = new EntityCollection(gameState.sharedScript, {}, [Filters.byOwner(entity.owner())]);
newArmy.addEnt(entity);
newArmy.freeze();
newArmy.registerUpdates();
entity.setMetadata(PlayerID, "inArmy", this.totalArmyNB);
this.enemyArmy[entity.owner()][this.totalArmyNB] = newArmy;
close.forEach(function (ent) { //}){
if (ent.position() !== undefined && self.reevaluateEntity(gameState, ent))
{
ent.setMetadata(PlayerID, "inArmy", self.totalArmyNB);
self.enemyArmy[ent.owner()][self.totalArmyNB].addEnt(ent);
}
});
this.totalArmyNB++;
}
} else {
// if we're here, we need to create an army for it, and freeze it to make sure no unit will be added automatically
var newArmy = new EntityCollection(gameState.sharedScript, {}, [Filters.byOwner(entity.owner())]);
newArmy.addEnt(entity);
newArmy.freeze();
newArmy.registerUpdates();
entity.setMetadata(PlayerID, "inArmy", this.totalArmyNB);
this.enemyArmy[entity.owner()][this.totalArmyNB] = newArmy;
this.totalArmyNB++;
}
return;
}
// Returns if a unit should be seen as dangerous or not.
Defence.prototype.evaluateRawEntity = function(gameState, entity) {
if (entity.position && +this.territoryMap.point(entity.position) - 64 === +PlayerID && entity._template.Attack !== undefined)
return true;
return false;
}
Defence.prototype.evaluateEntity = function(gameState, entity) {
if (!entity.position())
return false;
if (this.territoryMap.point(entity.position()) - 64 === entity.owner() || entity.attackTypes() === undefined)
return false;
for (var i in this.myBuildings._entities)
{
if (!this.myBuildings._entities[i].hasClass("ConquestCritical"))
continue;
if (SquareVectorDistance(this.myBuildings._entities[i].position(), entity.position()) < 6000)
return true;
}
return false;
}
// returns false if the unit is in its territory
Defence.prototype.reevaluateEntity = function(gameState, entity) {
if ( (entity.position() && +this.territoryMap.point(entity.position()) - 64 === +entity.owner()) || entity.attackTypes() === undefined)
return false;
return true;
}
// This deals with incoming enemy armies, setting the defcon if needed. It will take new soldiers, and assign them to attack
// TODO: still is still pretty dumb, it could use improvements.
Defence.prototype.defendFromEnemies = function(gameState, events, militaryManager) {
var self = this;
// New, faster system will loop for enemy soldiers, and also females on occasions ( TODO )
// if a dangerous unit is found, it will check for neighbors and make them into an "army", an entityCollection
// > updated against owner, for the day when I throw healers in the deal.
// armies are checked against each other now and then to see if they should be merged, and units in armies are checked to see if they should be taken away from the army.
// We keep a list of idle defenders. For any new attacker, we'll check if we have any idle defender available, and if not, we assign available units.
// At the end of each turn, if we still have idle defenders, we either assign them to neighboring units, or we release them.
var nbOfAttackers = 0; // actually new attackers.
var newEnemies = [];
// clean up using events.
for each(var evt in events)
{
if (evt.type == "Destroy")
{
if (this.listOfEnemies[evt.msg.entity] !== undefined)
{
if (this.attackerCache[evt.msg.entity] !== undefined) {
this.attackerCache[evt.msg.entity].forEach(function(ent) { ent.stopMoving(); });
delete self.attackerCache[evt.msg.entity];
}
delete this.listOfEnemies[evt.msg.entity];
this.nbAttackers--;
} else if (evt.msg.entityObj && evt.msg.entityObj.owner() === PlayerID && evt.msg.metadata[PlayerID] && evt.msg.metadata[PlayerID]["role"]
&& evt.msg.metadata[PlayerID]["role"] === "defence")
{
// lost a brave man there.
this.nbDefenders--;
}
}
}
// Optimizations: this will slowly iterate over all units (saved at an instant T) and all armies.
// It'll add new units if they are now dangerous and were not before
// It'll also deal with cleanup of armies.
// When it's finished it'll start over.
for (var enemyID in this.enemyArmy)
{
//this.enemyUnits[enemyID] = militaryManager.enemyWatchers[enemyID].getAllEnemySoldiers();
if (this.enemyUnits[enemyID] === undefined || this.enemyUnits[enemyID].length === 0)
{
this.enemyUnits[enemyID] = militaryManager.enemyWatchers[enemyID].enemySoldiers.toEntityArray();
} else {
// we have some units still to check in this array. Check 15 (TODO: DIFFLEVEL)
// Note: given the way memory works, if the entity has been recently deleted, its reference may still exist.
// and this.enemyUnits[enemyID][0] may still point to that reference, "reviving" the unit.
// So we've got to make sure it's not supposed to be dead.
for (var check = 0; check < 20; check++)
{
if (this.enemyUnits[enemyID].length > 0 && gameState.getEntityById(this.enemyUnits[enemyID][0].id()) !== undefined)
{
if (this.enemyUnits[enemyID][0].getMetadata(PlayerID, "inArmy") !== undefined)
{
this.enemyUnits[enemyID].splice(0,1);
} else {
var dangerous = this.evaluateEntity(gameState, this.enemyUnits[enemyID][0]);
if (dangerous)
this.armify(gameState, this.enemyUnits[enemyID][0], militaryManager,2);
this.enemyUnits[enemyID].splice(0,1);
}
} else if (this.enemyUnits[enemyID].length > 0 && gameState.getEntityById(this.enemyUnits[enemyID][0].id()) === undefined)
{
this.enemyUnits[enemyID].splice(0,1);
}
}
}
// okay then we'll check one of the armies
// creating the array to iterate over.
if (this.enemyArmyLoop[enemyID] === undefined || this.enemyArmyLoop[enemyID].length === 0)
{
this.enemyArmyLoop[enemyID] = [];
for (var i in this.enemyArmy[enemyID])
this.enemyArmyLoop[enemyID].push([this.enemyArmy[enemyID][i],i]);
}
// and now we check the last known army.
if (this.enemyArmyLoop[enemyID].length !== 0) {
var army = this.enemyArmyLoop[enemyID][0][0];
var position = army.getCentrePosition();
if (!position)
{
var index = this.enemyArmyLoop[enemyID][0][1];
delete this.enemyArmy[enemyID][index];
this.enemyArmyLoop[enemyID].splice(0,1);
} else {
army.forEach(function (ent) { //}){
// check if the unit is a breakaway
if (ent.position() && SquareVectorDistance(position, ent.position()) > self.armyBreakawaySize)
{
ent.setMetadata(PlayerID, "inArmy", undefined);
army.removeEnt(ent);
if (self.evaluateEntity(gameState,ent))
self.armify(gameState,ent);
} else {
// check if we have registered that unit already.
if (self.listOfEnemies[ent.id()] === undefined) {
self.listOfEnemies[ent.id()] = new EntityCollection(gameState.sharedScript, {}, [Filters.byOwner(ent.owner())]);
self.listOfEnemies[ent.id()].freeze();
self.listOfEnemies[ent.id()].addEnt(ent);
self.listOfEnemies[ent.id()].registerUpdates();
self.attackerCache[ent.id()] = self.myUnits.filter(Filters.byTargetedEntity(ent.id()));
self.attackerCache[ent.id()].registerUpdates();
nbOfAttackers++;
self.nbAttackers++;
newEnemies.push(ent);
} else if (self.attackerCache[ent.id()] === undefined || self.attackerCache[ent.id()].length == 0) {
nbOfAttackers++;
newEnemies.push(ent);
} else if (!self.reevaluateEntity(gameState,ent))
{
ent.setMetadata(PlayerID, "inArmy", undefined);
army.removeEnt(ent);
if (self.attackerCache[ent.id()] !== undefined)
{
self.attackerCache[ent.id()].forEach(function(ent) { ent.stopMoving(); });
delete self.attackerCache[ent.id()];
delete self.listOfEnemies[ent.id()];
self.nbAttackers--;
}
}
}
});
// TODO: check if the army itself is not dangerous anymore.
this.enemyArmyLoop[enemyID].splice(0,1);
}
}
// okay so now the army update is done.
}
// Reordering attack because the pathfinder is for now not dynamically updated
for (var o in this.attackerCache) {
if ((this.attackerCacheLoopIndicator + o) % 2 === 0) {
this.attackerCache[o].forEach(function (ent) {
ent.attack(+o);
});
}
}
this.attackerCacheLoopIndicator++;
this.attackerCacheLoopIndicator = this.attackerCacheLoopIndicator % 2;
if (this.nbAttackers === 0 && this.nbDefenders === 0) {
// Release all our units
this.myUnits.filter(Filters.byMetadata(PlayerID, "role","defence")).forEach(function (defender) { //}){
defender.stopMoving();
if (defender.getMetadata(PlayerID, "formerrole"))
defender.setMetadata(PlayerID, "role", defender.getMetadata(PlayerID, "formerrole") );
else
defender.setMetadata(PlayerID, "role", "worker");
defender.setMetadata(PlayerID, "subrole", undefined);
self.nbDefenders--;
});
militaryManager.ungarrisonAll(gameState);
militaryManager.unpauseAllPlans(gameState);
return;
} else if (this.nbAttackers === 0 && this.nbDefenders !== 0) {
// Release all our units
this.myUnits.filter(Filters.byMetadata(PlayerID, "role","defence")).forEach(function (defender) { //}){
defender.stopMoving();
if (defender.getMetadata(PlayerID, "formerrole"))
defender.setMetadata(PlayerID, "role", defender.getMetadata(PlayerID, "formerrole") );
else
defender.setMetadata(PlayerID, "role", "worker");
defender.setMetadata(PlayerID, "subrole", undefined);
self.nbDefenders--;
});
militaryManager.ungarrisonAll(gameState);
militaryManager.unpauseAllPlans(gameState);
return;
}
if ( (this.nbDefenders < 4 && this.nbAttackers >= 5) || this.nbDefenders === 0) {
militaryManager.ungarrisonAll(gameState);
}
//debug ("total number of attackers:"+ this.nbAttackers);
//debug ("total number of defenders:"+ this.nbDefenders);
// If I'm here, I have a list of enemy units, and a list of my units attacking it (in absolute terms, I could use a list of any unit attacking it).
// now I'll list my idle defenders, then my idle soldiers that could defend.
// and then I'll assign my units.
// and then rock on.
if (this.nbAttackers > 15){
gameState.setDefcon(3);
} else if (this.nbAttackers > 5){
gameState.setDefcon(4);
}
// we're having too many. Release those that attack units already dealt with, or idle ones.
if (this.myUnits.filter(Filters.byMetadata(PlayerID, "role","defence")).length > nbOfAttackers*this.defenceRatio*1.2) {
this.myUnits.filter(Filters.byMetadata(PlayerID, "role","defence")).forEach(function (defender) { //}){
if ( defender.isIdle() || (defender.unitAIOrderData() && defender.unitAIOrderData()["target"])) {
if ( defender.isIdle() || (self.attackerCache[defender.unitAIOrderData()["target"]] && self.attackerCache[defender.unitAIOrderData()["target"]].length > 3)) {
// okay release me.
defender.stopMoving();
if (defender.getMetadata(PlayerID, "formerrole"))
defender.setMetadata(PlayerID, "role", defender.getMetadata(PlayerID, "formerrole") );
else
defender.setMetadata(PlayerID, "role", "worker");
defender.setMetadata(PlayerID, "subrole", undefined);
self.nbDefenders--;
}
}
});
}
var nonDefenders = this.myUnits.filter(Filters.or(Filters.not(Filters.byMetadata(PlayerID, "role","defence")),Filters.isIdle()));
nonDefenders = nonDefenders.filter(Filters.not(Filters.byClass("Female")));
nonDefenders = nonDefenders.filter(Filters.not(Filters.byMetadata(PlayerID, "subrole","attacking")));
var defenceRatio = this.defenceRatio;
if (newEnemies.length + this.nbAttackers > (this.nbDefenders + nonDefenders.length) * 0.8 && this.nbAttackers > 9)
gameState.setDefcon(2);
if (newEnemies.length + this.nbAttackers > (this.nbDefenders + nonDefenders.length) * 1.5 && this.nbAttackers > 5)
gameState.setDefcon(1);
//debug ("newEnemies.length "+ newEnemies.length);
//debug ("nonDefenders.length "+ nonDefenders.length);
if (gameState.defcon() > 3)
militaryManager.unpauseAllPlans(gameState);
if ( (nonDefenders.length + this.nbDefenders > newEnemies.length + this.nbAttackers)
|| this.nbDefenders + nonDefenders.length < 4)
{
var buildings = gameState.getOwnEntities().filter(Filters.byCanGarrison()).toEntityArray();
buildings.forEach( function (struct) {
if (struct.garrisoned() && struct.garrisoned().length)
struct.unloadAll();
});
};
if (newEnemies.length === 0)
return;
/*
if (gameState.defcon() < 2 && (this.nbAttackers-this.nbDefenders) > 15)
{
militaryManager.pauseAllPlans(gameState);
} else if (gameState.defcon() < 3 && this.nbDefenders === 0 && newEnemies.length === 0) {
militaryManager.ungarrisonAll(gameState);
}*/
// A little sorting to target sieges/champions first.
newEnemies.sort (function (a,b) {
var vala = 1;
var valb = 1;
if (a.hasClass("Siege"))
vala = 10;
else if (a.hasClass("Champion") || a.hasClass("Hero"))
vala = 5;
if (b.hasClass("Siege"))
valb = 10;
else if (b.hasClass("Champion") || b.hasClass("Hero"))
valb = 5;
return valb - vala;
});
// For each enemy, we'll pick two units.
for each (var enemy in newEnemies) {
if (nonDefenders.length === 0 || self.nbDefenders >= self.nbAttackers * 1.8)
break;
// garrisoned.
if (enemy.position() === undefined)
continue;
var assigned = self.attackerCache[enemy.id()].length;
var defRatio = defenceRatio;
if (enemy.hasClass("Siege"))
defRatio *= 1.2;
if (assigned >= defRatio)
return;
// We'll sort through our units that can legitimately attack.
var data = [];
for (var id in nonDefenders._entities)
{
var ent = nonDefenders._entities[id];
if (ent.position())
data.push([id, ent, SquareVectorDistance(enemy.position(), ent.position())]);
}
// refine the defenders we want. Since it's the distance squared, it has the effect
// of tending to always prefer closer units, though this refinement should change it slighty.
data.sort(function (a, b) {
var vala = a[2];
var valb = b[2];
// don't defend with siege units unless enemy is also a siege unit.
if (a[1].hasClass("Siege") && !enemy.hasClass("Siege"))
vala *= 9;
if (b[1].hasClass("Siege") && !enemy.hasClass("Siege"))
valb *= 9;
// If it's a siege unit, We basically ignore units that only deal pierce damage.
if (enemy.hasClass("Siege") && a[1].attackStrengths("Melee") !== undefined)
vala /= (a[1].attackStrengths("Melee")["hack"] + a[1].attackStrengths("Melee")["crush"]);
if (enemy.hasClass("Siege") && b[1].attackStrengths("Melee") !== undefined)
valb /= (b[1].attackStrengths("Melee")["hack"] + b[1].attackStrengths("Melee")["crush"]);
// If it's a counter, it's better.
if (a[1].countersClasses(b[1].classes()))
vala *= 0.1; // quite low but remember it's squared distance.
if (b[1].countersClasses(a[1].classes()))
valb *= 0.1;
// If the unit is idle, we prefer. ALso if attack plan.
if ((a[1].isIdle() || a[1].getMetadata(PlayerID, "plan") !== undefined) && !a[1].hasClass("Siege"))
vala *= 0.15;
if ((b[1].isIdle() || b[1].getMetadata(PlayerID, "plan") !== undefined) && !b[1].hasClass("Siege"))
valb *= 0.15;
return (vala - valb); });
var ret = {};
for each (var val in data.slice(0, Math.min(nonDefenders._length, defRatio - assigned)))
ret[val[0]] = val[1];
var defs = new EntityCollection(nonDefenders._ai, ret);
// successfully sorted
defs.forEach(function (defender) { //}){
if (defender.getMetadata(PlayerID, "plan") != undefined && (gameState.defcon() < 4 || defender.getMetadata(PlayerID,"subrole") == "walking"))
militaryManager.pausePlan(gameState, defender.getMetadata(PlayerID, "plan"));
//debug ("Against " +enemy.id() + " Assigning " + defender.id());
if (defender.getMetadata(PlayerID, "role") == "worker" || defender.getMetadata(PlayerID, "role") == "attack")
defender.setMetadata(PlayerID, "formerrole", defender.getMetadata(PlayerID, "role"));
defender.setMetadata(PlayerID, "role","defence");
defender.setMetadata(PlayerID, "subrole","defending");
defender.attack(+enemy.id());
defender._entity.idle = false; // hack to prevent a bug as informations aren't updated during a turn
nonDefenders.updateEnt(defender);
assigned++;
self.nbDefenders++;
});
/*if (gameState.defcon() <= 3)
{
// let's try to garrison neighboring females.
var buildings = gameState.getOwnEntities().filter(Filters.byCanGarrison()).toEntityArray();
var females = gameState.getOwnEntities().filter(Filters.byClass("Support"));
var cache = {};
var garrisoned = false;
females.forEach( function (ent) { //}){
garrisoned = false;
if (ent.position())
{
if (SquareVectorDistance(ent.position(), enemy.position()) < 3500)
{
for (var i in buildings)
{
var struct = buildings[i];
if (!cache[struct.id()])
cache[struct.id()] = 0;
if (struct.garrisoned() && struct.garrisonMax() - struct.garrisoned().length - cache[struct.id()] > 0)
{
garrisoned = true;
ent.garrison(struct);
cache[struct.id()]++;
break;
}
}
if (!garrisoned) {
ent.flee(enemy);
ent.setMetadata(PlayerID,"fleeing", gameState.getTimeElapsed());
}
}
}
});
}*/
}
return;
}
// this processes the attackmessages
// So that a unit that gets attacked will not be completely dumb.
// warning: huge levels of indentation coming.
Defence.prototype.MessageProcess = function(gameState,events, militaryManager) {
var self = this;
for (var key in events){
var e = events[key];
if (e.type === "Attacked" && e.msg){
if (gameState.isEntityOwn(gameState.getEntityById(e.msg.target))) {
var attacker = gameState.getEntityById(e.msg.attacker);
var ourUnit = gameState.getEntityById(e.msg.target);
// the attacker must not be already dead, and it must not be me (think catapults that miss).
if (attacker !== undefined && attacker.owner() !== PlayerID && attacker.position() !== undefined) {
// note: our unit can already by dead by now... We'll then have to rely on the enemy to react.
// if we're not on enemy territory
var territory = +this.territoryMap.point(attacker.position()) - 64;
// we do not consider units that are defenders, and we do not consider units that are part of an attacking attack plan
// (attacking attacking plans are dealing with threats on their own).
if (ourUnit !== undefined && (ourUnit.getMetadata(PlayerID, "role") == "defence" || ourUnit.getMetadata(PlayerID, "role") == "attack"))
continue;
// let's check for animals
if (attacker.owner() == 0) {
// if our unit is still alive, we make it react
// in this case we attack.
if (ourUnit !== undefined) {
if (ourUnit.hasClass("Unit") && !ourUnit.hasClass("Support"))
ourUnit.attack(e.msg.attacker);
else {
ourUnit.flee(attacker);
ourUnit.setMetadata(PlayerID,"fleeing", gameState.getTimeElapsed());
}
}
if (territory === PlayerID)
{
// anyway we'll register the animal as dangerous, and attack it (note: only on our territory. Don't care otherwise).
this.listOfWantedUnits[attacker.id()] = new EntityCollection(gameState.sharedScript);
this.listOfWantedUnits[attacker.id()].addEnt(attacker);
this.listOfWantedUnits[attacker.id()].freeze();
this.listOfWantedUnits[attacker.id()].registerUpdates();
var filter = Filters.byTargetedEntity(attacker.id());
this.WantedUnitsAttacker[attacker.id()] = this.myUnits.filter(filter);
this.WantedUnitsAttacker[attacker.id()].registerUpdates();
}
} // preliminary check: we do not count attacked military units (for sanity for now, TODO).
else if ( (territory != attacker.owner() && ourUnit.hasClass("Support")) || (!ourUnit.hasClass("Support") && territory == PlayerID))
{
// Also TODO: this does not differentiate with buildings...
// These ought to be treated differently.
// units in attack plans will react independently, but we still list the attacks here.
if (attacker.hasClass("Structure")) {
// todo: we ultimately have to check wether it's a danger point or an isolated area, and if it's a danger point, mark it as so.
// Right now, to make the AI less gameable, we'll mark any surrounding resource as inaccessible.
// usual tower range is 80. Be on the safe side.
var close = gameState.getResourceSupplies("wood").filter(Filters.byDistance(attacker.position(), 90));
close.forEach(function (supply) { //}){
supply.setMetadata(PlayerID, "inaccessible", true);
});
} else {
// TODO: right now a soldier always retaliate... Perhaps it should be set in "Defence" mode.
if (!attacker.hasClass("Female") && !attacker.hasClass("Ship")) {
// This unit is dangerous. if it's in an army, it's being dealt with.
// if it's not in an army, it means it's either a lone raider, or it has got friends.
// In which case we must check for other dangerous units around, and perhaps armify them.
// TODO: perhaps someday army detection will have improved and this will require change.
var armyID = attacker.getMetadata(PlayerID, "inArmy");
if (armyID == undefined || !this.enemyArmy[attacker.owner()] || !this.enemyArmy[attacker.owner()][armyID]) {
if (this.reevaluateEntity(gameState, attacker))
{
var position = attacker.position();
var close = militaryManager.enemyWatchers[attacker.owner()].enemySoldiers.filter(Filters.byDistance(position, self.armyCompactSize));
if (close.length > 2 || ourUnit.hasClass("Support") || attacker.hasClass("Siege"))
{
// armify it, then armify units close to him.
this.armify(gameState,attacker);
armyID = attacker.getMetadata(PlayerID, "inArmy");
close.forEach(function (ent) { //}){
if (SquareVectorDistance(position, ent.position()) < self.armyCompactSize)
{
ent.setMetadata(PlayerID, "inArmy", armyID);
self.enemyArmy[ent.owner()][armyID].addEnt(ent);
}
});
return; // don't use too much processing power. If there are other cases, they'll be processed soon enough.
}
}
// Defencemanager will deal with them in the next turn.
}
if (ourUnit && ourUnit.hasClass("Unit")) {
if (ourUnit.hasClass("Support")) {
// let's try to garrison this support unit.
if (ourUnit.position())
{
var buildings = gameState.getOwnEntities().filter(Filters.byCanGarrison()).filterNearest(ourUnit.position(),4).toEntityArray();
var garrisoned = false;
for (var i in buildings)
{
var struct = buildings[i];
if (struct.garrisoned() && struct.garrisonMax() - struct.garrisoned().length > 0)
{
garrisoned = true;
ourUnit.garrison(struct);
break;
}
}
if (!garrisoned) {
ourUnit.flee(attacker);
ourUnit.setMetadata(PlayerID,"fleeing", gameState.getTimeElapsed());
}
}
} else {
// It's a soldier. Right now we'll retaliate
// TODO: check for stronger units against this type, check for fleeing options, etc.
// Check also for neighboring towers and garrison there perhaps?
ourUnit.attack(e.msg.attacker);
}
}
}
}
}
}
}
}
}
}; // nice sets of closing brackets, isn't it?
// At most, this will put defcon to 4
Defence.prototype.DealWithWantedUnits = function(gameState, events, militaryManager) {
//if (gameState.defcon() < 3)
// return;
var self = this;
var nbOfAttackers = 0;
var nbOfDealtWith = 0;
// clean up before adding new units (slight speeding up, since new units can't already be dead)
for (var i in this.listOfWantedUnits) {
if (this.listOfWantedUnits[i].length === 0 || this.listOfEnemies[i] !== undefined) { // unit died/was converted/is already dealt with as part of an army
delete this.WantedUnitsAttacker[i];
delete this.listOfWantedUnits[i];
} else {
nbOfAttackers++;
if (this.WantedUnitsAttacker[i].length > 0)
nbOfDealtWith++;
}
}
// note: we can deal with units the way we want because anyway, the Army Defender has already done its task.
// If there are still idle defenders here, it's because they aren't needed.
// I can also call other units: they're not needed.
// Note however that if the defcon level is too high, this won't do anything because it's low priority.
// this also won't take units from attack managers
if (nbOfAttackers === 0)
return;
// at most, we'll deal with 3 enemies at once.
if (nbOfDealtWith >= 3)
return;
// dynamic properties are not updated nearly fast enough here so a little caching
var addedto = {};
// we send 3 units to each target just to be sure. TODO refine.
// we do not use plan units
this.idleDefs.forEach(function(ent) {
if (nbOfDealtWith < 3 && nbOfAttackers > 0 && ent.getMetadata(PlayerID, "plan") == undefined)
for (var o in self.listOfWantedUnits) {
if ( (addedto[o] == undefined && self.WantedUnitsAttacker[o].length < 3) || (addedto[o] && self.WantedUnitsAttacker[o].length + addedto[o] < 3)) {
if (self.WantedUnitsAttacker[o].length === 0)
nbOfDealtWith++;
ent.setMetadata(PlayerID, "formerrole", ent.getMetadata(PlayerID, "role"));
ent.setMetadata(PlayerID, "role","defence");
ent.setMetadata(PlayerID, "subrole", "defending");
ent.attack(+o);
if (addedto[o])
addedto[o]++;
else
addedto[o] = 1;
break;
}
if (self.WantedUnitsAttacker[o].length == 3)
nbOfAttackers--; // we hav eenough units, mark this one as being OKAY
}
});
// still some undealt with attackers, recruit citizen soldiers
if (nbOfAttackers > 0 && nbOfDealtWith < 2) {
gameState.setDefcon(4);
var newSoldiers = gameState.getOwnEntitiesByRole("worker");
newSoldiers.forEach(function(ent) {
// If we're not female, we attack
if (ent.hasClass("CitizenSoldier"))
if (nbOfDealtWith < 3 && nbOfAttackers > 0)
for (var o in self.listOfWantedUnits) {
if ( (addedto[o] == undefined && self.WantedUnitsAttacker[o].length < 3) || (addedto[o] && self.WantedUnitsAttacker[o].length + addedto[o] < 3)) {
if (self.WantedUnitsAttacker[o].length === 0)
nbOfDealtWith++;
ent.setMetadata(PlayerID, "formerrole", ent.getMetadata(PlayerID, "role"));
ent.setMetadata(PlayerID, "role","defence");
ent.setMetadata(PlayerID, "subrole", "defending");
ent.attack(+o);
if (addedto[o])
addedto[o]++;
else
addedto[o] = 1;
break;
}
if (self.WantedUnitsAttacker[o].length == 3)
nbOfAttackers--; // we hav eenough units, mark this one as being OKAY
}
});
}
return;
}

File diff suppressed because it is too large Load Diff

View File

@ -1,212 +0,0 @@
/*
* A class that keeps track of enemy buildings, units, and pretty much anything I can think of (still a LOT TODO here)
* Only watches one enemy, you'll need one per enemy.
* Note: pretty much unused in the current version.
*/
var enemyWatcher = function(gameState, playerToWatch) {
this.watched = playerToWatch;
// using global entity collections, shared by any AI that knows the name of this.
var filter = Filters.and(Filters.byClass("Structure"), Filters.byOwner(this.watched));
this.enemyBuildings = gameState.updatingGlobalCollection("player-" +this.watched + "-structures", filter);
filter = Filters.and(Filters.byClass("Worker"), Filters.byOwner(this.watched));
this.enemyCivilians = gameState.updatingGlobalCollection("player-" +this.watched + "-civilians", filter);
filter = Filters.and(Filters.byClassesOr(["CitizenSoldier", "Hero", "Champion", "Siege"]), Filters.byOwner(this.watched));
this.enemySoldiers = gameState.updatingGlobalCollection("player-" +this.watched + "-soldiers", filter);
filter = Filters.and(Filters.byClass("Worker"), Filters.byOwner(this.watched));
this.enemyCivilians = gameState.getEnemyEntities().filter(filter);
this.enemyCivilians.registerUpdates();
filter = Filters.and(Filters.byClassesOr(["CitizenSoldier", "Hero", "Champion", "Siege"]), Filters.byOwner(this.watched));
this.enemySoldiers = gameState.getEnemyEntities().filter(filter);
this.enemySoldiers.registerUpdates();
// entity collections too.
this.armies = {};
this.enemyBuildingClass = {};
this.totalNBofArmies = 0;
// this is an array of integers, refering to "this.armies[ XX ]"
this.dangerousArmies = [];
};
enemyWatcher.prototype.getAllEnemySoldiers = function() {
return this.enemySoldiers;
};
enemyWatcher.prototype.getAllEnemyBuildings = function() {
return this.enemyBuildings;
};
enemyWatcher.prototype.getEnemyBuildings = function(gameState, specialClass, OneTime) {
var filter = Filters.byClass(specialClass);
if (OneTime && gameState.getGEC("player-" +this.watched + "-structures-" +specialClass))
return gameState.getGEC("player-" +this.watched + "-structures-" +specialClass);
else if (OneTime)
return this.enemyBuildings.filter(filter);
return gameState.updatingGlobalCollection("player-" +this.watched + "-structures-" +specialClass, filter, gameState.getGEC("player-" +this.watched + "-structures"));
};
enemyWatcher.prototype.getDangerousArmies = function() {
var toreturn = {};
for (var i in this.dangerousArmies)
toreturn[this.dangerousArmies[i]] = this.armies[this.dangerousArmies[i]];
return toreturn;
};
enemyWatcher.prototype.getSafeArmies = function() {
var toreturn = {};
for (var i in this.armies)
if (this.dangerousArmies.indexOf(i) == -1)
toreturn[i] = this.armies[i];
return toreturn;
};
enemyWatcher.prototype.resetDangerousArmies = function() {
this.dangerousArmies = [];
};
enemyWatcher.prototype.setAsDangerous = function(armyID) {
if (this.dangerousArmies.indexOf(armyID) === -1)
this.dangerousArmies.push(armyID);
};
enemyWatcher.prototype.isDangerous = function(armyID) {
if (this.dangerousArmies.indexOf(armyID) === -1)
return false;
return true;
};
// returns [id, army]
enemyWatcher.prototype.getArmyFromMember = function(memberID) {
for (var i in this.armies) {
if (this.armies[i].toIdArray().indexOf(memberID) !== -1)
return [i,this.armies[i]];
}
return undefined;
};
enemyWatcher.prototype.isPartOfDangerousArmy = function(memberID) {
var armyID = this.getArmyFromMember(memberID)[0];
if (this.isDangerous(armyID))
return true;
return false;
};
enemyWatcher.prototype.cleanDebug = function() {
for (var armyID in this.armies) {
var army = this.armies[armyID];
debug ("Army " +armyID);
debug (army.length +" members, centered around " +army.getCentrePosition());
}
}
// this will monitor any unmonitored soldier.
enemyWatcher.prototype.detectArmies = function(gameState){
//this.cleanDebug();
var self = this;
if (gameState.ai.playedTurn % 4 === 0) {
Engine.ProfileStart("Looking for new soldiers");
// let's loop through unmonitored enemy soldiers
this.unmonitoredEnemySoldiers.forEach( function (enemy) { //}){
if (enemy.position() === undefined)
return;
// this was an unmonitored unit, we do not know any army associated with it. We assign it a new army (we'll merge later if needed)
enemy.setMetadata(PlayerID, "monitored","true");
var armyID = gameState.player + "" + self.totalNBofArmies;
self.totalNBofArmies++,
enemy.setMetadata(PlayerID, "EnemyWatcherArmy",armyID);
var filter = Filters.byMetadata(PlayerID, "EnemyWatcherArmy",armyID);
var army = self.enemySoldiers.filter(filter);
self.armies[armyID] = army;
self.armies[armyID].registerUpdates();
self.armies[armyID].length;
});
Engine.ProfileStop();
} else if (gameState.ai.playedTurn % 16 === 3) {
Engine.ProfileStart("Merging");
this.mergeArmies(); // calls "scrap empty armies"
Engine.ProfileStop();
} else if (gameState.ai.playedTurn % 16 === 7) {
Engine.ProfileStart("Splitting");
this.splitArmies(gameState);
Engine.ProfileStop();
}
};
// this will merge any two army who are too close together. The distance for "army" is fairly big.
// note: this doesn't actually merge two entity collections... It simply changes the unit metadatas, and will clear the empty entity collection
enemyWatcher.prototype.mergeArmies = function(){
for (var army in this.armies) {
var firstArmy = this.armies[army];
if (firstArmy.length !== 0) {
var firstAPos = firstArmy.getApproximatePosition(4);
for (var otherArmy in this.armies) {
if (otherArmy !== army && this.armies[otherArmy].length !== 0) {
var secondArmy = this.armies[otherArmy];
// we're not self merging, so we check if the two armies are close together
if (inRange(firstAPos,secondArmy.getApproximatePosition(4), 4000 ) ) {
// okay so we merge the two together
// if the other one was dangerous and we weren't, we're now.
if (this.dangerousArmies.indexOf(otherArmy) !== -1 && this.dangerousArmies.indexOf(army) === -1)
this.dangerousArmies.push(army);
secondArmy.forEach( function(ent) {
ent.setMetadata(PlayerID, "EnemyWatcherArmy",army);
});
}
}
}
}
}
this.ScrapEmptyArmies();
};
enemyWatcher.prototype.ScrapEmptyArmies = function(){
var removelist = [];
for (var army in this.armies) {
if (this.armies[army].length === 0) {
removelist.push(army);
// if the army was dangerous, we remove it from the list
if (this.dangerousArmies.indexOf(army) !== -1)
this.dangerousArmies.splice(this.dangerousArmies.indexOf(army),1);
}
}
for each (var toRemove in removelist) {
delete this.armies[toRemove];
}
};
// splits any unit too far from the centerposition
enemyWatcher.prototype.splitArmies = function(gameState){
var self = this;
var map = Map.createTerritoryMap(gameState);
for (var armyID in this.armies) {
var army = this.armies[armyID];
var centre = army.getApproximatePosition(4);
if (map.getOwner(centre) === gameState.player)
continue;
army.forEach( function (enemy) {
if (enemy.position() === undefined)
return;
if (!inRange(enemy.position(),centre, 3500) ) {
var newArmyID = gameState.player + "" + self.totalNBofArmies;
if (self.dangerousArmies.indexOf(armyID) !== -1)
self.dangerousArmies.push(newArmyID);
self.totalNBofArmies++,
enemy.setMetadata(PlayerID, "EnemyWatcherArmy",newArmyID);
var filter = Filters.byMetadata(PlayerID, "EnemyWatcherArmy",newArmyID);
var newArmy = self.enemySoldiers.filter(filter);
self.armies[newArmyID] = newArmy;
self.armies[newArmyID].registerUpdates();
self.armies[newArmyID].length;
}
});
}
};

View File

@ -1,63 +0,0 @@
// returns some sort of DPS * health factor. If you specify a class, it'll use the modifiers against that class too.
function getMaxStrength(ent, againstClass)
{
var strength = 0.0;
var attackTypes = ent.attackTypes();
var armourStrength = ent.armourStrengths();
var hp = ent.maxHitpoints() / 100.0; // some normalization
for (var typeKey in attackTypes) {
var type = attackTypes[typeKey];
if (type == "Slaughter" || type == "Charged")
continue;
var attackStrength = ent.attackStrengths(type);
var attackRange = ent.attackRange(type);
var attackTimes = ent.attackTimes(type);
for (var str in attackStrength) {
var val = parseFloat(attackStrength[str]);
if (againstClass)
val *= ent.getMultiplierAgainst(type, againstClass);
switch (str) {
case "crush":
strength += (val * 0.085) / 3;
break;
case "hack":
strength += (val * 0.075) / 3;
break;
case "pierce":
strength += (val * 0.065) / 3;
break;
}
}
if (attackRange){
strength += (attackRange.max * 0.0125) ;
}
for (var str in attackTimes) {
var val = parseFloat(attackTimes[str]);
switch (str){
case "repeat":
strength += (val / 100000);
break;
case "prepare":
strength -= (val / 100000);
break;
}
}
}
for (var str in armourStrength) {
var val = parseFloat(armourStrength[str]);
switch (str) {
case "crush":
strength += (val * 0.085) / 3;
break;
case "hack":
strength += (val * 0.075) / 3;
break;
case "pierce":
strength += (val * 0.065) / 3;
break;
}
}
return strength * hp;
};

View File

@ -1,10 +0,0 @@
function EntityCollectionFromIds(gameState, idList){
var ents = {};
for (var i in idList){
var id = idList[i];
if (gameState.entities._entities[id]) {
ents[id] = gameState.entities._entities[id];
}
}
return new EntityCollection(gameState.ai, ents);
}

View File

@ -1,339 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View File

@ -1,378 +0,0 @@
const TERRITORY_PLAYER_MASK = 0x3F;
//TODO: Make this cope with negative cell values
// This is by default a 16-bit map but can be adapted into 8-bit.
function Map(gameState, originalMap, actualCopy){
// get the map to find out the correct dimensions
var gameMap = gameState.getMap();
this.width = gameMap.width;
this.height = gameMap.height;
this.length = gameMap.data.length;
this.maxVal = 65535;
if (originalMap && actualCopy){
this.map = new Uint16Array(this.length);
for (var i = 0; i < originalMap.length; ++i)
this.map[i] = originalMap[i];
} else if (originalMap) {
this.map = originalMap;
} else {
this.map = new Uint16Array(this.length);
}
this.cellSize = gameState.cellSize;
}
Map.prototype.setMaxVal = function(val){
this.maxVal = val;
};
Map.prototype.gamePosToMapPos = function(p){
return [Math.floor(p[0]/this.cellSize), Math.floor(p[1]/this.cellSize)];
};
Map.prototype.point = function(p){
var q = this.gamePosToMapPos(p);
return this.map[q[0] + this.width * q[1]];
};
// returns an 8-bit map.
Map.createObstructionMap = function(gameState, template){
var passabilityMap = gameState.getMap();
var territoryMap = gameState.ai.territoryMap;
// default values
var placementType = "land";
var buildOwn = true;
var buildAlly = true;
var buildNeutral = true;
var buildEnemy = false;
// If there is a template then replace the defaults
if (template){
placementType = template.buildPlacementType();
buildOwn = template.hasBuildTerritory("own");
buildAlly = template.hasBuildTerritory("ally");
buildNeutral = template.hasBuildTerritory("neutral");
buildEnemy = template.hasBuildTerritory("enemy");
}
var obstructionMask = gameState.getPassabilityClassMask("foundationObstruction") | gameState.getPassabilityClassMask("building-land");
if (placementType == "shore")
{
// TODO: this won't change much, should be cached, it's slow.
var obstructionTiles = new Uint8Array(passabilityMap.data.length);
var okay = false;
for (var x = 0; x < passabilityMap.width; ++x)
{
for (var y = 0; y < passabilityMap.height; ++y)
{
okay = false;
var i = x + y*passabilityMap.width;
var tilePlayer = (territoryMap.data[i] & TERRITORY_PLAYER_MASK);
var positions = [[0,1], [1,1], [1,0], [1,-1], [0,-1], [-1,-1], [-1,0], [-1,1]];
var available = 0;
for each (var stuff in positions)
{
var index = x + stuff[0] + (y+stuff[1])*passabilityMap.width;
var index2 = x + stuff[0]*2 + (y+stuff[1]*2)*passabilityMap.width;
var index3 = x + stuff[0]*3 + (y+stuff[1]*3)*passabilityMap.width;
var index4 = x + stuff[0]*4 + (y+stuff[1]*4)*passabilityMap.width;
if ((passabilityMap.data[index] & gameState.getPassabilityClassMask("default")) && gameState.ai.accessibility.getRegionSizei(index) > 500)
if ((passabilityMap.data[index2] & gameState.getPassabilityClassMask("default")) && gameState.ai.accessibility.getRegionSizei(index2) > 500)
if ((passabilityMap.data[index3] & gameState.getPassabilityClassMask("default")) && gameState.ai.accessibility.getRegionSizei(index3) > 500)
if ((passabilityMap.data[index4] & gameState.getPassabilityClassMask("default")) && gameState.ai.accessibility.getRegionSizei(index4) > 500) {
if (available < 2)
available++;
else
okay = true;
}
}
// checking for accessibility: if a neighbor is inaccessible, this is too. If it's not on the same "accessible map" as us, we crash-i~u.
var radius = 3;
for (var xx = -radius;xx <= radius; xx++)
for (var yy = -radius;yy <= radius; yy++)
{
var id = x + xx + (y+yy)*passabilityMap.width;
if (id > 0 && id < passabilityMap.data.length)
if (gameState.ai.terrainAnalyzer.map[id] === 0 || gameState.ai.terrainAnalyzer.map[id] == 30 || gameState.ai.terrainAnalyzer.map[id] == 40)
okay = false;
}
if (gameState.ai.myIndex !== gameState.ai.accessibility.passMap[i])
okay = false;
if (gameState.isPlayerEnemy(tilePlayer) && tilePlayer !== 0)
okay = false;
if ((passabilityMap.data[i] & (gameState.getPassabilityClassMask("building-shore") | gameState.getPassabilityClassMask("default"))))
okay = false;
obstructionTiles[i] = okay ? 255 : 0;
}
}
} else {
var playerID = PlayerID;
var obstructionTiles = new Uint8Array(passabilityMap.data.length);
for (var i = 0; i < passabilityMap.data.length; ++i)
{
var tilePlayer = (territoryMap.data[i] & TERRITORY_PLAYER_MASK);
var invalidTerritory = (
(!buildOwn && tilePlayer == playerID) ||
(!buildAlly && gameState.isPlayerAlly(tilePlayer) && tilePlayer != playerID) ||
(!buildNeutral && tilePlayer == 0) ||
(!buildEnemy && gameState.isPlayerEnemy(tilePlayer) && tilePlayer != 0)
);
var tileAccessible = (gameState.ai.myIndex === gameState.ai.accessibility.passMap[i]);
if (placementType === "shore")
tileAccessible = true;
obstructionTiles[i] = (!tileAccessible || invalidTerritory || (passabilityMap.data[i] & obstructionMask)) ? 0 : 255;
}
}
var map = new Map(gameState, obstructionTiles);
map.setMaxVal(255);
if (template && template.buildDistance()){
var minDist = template.buildDistance().MinDistance;
var category = template.buildDistance().FromCategory;
if (minDist !== undefined && category !== undefined){
gameState.getOwnEntities().forEach(function(ent) {
if (ent.buildCategory() === category && ent.position()){
var pos = ent.position();
var x = Math.round(pos[0] / gameState.cellSize);
var z = Math.round(pos[1] / gameState.cellSize);
map.addInfluence(x, z, minDist/gameState.cellSize, -255, 'constant');
}
});
}
}
return map;
};
Map.createTerritoryMap = function(gameState) {
var map = gameState.ai.territoryMap;
var ret = new Map(gameState, map.data);
ret.getOwner = function(p) {
return this.point(p) & TERRITORY_PLAYER_MASK;
}
ret.getOwnerIndex = function(p) {
return this.map[p] & TERRITORY_PLAYER_MASK;
}
return ret;
};
Map.prototype.addInfluence = function(cx, cy, maxDist, strength, type) {
strength = strength ? +strength : +maxDist;
type = type ? type : 'linear';
var x0 = Math.max(0, cx - maxDist);
var y0 = Math.max(0, cy - maxDist);
var x1 = Math.min(this.width, cx + maxDist);
var y1 = Math.min(this.height, cy + maxDist);
var maxDist2 = maxDist * maxDist;
var str = 0.0;
switch (type){
case 'linear':
str = +strength / +maxDist;
break;
case 'quadratic':
str = +strength / +maxDist2;
break;
case 'constant':
str = +strength;
break;
}
for ( var y = y0; y < y1; ++y) {
for ( var x = x0; x < x1; ++x) {
var dx = x - cx;
var dy = y - cy;
var r2 = dx*dx + dy*dy;
if (r2 < maxDist2){
var quant = 0;
switch (type){
case 'linear':
var r = Math.sqrt(r2);
quant = str * (maxDist - r);
break;
case 'quadratic':
quant = str * (maxDist2 - r2);
break;
case 'constant':
quant = str;
break;
}
if (this.map[x + y * this.width] + quant < 0)
this.map[x + y * this.width] = 0;
else if (this.map[x + y * this.width] + quant > this.maxVal)
this.map[x + y * this.width] = this.maxVal; // avoids overflow.
else
this.map[x + y * this.width] += quant;
}
}
}
};
Map.prototype.multiplyInfluence = function(cx, cy, maxDist, strength, type) {
strength = strength ? +strength : +maxDist;
type = type ? type : 'constant';
var x0 = Math.max(0, cx - maxDist);
var y0 = Math.max(0, cy - maxDist);
var x1 = Math.min(this.width, cx + maxDist);
var y1 = Math.min(this.height, cy + maxDist);
var maxDist2 = maxDist * maxDist;
var str = 0.0;
switch (type){
case 'linear':
str = strength / maxDist;
break;
case 'quadratic':
str = strength / maxDist2;
break;
case 'constant':
str = strength;
break;
}
for ( var y = y0; y < y1; ++y) {
for ( var x = x0; x < x1; ++x) {
var dx = x - cx;
var dy = y - cy;
var r2 = dx*dx + dy*dy;
if (r2 < maxDist2){
var quant = 0;
switch (type){
case 'linear':
var r = Math.sqrt(r2);
quant = str * (maxDist - r);
break;
case 'quadratic':
quant = str * (maxDist2 - r2);
break;
case 'constant':
quant = str;
break;
}
var machin = this.map[x + y * this.width] * quant;
if (machin < 0)
this.map[x + y * this.width] = 0;
else if (machin > this.maxVal)
this.map[x + y * this.width] = this.maxVal;
else
this.map[x + y * this.width] = machin;
}
}
}
};
// doesn't check for overflow.
Map.prototype.setInfluence = function(cx, cy, maxDist, value) {
value = value ? value : 0;
var x0 = Math.max(0, cx - maxDist);
var y0 = Math.max(0, cy - maxDist);
var x1 = Math.min(this.width, cx + maxDist);
var y1 = Math.min(this.height, cy + maxDist);
var maxDist2 = maxDist * maxDist;
for ( var y = y0; y < y1; ++y) {
for ( var x = x0; x < x1; ++x) {
var dx = x - cx;
var dy = y - cy;
var r2 = dx*dx + dy*dy;
if (r2 < maxDist2){
this.map[x + y * this.width] = value;
}
}
}
};
/**
* Make each cell's 16-bit/8-bit value at least one greater than each of its
* neighbours' values. (If the grid is initialised with 0s and 65535s or 255s, the
* result of each cell is its Manhattan distance to the nearest 0.)
*/
Map.prototype.expandInfluences = function() {
var w = this.width;
var h = this.height;
var grid = this.map;
for ( var y = 0; y < h; ++y) {
var min = this.maxVal;
for ( var x = 0; x < w; ++x) {
var g = grid[x + y * w];
if (g > min)
grid[x + y * w] = min;
else if (g < min)
min = g;
++min;
}
for ( var x = w - 2; x >= 0; --x) {
var g = grid[x + y * w];
if (g > min)
grid[x + y * w] = min;
else if (g < min)
min = g;
++min;
}
}
for ( var x = 0; x < w; ++x) {
var min = this.maxVal;
for ( var y = 0; y < h; ++y) {
var g = grid[x + y * w];
if (g > min)
grid[x + y * w] = min;
else if (g < min)
min = g;
++min;
}
for ( var y = h - 2; y >= 0; --y) {
var g = grid[x + y * w];
if (g > min)
grid[x + y * w] = min;
else if (g < min)
min = g;
++min;
}
}
};
Map.prototype.findBestTile = function(radius, obstructionTiles){
// Find the best non-obstructed tile
var bestIdx = 0;
var bestVal = -1;
for ( var i = 0; i < this.length; ++i) {
if (obstructionTiles.map[i] > radius) {
var v = this.map[i];
if (v > bestVal) {
bestVal = v;
bestIdx = i;
}
}
}
return [bestIdx, bestVal];
};
// add to current map by the parameter map pixelwise
Map.prototype.add = function(map){
for (var i = 0; i < this.length; ++i) {
if (this.map[i] + map.map[i] < 0)
this.map[i] = 0;
else if (this.map[i] + map.map[i] > this.maxVal)
this.map[i] = this.maxVal;
else
this.map[i] += map.map[i];
}
};
Map.prototype.dumpIm = function(name, threshold){
name = name ? name : "default.png";
threshold = threshold ? threshold : this.maxVal;
Engine.DumpImage(name, this.map, this.width, this.height, threshold);
};

View File

@ -1,489 +0,0 @@
/*
* Military Manager.
* Basically this deals with constructing defense and attack buildings, but it's not very developped yet.
* There's a lot of work still to do here.
* It also handles the attack plans (see attack_plan.js)
* Not completely cleaned up from the original version in qBot.
*/
var MilitaryAttackManager = function() {
this.fortressStartTime = 0;
this.fortressLapseTime = Config.Military.fortressLapseTime * 1000;
this.defenceBuildingTime = Config.Military.defenceBuildingTime * 1000;
this.attackPlansStartTime = Config.Military.attackPlansStartTime * 1000;
this.defenceManager = new Defence();
this.TotalAttackNumber = 0;
this.upcomingAttacks = { "CityAttack" : [] };
this.startedAttacks = { "CityAttack" : [] };
};
MilitaryAttackManager.prototype.init = function(gameState) {
var civ = gameState.playerData.civ;
// load units and buildings from the config files
if (civ in Config.buildings.moderate){
this.bModerate = Config.buildings.moderate[civ];
}else{
this.bModerate = Config.buildings.moderate['default'];
}
if (civ in Config.buildings.advanced){
this.bAdvanced = Config.buildings.advanced[civ];
}else{
this.bAdvanced = Config.buildings.advanced['default'];
}
if (civ in Config.buildings.fort){
this.bFort = Config.buildings.fort[civ];
}else{
this.bFort = Config.buildings.fort['default'];
}
for (var i in this.bAdvanced){
this.bAdvanced[i] = gameState.applyCiv(this.bAdvanced[i]);
}
for (var i in this.bFort){
this.bFort[i] = gameState.applyCiv(this.bFort[i]);
}
// TODO: figure out how to make this generic
for (var i in this.attackManagers){
this.availableAttacks[i] = new this.attackManagers[i](gameState, this);
}
var enemies = gameState.getEnemyEntities();
var filter = Filters.byClassesOr(["CitizenSoldier", "Champion", "Hero", "Siege"]);
this.enemySoldiers = enemies.filter(filter); // TODO: cope with diplomacy changes
this.enemySoldiers.registerUpdates();
// each enemy watchers keeps a list of entity collections about the enemy it watches
// It also keeps track of enemy armies, merging/splitting as needed
this.enemyWatchers = {};
this.ennWatcherIndex = [];
for (var i = 1; i <= 8; i++)
if (PlayerID != i && gameState.isPlayerEnemy(i)) {
this.enemyWatchers[i] = new enemyWatcher(gameState, i);
this.ennWatcherIndex.push(i);
this.defenceManager.enemyArmy[i] = [];
}
};
// picks the best template based on parameters and classes
MilitaryAttackManager.prototype.findBestTrainableUnit = function(gameState, classes, parameters) {
var units = gameState.findTrainableUnits(classes);
if (units.length === 0)
return undefined;
units.sort(function(a, b) { //}) {
var aDivParam = 0, bDivParam = 0;
var aTopParam = 0, bTopParam = 0;
for (var i in parameters) {
var param = parameters[i];
if (param[0] == "base") {
aTopParam = param[1];
bTopParam = param[1];
}
if (param[0] == "strength") {
aTopParam += getMaxStrength(a[1]) * param[1];
bTopParam += getMaxStrength(b[1]) * param[1];
}
if (param[0] == "siegeStrength") {
aTopParam += getMaxStrength(a[1], "Structure") * param[1];
bTopParam += getMaxStrength(b[1], "Structure") * param[1];
}
if (param[0] == "speed") {
aTopParam += a[1].walkSpeed() * param[1];
bTopParam += b[1].walkSpeed() * param[1];
}
if (param[0] == "cost") {
aDivParam += a[1].costSum() * param[1];
bDivParam += b[1].costSum() * param[1];
}
if (param[0] == "canGather") {
// checking against wood, could be anything else really.
if (a[1].resourceGatherRates() && a[1].resourceGatherRates()["wood.tree"])
aTopParam *= param[1];
if (b[1].resourceGatherRates() && b[1].resourceGatherRates()["wood.tree"])
bTopParam *= param[1];
}
}
return -(aTopParam/(aDivParam+1)) + (bTopParam/(bDivParam+1));
});
return units[0][0];
};
// Deals with building fortresses and towers.
// Currently build towers next to every useful dropsites.
// TODO: Fortresses are placed randomly atm.
MilitaryAttackManager.prototype.buildDefences = function(gameState, queues){
var workersNumber = gameState.getOwnEntitiesByRole("worker").filter(Filters.not(Filters.byHasMetadata(PlayerID,"plan"))).length;
if (gameState.countEntitiesAndQueuedByType(gameState.applyCiv('structures/{civ}_defense_tower'))
+ queues.defenceBuilding.totalLength() < gameState.getEntityLimits()["DefenseTower"] && queues.defenceBuilding.totalLength() < 4
&& gameState.currentPhase() > 1 && queues.defenceBuilding.totalLength() < 3) {
gameState.getOwnEntities().forEach(function(dropsiteEnt) {
if (dropsiteEnt.resourceDropsiteTypes() && dropsiteEnt.getMetadata(PlayerID, "defenseTower") !== true
&& (dropsiteEnt.getMetadata(PlayerID, "resource-quantity-wood") > 400 || dropsiteEnt.getMetadata(PlayerID, "resource-quantity-stone") > 500
|| dropsiteEnt.getMetadata(PlayerID, "resource-quantity-metal") > 500) ){
var position = dropsiteEnt.position();
if (position){
queues.defenceBuilding.addItem(new BuildingConstructionPlan(gameState, 'structures/{civ}_defense_tower', position));
}
dropsiteEnt.setMetadata(PlayerID, "defenseTower", true);
}
});
}
var numFortresses = 0;
for (var i in this.bFort){
numFortresses += gameState.countEntitiesAndQueuedByType(gameState.applyCiv(this.bFort[i]));
}
if (queues.defenceBuilding.totalLength() < 1 && (gameState.currentPhase() > 2 || gameState.isResearching("phase_city_generic")))
{
if (workersNumber >= 80 && gameState.getTimeElapsed() > numFortresses * this.fortressLapseTime + this.fortressStartTime)
{
if (!this.fortressStartTime)
this.fortressStartTime = gameState.getTimeElapsed();
queues.defenceBuilding.addItem(new BuildingConstructionPlan(gameState, this.bFort[0]));
debug ("Building a fortress");
}
}
if (gameState.countEntitiesByType(gameState.applyCiv(this.bFort[i])) >= 1) {
// let's add a siege building plan to the current attack plan if there is none currently.
if (this.upcomingAttacks["CityAttack"].length !== 0)
{
var attack = this.upcomingAttacks["CityAttack"][0];
if (!attack.unitStat["Siege"])
{
// no minsize as we don't want the plan to fail at the last minute though.
var stat = { "priority" : 1.1, "minSize" : 0, "targetSize" : 4, "batchSize" : 2, "classes" : ["Siege"],
"interests" : [ ["siegeStrength", 3], ["cost",1] ] ,"templates" : [] };
if (gameState.civ() == "cart" || gameState.civ() == "maur")
stat["classes"] = ["Elephant"];
attack.addBuildOrder(gameState, "Siege", stat, true);
}
}
}
};
// Deals with constructing military buildings (barracks, stables…)
// They are mostly defined by Config.js. This is unreliable since changes could be done easily.
// TODO: We need to determine these dynamically. Also doesn't build fortresses since the above function does that.
// TODO: building placement is bad. Choice of buildings is also fairly dumb.
MilitaryAttackManager.prototype.constructTrainingBuildings = function(gameState, queues) {
Engine.ProfileStart("Build buildings");
var workersNumber = gameState.getOwnEntitiesByRole("worker").filter(Filters.not(Filters.byHasMetadata(PlayerID, "plan"))).length;
if (workersNumber > 30 && (gameState.currentPhase() > 1 || gameState.isResearching("phase_town"))) {
if (gameState.countEntitiesAndQueuedByType(gameState.applyCiv(this.bModerate[0])) + queues.militaryBuilding.totalLength() < 1) {
debug ("Trying to build barracks");
queues.militaryBuilding.addItem(new BuildingConstructionPlan(gameState, this.bModerate[0]));
}
}
if (gameState.countEntitiesAndQueuedByType(gameState.applyCiv(this.bModerate[0])) < 2 && workersNumber > 85)
if (queues.militaryBuilding.totalLength() < 1)
queues.militaryBuilding.addItem(new BuildingConstructionPlan(gameState, this.bModerate[0]));
if (gameState.countEntitiesByType(gameState.applyCiv(this.bModerate[0])) === 2 && gameState.countEntitiesAndQueuedByType(gameState.applyCiv(this.bModerate[0])) < 3 && workersNumber > 125)
if (queues.militaryBuilding.totalLength() < 1)
{
queues.militaryBuilding.addItem(new BuildingConstructionPlan(gameState, this.bModerate[0]));
if (gameState.civ() == "gaul" || gameState.civ() == "brit" || gameState.civ() == "iber") {
queues.militaryBuilding.addItem(new BuildingConstructionPlan(gameState, this.bModerate[0]));
queues.militaryBuilding.addItem(new BuildingConstructionPlan(gameState, this.bModerate[0]));
}
}
//build advanced military buildings
if (workersNumber >= 75 && gameState.currentPhase() > 2){
if (queues.militaryBuilding.totalLength() === 0){
var inConst = 0;
for (var i in this.bAdvanced)
inConst += gameState.countFoundationsWithType(gameState.applyCiv(this.bAdvanced[i]));
if (inConst == 0 && this.bAdvanced && this.bAdvanced.length !== 0) {
var i = Math.floor(Math.random() * this.bAdvanced.length);
if (gameState.countEntitiesAndQueuedByType(gameState.applyCiv(this.bAdvanced[i])) < 1){
queues.militaryBuilding.addItem(new BuildingConstructionPlan(gameState, this.bAdvanced[i]));
}
}
}
}
if (gameState.civ() !== "gaul" && gameState.civ() !== "brit" && gameState.civ() !== "iber" &&
workersNumber > 130 && gameState.currentPhase() > 2)
{
var Const = 0;
for (var i in this.bAdvanced)
Const += gameState.countEntitiesByType(gameState.applyCiv(this.bAdvanced[i]));
if (inConst == 1) {
var i = Math.floor(Math.random() * this.bAdvanced.length);
if (gameState.countEntitiesAndQueuedByType(gameState.applyCiv(this.bAdvanced[i])) < 1){
queues.militaryBuilding.addItem(new BuildingConstructionPlan(gameState, this.bAdvanced[i]));
queues.militaryBuilding.addItem(new BuildingConstructionPlan(gameState, this.bAdvanced[i]));
}
}
}
Engine.ProfileStop();
};
// TODO: use pop(). Currently unused as this is too gameable.
MilitaryAttackManager.prototype.garrisonAllFemales = function(gameState) {
var buildings = gameState.getOwnEntities().filter(Filters.byCanGarrison()).toEntityArray();
var females = gameState.getOwnEntities().filter(Filters.byClass("Support"));
var cache = {};
females.forEach( function (ent) {
for (var i in buildings)
{
if (ent.position())
{
var struct = buildings[i];
if (!cache[struct.id()])
cache[struct.id()] = 0;
if (struct.garrisoned() && struct.garrisonMax() - struct.garrisoned().length - cache[struct.id()] > 0)
{
ent.garrison(struct);
cache[struct.id()]++;
break;
}
}
}
});
this.hasGarrisonedFemales = true;
};
MilitaryAttackManager.prototype.ungarrisonAll = function(gameState) {
this.hasGarrisonedFemales = false;
var buildings = gameState.getOwnEntities().filter(Filters.byCanGarrison()).toEntityArray();
buildings.forEach( function (struct) {
if (struct.garrisoned() && struct.garrisoned().length)
struct.unloadAll();
});
};
MilitaryAttackManager.prototype.pausePlan = function(gameState, planName) {
for (var attackType in this.upcomingAttacks) {
for (var i in this.upcomingAttacks[attackType]) {
var attack = this.upcomingAttacks[attackType][i];
if (attack.getName() == planName)
attack.setPaused(gameState, true);
}
}
for (var attackType in this.startedAttacks) {
for (var i in this.startedAttacks[attackType]) {
var attack = this.startedAttacks[attackType][i];
if (attack.getName() == planName)
attack.setPaused(gameState, true);
}
}
}
MilitaryAttackManager.prototype.unpausePlan = function(gameState, planName) {
for (var attackType in this.upcomingAttacks) {
for (var i in this.upcomingAttacks[attackType]) {
var attack = this.upcomingAttacks[attackType][i];
if (attack.getName() == planName)
attack.setPaused(gameState, false);
}
}
for (var attackType in this.startedAttacks) {
for (var i in this.startedAttacks[attackType]) {
var attack = this.startedAttacks[attackType][i];
if (attack.getName() == planName)
attack.setPaused(gameState, false);
}
}
}
MilitaryAttackManager.prototype.pauseAllPlans = function(gameState) {
for (var attackType in this.upcomingAttacks) {
for (var i in this.upcomingAttacks[attackType]) {
var attack = this.upcomingAttacks[attackType][i];
attack.setPaused(gameState, true);
}
}
for (var attackType in this.startedAttacks) {
for (var i in this.startedAttacks[attackType]) {
var attack = this.startedAttacks[attackType][i];
attack.setPaused(gameState, true);
}
}
}
MilitaryAttackManager.prototype.unpauseAllPlans = function(gameState) {
for (var attackType in this.upcomingAttacks) {
for (var i in this.upcomingAttacks[attackType]) {
var attack = this.upcomingAttacks[attackType][i];
attack.setPaused(gameState, false);
}
}
for (var attackType in this.startedAttacks) {
for (var i in this.startedAttacks[attackType]) {
var attack = this.startedAttacks[attackType][i];
attack.setPaused(gameState, false);
}
}
}
MilitaryAttackManager.prototype.update = function(gameState, queues, events) {
var self = this;
Engine.ProfileStart("military update");
this.gameState = gameState;
Engine.ProfileStart("Constructing military buildings and building defences");
this.constructTrainingBuildings(gameState, queues);
if(gameState.getTimeElapsed() > this.defenceBuildingTime)
this.buildDefences(gameState, queues);
Engine.ProfileStop();
this.defenceManager.update(gameState, events, this);
Engine.ProfileStart("Looping through attack plans");
// TODO: implement some form of check before starting a new attack plans. Sometimes it is not the priority.
if (1) {
for (var attackType in this.upcomingAttacks) {
for (var i = 0;i < this.upcomingAttacks[attackType].length; ++i) {
var attack = this.upcomingAttacks[attackType][i];
// okay so we'll get the support plan
if (!attack.isStarted()) {
var updateStep = attack.updatePreparation(gameState, this,events);
// now we're gonna check if the preparation time is over
if (updateStep === 1 || attack.isPaused() ) {
// just chillin'
} else if (updateStep === 0 || updateStep === 3) {
debug ("Military Manager: " +attack.getType() +" plan " +attack.getName() +" aborted.");
if (updateStep === 3) {
this.attackPlansEncounteredWater = true;
debug("No attack path found. Aborting.");
}
attack.Abort(gameState, this);
this.upcomingAttacks[attackType].splice(i--,1);
} else if (updateStep === 2) {
var chatText = "I am launching an attack against " + gameState.sharedScript.playersData[attack.targetPlayer].name + ".";
if (Math.random() < 0.2)
chatText = "Attacking " + gameState.sharedScript.playersData[attack.targetPlayer].name + ".";
else if (Math.random() < 0.3)
chatText = "I have sent an army against " + gameState.sharedScript.playersData[attack.targetPlayer].name + ".";
else if (Math.random() < 0.3)
chatText = "I'm starting an attack against " + gameState.sharedScript.playersData[attack.targetPlayer].name + ".";
gameState.ai.chatTeam(chatText);
debug ("Military Manager: Starting " +attack.getType() +" plan " +attack.getName());
attack.StartAttack(gameState,this);
this.startedAttacks[attackType].push(attack);
this.upcomingAttacks[attackType].splice(i--,1);
}
} else {
var chatText = "I am launching an attack against " + gameState.sharedScript.playersData[attack.targetPlayer].name + ".";
if (Math.random() < 0.2)
chatText = "Attacking " + gameState.sharedScript.playersData[attack.targetPlayer].name + ".";
else if (Math.random() < 0.3)
chatText = "I have sent an army against " + gameState.sharedScript.playersData[attack.targetPlayer].name + ".";
else if (Math.random() < 0.3)
chatText = "I'm starting an attack against " + gameState.sharedScript.playersData[attack.targetPlayer].name + ".";
gameState.ai.chatTeam(chatText);
debug ("Military Manager: Starting " +attack.getType() +" plan " +attack.getName());
this.startedAttacks[attackType].push(attack);
this.upcomingAttacks[attackType].splice(i--,1);
}
}
}
}
for (var attackType in this.startedAttacks) {
for (var i = 0; i < this.startedAttacks[attackType].length; ++i) {
var attack = this.startedAttacks[attackType][i];
// okay so then we'll update the attack.
if (!attack.isPaused())
{
var remaining = attack.update(gameState,this,events);
if (remaining == 0 || remaining == undefined) {
debug ("Military Manager: " +attack.getType() +" plan " +attack.getName() +" is now finished.");
attack.Abort(gameState);
this.startedAttacks[attackType].splice(i--,1);
}
}
}
}
// Note: these indications of "rush" are currently unused.
if (gameState.ai.strategy === "rush" && this.startedAttacks["CityAttack"].length !== 0) {
// and then we revert.
gameState.ai.strategy = "normal";
Config.Economy.femaleRatio = 0.4;
gameState.ai.modules.economy.targetNumWorkers = Math.max(Math.floor(gameState.getPopulationMax()*0.55), 1);
} else if (gameState.ai.strategy === "rush" && this.upcomingAttacks["CityAttack"].length === 0)
{
Lalala = new CityAttack(gameState, this,this.TotalAttackNumber, -1, "rush")
this.TotalAttackNumber++;
this.upcomingAttacks["CityAttack"].push(Lalala);
debug ("Starting a little something");
} else if (gameState.ai.strategy !== "rush")
{
// creating plans after updating because an aborted plan might be reused in that case.
if (gameState.countEntitiesByType(gameState.applyCiv(this.bModerate[0])) >= 1 && !this.attackPlansEncounteredWater
&& gameState.getTimeElapsed() > this.attackPlansStartTime) {
if (gameState.countEntitiesByType(gameState.applyCiv("structures/{civ}_dock")) === 0 && gameState.ai.waterMap)
{
// wait till we get a dock.
} else {
// basically only the first plan, really.
if (this.upcomingAttacks["CityAttack"].length == 0 && (gameState.getTimeElapsed() < 12*60000 || Config.difficulty < 1)) {
var Lalala = new CityAttack(gameState, this,this.TotalAttackNumber, -1);
if (Lalala.failed)
{
this.attackPlansEncounteredWater = true; // hack
} else {
debug ("Military Manager: Creating the plan " +this.TotalAttackNumber);
this.TotalAttackNumber++;
this.upcomingAttacks["CityAttack"].push(Lalala);
}
} else if (this.upcomingAttacks["CityAttack"].length == 0 && Config.difficulty !== 0) {
var Lalala = new CityAttack(gameState, this,this.TotalAttackNumber, -1, "superSized");
if (Lalala.failed)
{
this.attackPlansEncounteredWater = true; // hack
} else {
debug ("Military Manager: Creating the super sized plan " +this.TotalAttackNumber);
this.TotalAttackNumber++;
this.upcomingAttacks["CityAttack"].push(Lalala);
}
}
}
}
}
/*
// very old relic. This should be reimplemented someday so the code stays here.
if (this.HarassRaiding && this.preparingRaidNumber + this.startedRaidNumber < 1 && gameState.getTimeElapsed() < 780000) {
var Lalala = new CityAttack(gameState, this,this.totalStartedAttackNumber, -1, "harass_raid");
if (!Lalala.createSupportPlans(gameState, this, )) {
debug ("Military Manager: harrassing plan not a valid option");
this.HarassRaiding = false;
} else {
debug ("Military Manager: Creating the harass raid plan " +this.totalStartedAttackNumber);
this.totalStartedAttackNumber++;
this.preparingRaidNumber++;
this.currentAttacks.push(Lalala);
}
}
*/
Engine.ProfileStop();
Engine.ProfileStop();
};

View File

@ -1,198 +0,0 @@
var BuildingConstructionPlan = function(gameState, type, position) {
this.type = gameState.applyCiv(type);
this.position = position;
this.template = gameState.getTemplate(this.type);
if (!this.template) {
this.invalidTemplate = true;
this.template = undefined;
debug("Cannot build " + this.type);
return;
}
this.category = "building";
this.cost = new Resources(this.template.cost());
this.number = 1; // The number of buildings to build
};
BuildingConstructionPlan.prototype.canExecute = function(gameState) {
if (this.invalidTemplate){
return false;
}
// TODO: verify numeric limits etc
if (this.template.requiredTech() && !gameState.isResearched(this.template.requiredTech()))
return false;
var builders = gameState.findBuilders(this.type);
return (builders.length != 0);
};
BuildingConstructionPlan.prototype.execute = function(gameState) {
var builders = gameState.findBuilders(this.type).toEntityArray();
// We don't care which builder we assign, since they won't actually
// do the building themselves - all we care about is that there is
// some unit that can start the foundation
var pos = this.findGoodPosition(gameState);
if (!pos){
if (this.template.hasClass("Naval"))
gameState.ai.modules.economy.dockFailed = true;
debug("No room to place " + this.type);
return;
}
if (gameState.getTemplate(this.type).buildCategory() === "Dock")
{
for (var angle = 0; angle < Math.PI * 2; angle += Math.PI/4)
{
builders[0].construct(this.type, pos.x, pos.z, angle);
}
} else
builders[0].construct(this.type, pos.x, pos.z, pos.angle);
};
BuildingConstructionPlan.prototype.getCost = function() {
return this.cost;
};
BuildingConstructionPlan.prototype.findGoodPosition = function(gameState) {
var template = gameState.getTemplate(this.type);
var cellSize = gameState.cellSize; // size of each tile
// First, find all tiles that are far enough away from obstructions:
var obstructionMap = Map.createObstructionMap(gameState,template);
//obstructionMap.dumpIm(template.buildCategory() + "_obstructions.png");
if (template.buildCategory() !== "Dock")
obstructionMap.expandInfluences();
// Compute each tile's closeness to friendly structures:
var friendlyTiles = new Map(gameState);
var alreadyHasHouses = false;
// If a position was specified then place the building as close to it as possible
if (this.position){
var x = Math.round(this.position[0] / cellSize);
var z = Math.round(this.position[1] / cellSize);
friendlyTiles.addInfluence(x, z, 200);
} else {
// No position was specified so try and find a sensible place to build
gameState.getOwnEntities().forEach(function(ent) {
if (ent.hasClass("Structure")) {
var infl = 32;
if (ent.hasClass("CivCentre"))
infl *= 4;
var pos = ent.position();
var x = Math.round(pos[0] / cellSize);
var z = Math.round(pos[1] / cellSize);
if (ent.buildCategory() == "Wall") { // no real blockers, but can't build where they are
friendlyTiles.addInfluence(x, z, 2,-1000);
return;
}
if (template._template.BuildRestrictions.Category === "Field"){
if (ent.resourceDropsiteTypes() && ent.resourceDropsiteTypes().indexOf("food") !== -1){
if (ent.hasClass("CivCentre"))
friendlyTiles.addInfluence(x, z, infl/4, infl);
else
friendlyTiles.addInfluence(x, z, infl, infl);
}
}else{
if (template.genericName() == "House" && ent.genericName() == "House") {
friendlyTiles.addInfluence(x, z, 15.0,20,'linear'); // houses are close to other houses
alreadyHasHouses = true;
} else if (template.hasClass("GarrisonFortress") && ent.genericName() == "House")
{
friendlyTiles.addInfluence(x, z, 30, -50);
} else if (template.genericName() == "House") {
friendlyTiles.addInfluence(x, z, Math.ceil(infl/2.0),infl); // houses are farther away from other buildings but houses
friendlyTiles.addInfluence(x, z, Math.ceil(infl/4.0),-infl/2.0); // houses are farther away from other buildings but houses
} else if (template.hasClass("GarrisonFortress"))
{
friendlyTiles.addInfluence(x, z, 20, 10);
friendlyTiles.addInfluence(x, z, 10, -40, 'linear');
} else if (ent.genericName() != "House") // houses have no influence on other buildings
{
friendlyTiles.addInfluence(x, z, infl);
//avoid building too close to each other if possible.
friendlyTiles.addInfluence(x, z, 5, -5, 'linear');
}
// If this is not a field add a negative influence near the CivCentre because we want to leave this
// area for fields.
if (ent.hasClass("CivCentre") && template.genericName() != "House"){
friendlyTiles.addInfluence(x, z, Math.floor(infl/8), Math.floor(-infl/2));
} else if (ent.hasClass("CivCentre")) {
friendlyTiles.addInfluence(x, z, infl/3.0, infl + 1);
friendlyTiles.addInfluence(x, z, Math.ceil(infl/5.0), -(infl/2.0), 'linear');
}
}
}
});
}
//friendlyTiles.dumpIm(template.buildCategory() + "_" +gameState.getTimeElapsed() + ".png", 200);
// Find target building's approximate obstruction radius, and expand by a bit to make sure we're not too close, this
// allows room for units to walk between buildings.
// note: not for houses and dropsites who ought to be closer to either each other or a resource.
// also not for fields who can be stacked quite a bit
var radius = 0;
if (template.genericName() == "Field")
radius = Math.ceil(template.obstructionRadius() / cellSize) - 0.4;
else if (template.hasClass("GarrisonFortress"))
radius = Math.ceil(template.obstructionRadius() / cellSize) + 2;
else if (template.buildCategory() === "Dock")
radius = 1;//Math.floor(template.obstructionRadius() / cellSize);
else if (!template.hasClass("DropsiteWood") && !template.hasClass("DropsiteStone") && !template.hasClass("DropsiteMetal"))
radius = Math.ceil(template.obstructionRadius() / cellSize + 1);
else
radius = Math.ceil(template.obstructionRadius() / cellSize);
// further contract cause walls
// Note: I'm currently destroying them so that doesn't matter.
//if (gameState.playerData.civ == "iber")
// radius *= 0.95;
// Find the best non-obstructed
if (template.genericName() == "House" && !alreadyHasHouses) {
// try to get some space first
var bestTile = friendlyTiles.findBestTile(10, obstructionMap);
var bestIdx = bestTile[0];
var bestVal = bestTile[1];
}
if (bestVal === undefined || bestVal === -1) {
var bestTile = friendlyTiles.findBestTile(radius, obstructionMap);
var bestIdx = bestTile[0];
var bestVal = bestTile[1];
}
if (bestVal === -1) {
return false;
}
//friendlyTiles.setInfluence((bestIdx % friendlyTiles.width), Math.floor(bestIdx / friendlyTiles.width), 1, 200);
//friendlyTiles.dumpIm(template.buildCategory() + "_" +gameState.getTimeElapsed() + ".png", 200);
var x = ((bestIdx % friendlyTiles.width) + 0.5) * cellSize;
var z = (Math.floor(bestIdx / friendlyTiles.width) + 0.5) * cellSize;
// default angle
var angle = 3*Math.PI/4;
return {
"x" : x,
"z" : z,
"angle" : angle
};
};

View File

@ -1,54 +0,0 @@
var ResearchPlan = function(gameState, type, rush) {
this.type = type;
this.template = gameState.getTemplate(this.type);
if (!this.template || this.template.researchTime === undefined) {
this.invalidTemplate = true;
this.template = undefined;
debug ("Invalid research");
return false;
}
this.category = "technology";
this.cost = new Resources(this.template.cost(),0);
this.number = 1; // Obligatory for compatibility
if (rush)
this.rush = true;
else
this.rush = false;
return true;
};
ResearchPlan.prototype.canExecute = function(gameState) {
if (this.invalidTemplate)
return false;
// also checks canResearch
return (gameState.findResearchers(this.type).length !== 0);
};
ResearchPlan.prototype.execute = function(gameState) {
var self = this;
//debug ("Starting the research plan for " + this.type);
var trainers = gameState.findResearchers(this.type).toEntityArray();
//for (var i in trainers)
// warn (this.type + " - " +trainers[i].genericName());
// Prefer training buildings with short queues
// (TODO: this should also account for units added to the queue by
// plans that have already been executed this turn)
if (trainers.length > 0){
trainers.sort(function(a, b) {
return (a.trainingQueueTime() - b.trainingQueueTime());
});
// drop anything in the queue if we rush it.
if (this.rush)
trainers[0].stopAllProduction(0.45);
trainers[0].research(this.type);
}
};
ResearchPlan.prototype.getCost = function(){
return this.cost;
};

View File

@ -1,69 +0,0 @@
var UnitTrainingPlan = function(gameState, type, metadata, number, maxMerge) {
this.type = gameState.applyCiv(type);
this.metadata = metadata;
this.template = gameState.getTemplate(this.type);
if (!this.template) {
this.invalidTemplate = true;
this.template = undefined;
return;
}
this.category= "unit";
this.cost = new Resources(this.template.cost(), this.template._template.Cost.Population);
if (!number){
this.number = 1;
}else{
this.number = number;
}
if (!maxMerge)
this.maxMerge = 5;
else
this.maxMerge = maxMerge;
};
UnitTrainingPlan.prototype.canExecute = function(gameState) {
if (this.invalidTemplate)
return false;
// TODO: we should probably check pop caps
var trainers = gameState.findTrainers(this.type);
return (trainers.length != 0);
};
UnitTrainingPlan.prototype.execute = function(gameState) {
//warn("Executing UnitTrainingPlan " + uneval(this));
var self = this;
var trainers = gameState.findTrainers(this.type).toEntityArray();
// Prefer training buildings with short queues
// (TODO: this should also account for units added to the queue by
// plans that have already been executed this turn)
if (trainers.length > 0){
trainers.sort(function(a, b) {
var aa = a.trainingQueueTime();
var bb = b.trainingQueueTime();
if (a.hasClass("Civic") && !self.template.hasClass("Support"))
aa += 0.9;
if (b.hasClass("Civic") && !self.template.hasClass("Support"))
bb += 0.9;
return (aa - bb);
});
trainers[0].train(this.type, this.number, this.metadata);
}
};
UnitTrainingPlan.prototype.getCost = function(){
var multCost = new Resources();
multCost.add(this.cost);
multCost.multiply(this.number);
return multCost;
};
UnitTrainingPlan.prototype.addItem = function(amount){
if (amount === undefined)
amount = 1;
this.number += amount;
};

View File

@ -1,367 +0,0 @@
function QBotAI(settings) {
BaseAI.call(this, settings);
Config.updateDifficulty(settings.difficulty);
this.turn = 0;
this.playedTurn = 0;
this.modules = {
"economy": new EconomyManager(),
"military": new MilitaryAttackManager()
};
// this.queues can only be modified by the queue manager or things will go awry.
this.queues = {
house : new Queue(),
citizenSoldier : new Queue(),
villager : new Queue(),
economicBuilding : new Queue(),
dropsites : new Queue(),
field : new Queue(),
militaryBuilding : new Queue(),
defenceBuilding : new Queue(),
civilCentre: new Queue(),
majorTech: new Queue(),
minorTech: new Queue()
};
this.productionQueues = [];
this.priorities = Config.priorities;
this.queueManager = new QueueManager(this.queues, this.priorities);
this.firstTime = true;
this.savedEvents = [];
this.waterMap = false;
this.defcon = 5;
this.defconChangeTime = -10000000;
}
QBotAI.prototype = new BaseAI();
// Bit of a hack: I run the pathfinder early, before the map apears, to avoid a sometimes substantial lag right at the start.
QBotAI.prototype.InitShared = function(gameState, sharedScript) {
var ents = gameState.getEntities().filter(Filters.byOwner(PlayerID));
var myKeyEntities = ents.filter(function(ent) {
return ent.hasClass("CivCentre");
});
if (myKeyEntities.length == 0){
myKeyEntities = gameState.getEntities().filter(Filters.byOwner(PlayerID));
}
var filter = Filters.byClass("CivCentre");
var enemyKeyEntities = gameState.getEntities().filter(Filters.not(Filters.byOwner(PlayerID))).filter(filter);
if (enemyKeyEntities.length == 0){
enemyKeyEntities = gameState.getEntities().filter(Filters.not(Filters.byOwner(PlayerID)));
}
this.pathFinder = new aStarPath(gameState, false, true);
this.pathsToMe = [];
this.pathInfo = { "angle" : 0, "needboat" : true, "mkeyPos" : myKeyEntities.toEntityArray()[0].position(), "ekeyPos" : enemyKeyEntities.toEntityArray()[0].position() };
// First path has a sampling of 3, which ensures we'll get at least one path even on Acropolis. The others are 6 so might fail.
var pos = [this.pathInfo.mkeyPos[0] + 150*Math.cos(this.pathInfo.angle),this.pathInfo.mkeyPos[1] + 150*Math.sin(this.pathInfo.angle)];
var path = this.pathFinder.getPath(this.pathInfo.ekeyPos, pos, 2, 2);// uncomment for debug:*/, 300000, gameState);
//Engine.DumpImage("initialPath" + PlayerID + ".png", this.pathFinder.TotorMap.map, this.pathFinder.TotorMap.width,this.pathFinder.TotorMap.height,255);
if (path !== undefined && path[1] !== undefined && path[1] == false) {
// path is viable and doesn't require boating.
// blackzone the last two waypoints.
this.pathFinder.markImpassableArea(path[0][0][0],path[0][0][1],20);
this.pathsToMe.push(path[0][0][0]);
this.pathInfo.needboat = false;
}
this.pathInfo.angle += Math.PI/3.0;
}
//Some modules need the gameState to fully initialise
QBotAI.prototype.runInit = function(gameState, events){
this.chooseRandomStrategy();
for (var i in this.modules){
if (this.modules[i].init){
this.modules[i].init(gameState, events);
}
}
debug ("Inited, diff is " + Config.difficulty);
this.timer = new Timer();
var ents = gameState.getOwnEntities();
var myKeyEntities = gameState.getOwnEntities().filter(function(ent) {
return ent.hasClass("CivCentre");
});
if (myKeyEntities.length == 0){
myKeyEntities = gameState.getOwnEntities();
}
// disband the walls themselves
if (gameState.playerData.civ == "iber") {
gameState.getOwnEntities().filter(function(ent) { //}){
if (ent.hasClass("StoneWall") && !ent.hasClass("Tower"))
ent.destroy();
});
}
var filter = Filters.byClass("CivCentre");
var enemyKeyEntities = gameState.getEnemyEntities().filter(filter);
if (enemyKeyEntities.length == 0){
enemyKeyEntities = gameState.getEnemyEntities();
}
//this.accessibility = new Accessibility(gameState, myKeyEntities.toEntityArray()[0].position());
this.myIndex = this.accessibility.getAccessValue(myKeyEntities.toEntityArray()[0].position());
if (enemyKeyEntities.length == 0)
return;
this.templateManager = new TemplateManager(gameState);
};
QBotAI.prototype.OnUpdate = function(sharedScript) {
if (this.gameFinished){
return;
}
if (this.events.length > 0){
this.savedEvents = this.savedEvents.concat(this.events);
}
// Run the update every n turns, offset depending on player ID to balance the load
// this also means that init at turn 0 always happen and is never run in parallel to the first played turn so I use an else if.
if (this.turn == 0) {
//Engine.DumpImage("terrain.png", this.accessibility.map, this.accessibility.width,this.accessibility.height,255)
//Engine.DumpImage("Access.png", this.accessibility.passMap, this.accessibility.width,this.accessibility.height,this.accessibility.regionID+1)
var gameState = sharedScript.gameState[PlayerID];
gameState.ai = this;
this.runInit(gameState, this.savedEvents);
// Delete creation events
delete this.savedEvents;
this.savedEvents = [];
} else if ((this.turn + this.player) % 8 == 5) {
Engine.ProfileStart("Aegis bot");
this.playedTurn++;
var gameState = sharedScript.gameState[PlayerID];
gameState.ai = this;
if (gameState.getOwnEntities().length === 0){
Engine.ProfileStop();
return; // With no entities to control the AI cannot do anything
}
if (this.pathInfo !== undefined)
{
var pos = [this.pathInfo.mkeyPos[0] + 150*Math.cos(this.pathInfo.angle),this.pathInfo.mkeyPos[1] + 150*Math.sin(this.pathInfo.angle)];
var path = this.pathFinder.getPath(this.pathInfo.ekeyPos, pos, 6, 5);// uncomment for debug:*/, 300000, gameState);
if (path !== undefined && path[1] !== undefined && path[1] == false) {
// path is viable and doesn't require boating.
// blackzone the last two waypoints.
this.pathFinder.markImpassableArea(path[0][0][0],path[0][0][1],20);
this.pathsToMe.push(path[0][0][0]);
this.pathInfo.needboat = false;
}
this.pathInfo.angle += Math.PI/3.0;
if (this.pathInfo.angle > Math.PI*2.0)
{
if (this.pathInfo.needboat)
{
debug ("Assuming this is a water map");
this.waterMap = true;
}
delete this.pathFinder;
delete this.pathInfo;
}
}
// try going up phases.
if (gameState.canResearch("phase_town",true) && gameState.getTimeElapsed() > (Config.Economy.townPhase*1000)
&& gameState.findResearchers("phase_town",true).length != 0 && this.queues.majorTech.totalLength() === 0) {
this.queues.majorTech.addItem(new ResearchPlan(gameState, "phase_town",true)); // we rush the town phase.
debug ("Trying to reach town phase");
var nb = gameState.getOwnEntities().filter(Filters.byClass("Village")).length-1;
if (nb < 5)
{
while (nb < 5 && ++nb)
this.queues.house.addItem(new BuildingConstructionPlan(gameState, "structures/{civ}_house"));
}
} else if (gameState.canResearch("phase_city_generic",true) && gameState.getTimeElapsed() > (Config.Economy.cityPhase*1000)
&& gameState.getOwnEntitiesByRole("worker").length > 85
&& gameState.findResearchers("phase_city_generic", true).length != 0 && this.queues.majorTech.totalLength() === 0) {
debug ("Trying to reach city phase");
this.queues.majorTech.addItem(new ResearchPlan(gameState, "phase_city_generic"));
}
// defcon cooldown
if (this.defcon < 5 && gameState.timeSinceDefconChange() > 20000)
{
this.defcon++;
debug ("updefconing to " +this.defcon);
if (this.defcon >= 4 && this.modules.military.hasGarrisonedFemales)
this.modules.military.ungarrisonAll(gameState);
}
for (var i in this.modules){
this.modules[i].update(gameState, this.queues, this.savedEvents);
}
this.queueManager.update(gameState);
/*
// Use this to debug informations about the metadata.
if (this.playedTurn % 10 === 0)
{
// some debug informations about units.
var units = gameState.getOwnEntities();
for (var i in units._entities)
{
var ent = units._entities[i];
if (!ent.isIdle())
continue;
warn ("Unit " + ent.id() + " is a " + ent._templateName);
if (sharedScript._entityMetadata[PlayerID][ent.id()])
{
var metadata = sharedScript._entityMetadata[PlayerID][ent.id()];
for (var j in metadata)
{
warn ("Metadata " + j);
if (typeof(metadata[j]) == "object")
warn ("Object");
else if (typeof(metadata[j]) == undefined)
warn ("Undefined");
else
warn(uneval(metadata[j]));
}
}
}
}*/
//if (this.playedTurn % 5 === 0)
// this.queueManager.printQueues(gameState);
// Generate some entropy in the random numbers (against humans) until the engine gets random initialised numbers
// TODO: remove this when the engine gives a random seed
var n = this.savedEvents.length % 29;
for (var i = 0; i < n; i++){
Math.random();
}
delete this.savedEvents;
this.savedEvents = [];
Engine.ProfileStop();
}
this.turn++;
};
QBotAI.prototype.chooseRandomStrategy = function()
{
// deactivated for now.
this.strategy = "normal";
// rarely and if we can assume it's not a water map.
if (!this.pathInfo.needboat && 0)//Math.random() < 0.2 && Config.difficulty == 2)
{
this.strategy = "rush";
// going to rush.
this.modules.economy.targetNumWorkers = 0;
Config.Economy.townPhase = 480;
Config.Economy.cityPhase = 900;
Config.Economy.farmsteadStartTime = 600;
Config.Economy.femaleRatio = 0; // raise it since we'll want to rush age 2.
}
};
// TODO: Remove override when the whole AI state is serialised
// TODO: this currently is very much equivalent to "rungamestateinit" with a few hacks. Should deserialize/serialize properly someday.
QBotAI.prototype.Deserialize = function(data, sharedScript)
{
BaseAI.prototype.Deserialize.call(this, data);
var ents = sharedScript.entities.filter(Filters.byOwner(PlayerID));
var myKeyEntities = ents.filter(function(ent) {
return ent.hasClass("CivCentre");
});
if (myKeyEntities.length == 0){
myKeyEntities = sharedScript.entities.filter(Filters.byOwner(PlayerID));
}
var filter = Filters.byClass("CivCentre");
var enemyKeyEntities = sharedScript.entities.filter(Filters.not(Filters.byOwner(PlayerID))).filter(filter);
if (enemyKeyEntities.length == 0){
enemyKeyEntities = sharedScript.entities.filter(Filters.not(Filters.byOwner(PlayerID)));
}
this.terrainAnalyzer = sharedScript.terrainAnalyzer;
this.passabilityMap = sharedScript.passabilityMap;
var fakeState = { "ai" : this, "sharedScript" : sharedScript };
this.pathFinder = new aStarPath(fakeState, false, true);
this.pathsToMe = [];
this.pathInfo = { "angle" : 0, "needboat" : true, "mkeyPos" : myKeyEntities.toEntityArray()[0].position(), "ekeyPos" : enemyKeyEntities.toEntityArray()[0].position() };
// First path has a sampling of 3, which ensures we'll get at least one path even on Acropolis. The others are 6 so might fail.
var pos = [this.pathInfo.mkeyPos[0] + 150*Math.cos(this.pathInfo.angle),this.pathInfo.mkeyPos[1] + 150*Math.sin(this.pathInfo.angle)];
var path = this.pathFinder.getPath(this.pathInfo.ekeyPos, pos, 2, 2);
if (path !== undefined && path[1] !== undefined && path[1] == false) {
// path is viable and doesn't require boating.
// blackzone the last two waypoints.
this.pathFinder.markImpassableArea(path[0][0][0],path[0][0][1],20);
this.pathsToMe.push(path[0][0][0]);
this.pathInfo.needboat = false;
}
this.pathInfo.angle += Math.PI/3.0;
};
// Override the default serializer
QBotAI.prototype.Serialize = function()
{
//var ret = BaseAI.prototype.Serialize.call(this);
return {};
};
function debug(output){
if (Config.debug){
if (typeof output === "string"){
warn(output);
}else{
warn(uneval(output));
}
}
}
function copyPrototype(descendant, parent) {
var sConstructor = parent.toString();
var aMatch = sConstructor.match( /\s*function (.*)\(/ );
if ( aMatch != null ) { descendant.prototype[aMatch[1]] = parent; }
for (var m in parent.prototype) {
descendant.prototype[m] = parent.prototype[m];
}
}

View File

@ -1,296 +0,0 @@
// This takes the input queues and picks which items to fund with resources until no more resources are left to distribute.
//
// Currently this manager keeps accounts for each queue, split between the 4 main resources
//
// Each time resources are available (ie not in any account), it is split between the different queues
// Mostly based on priority of the queue, and existing needs.
// Each turn, the queue Manager checks if a queue can afford its next item, then it does.
//
// A consequence of the system it's not really revertible. Once a queue has an account of 500 food, it'll keep it
// If for some reason the AI stops getting new food, and this queue lacks, say, wood, no other queues will
// be able to benefit form the 500 food (even if they only needed food).
// This is not to annoying as long as all goes well. If the AI loses many workers, it starts being problematic.
//
// It also has the effect of making the AI more or less always sit on a few hundreds resources since most queues
// get some part of the total, and if all queues have 70% of their needs, nothing gets done
// Particularly noticeable when phasing: the AI often overshoots by a good 200/300 resources before starting.
//
// The fact that there is an outqueue is mostly a relic of qBot.
//
// This system should be improved. It's probably not flexible enough.
var QueueManager = function(queues, priorities) {
this.queues = queues;
this.priorities = priorities;
this.account = {};
this.accounts = {};
// the sorting would need to be updated on priority change but there is currently none.
var self = this;
this.queueArrays = [];
for (var p in this.queues) {
this.account[p] = 0;
this.accounts[p] = new Resources();
this.queueArrays.push([p,this.queues[p]]);
}
this.queueArrays.sort(function (a,b) { return (self.priorities[b[0]] - self.priorities[a[0]]) });
this.curItemQueue = [];
};
QueueManager.prototype.getAvailableResources = function(gameState, noAccounts) {
var resources = gameState.getResources();
if (noAccounts)
return resources;
for (var key in this.queues) {
resources.subtract(this.accounts[key]);
}
return resources;
};
QueueManager.prototype.futureNeeds = function(gameState, EcoManager) {
var needs = new Resources();
// get ouy current resources, not removing accounts.
var current = this.getAvailableResources(gameState, true);
//queueArrays because it's faster.
for (var i in this.queueArrays)
{
var name = this.queueArrays[i][0];
var queue = this.queueArrays[i][1];
for (var j = 0; j < Math.min(2,queue.length()); ++j)
{
needs.add(queue.queue[j].getCost());
}
}
if (EcoManager === false) {
return {
"food" : Math.max(needs.food - current.food, 0),
"wood" : Math.max(needs.wood - current.wood, 0),
"stone" : Math.max(needs.stone - current.stone, 0),
"metal" : Math.max(needs.metal - current.metal, 0)
};
} else {
// Return predicted values minus the current stockpiles along with a base rater for all resources
return {
"food" : (Math.max(needs.food - current.food, 0) + EcoManager.baseNeed["food"])/2,
"wood" : (Math.max(needs.wood - current.wood, 0) + EcoManager.baseNeed["wood"])/2,
"stone" : (Math.max(needs.stone - current.stone, 0) + EcoManager.baseNeed["stone"])/2,
"metal" : (Math.max(needs.metal - current.metal, 0) + EcoManager.baseNeed["metal"])/2
};
}
};
QueueManager.prototype.printQueues = function(gameState){
debug("OUTQUEUES");
for (var i in this.queues){
var qStr = "";
var q = this.queues[i];
if (q.outQueue.length > 0)
debug((i + ":"));
for (var j in q.outQueue){
qStr = " " + q.outQueue[j].type + " ";
if (q.outQueue[j].number)
qStr += "x" + q.outQueue[j].number;
debug (qStr);
}
}
debug("INQUEUES");
for (var i in this.queues){
var qStr = "";
var q = this.queues[i];
if (q.queue.length > 0)
debug((i + ":"));
for (var j in q.queue){
qStr = " " + q.queue[j].type + " ";
if (q.queue[j].number)
qStr += "x" + q.queue[j].number;
debug (qStr);
}
}
debug ("Accounts");
for (var p in this.accounts)
{
debug(p + ": " + uneval(this.accounts[p]));
}
debug("Needed Resources:" + uneval(this.futureNeeds(gameState,false)));
debug ("Current Resources:" + uneval(gameState.getResources()));
debug ("Available Resources:" + uneval(this.getAvailableResources(gameState)));
};
QueueManager.prototype.clear = function(){
this.curItemQueue = [];
for (var i in this.queues)
this.queues[i].empty();
};
QueueManager.prototype.update = function(gameState) {
var self = this;
for (var i in this.priorities){
if (!(this.priorities[i] > 0)){
this.priorities[i] = 1; // TODO: make the Queue Manager not die when priorities are zero.
warn("QueueManager received bad priorities, please report this error: " + uneval(this.priorities));
}
}
Engine.ProfileStart("Queue Manager");
//if (gameState.ai.playedTurn % 10 === 0)
// this.printQueues(gameState);
Engine.ProfileStart("Pick items from queues");
// TODO: this only pushes the first object. SHould probably try to push any possible object to maximize productivity. Perhaps a settinh?
// looking at queues in decreasing priorities and pushing to the current item queues.
for (var i in this.queueArrays)
{
var name = this.queueArrays[i][0];
var queue = this.queueArrays[i][1];
if (queue.length() > 0)
{
var item = queue.getNext();
var total = new Resources();
total.add(this.accounts[name]);
total.subtract(queue.outQueueCost());
if (total.canAfford(item.getCost()))
{
queue.nextToOutQueue();
}
} else if (queue.totalLength() === 0) {
this.accounts[name].reset();
}
}
var availableRes = this.getAvailableResources(gameState);
// assign some accounts to queues. This is done by priority, and by need.
for (var ress in availableRes)
{
if (availableRes[ress] > 0 && ress != "population")
{
var totalPriority = 0;
var tempPrio = {};
var maxNeed = {};
// Okay so this is where it gets complicated.
// If a queue requires "ress" for the next elements (in the queue or the outqueue)
// And the account is not high enough for it.
// Then we add it to the total priority.
// To try and be clever, we don't want a long queue to hog all resources. So two things:
// -if a queue has enough of resource X for the 1st element, its priority is decreased (/2).
// -queues accounts are capped at "resources for the first + 80% of the next"
// This avoids getting a high priority queue with many elements hogging all of one resource
// uselessly while it awaits for other resources.
for (var j in this.queues) {
var outQueueCost = this.queues[j].outQueueCost();
var queueCost = this.queues[j].queueCost();
if (this.accounts[j][ress] < queueCost[ress] + outQueueCost[ress])
{
// adding us to the list of queues that need an update.
tempPrio[j] = this.priorities[j];
maxNeed[j] = outQueueCost[ress] + this.queues[j].getNext().getCost()[ress];
// if we have enough of that resource for the outqueue and our first resource in the queue, diminish our priority.
if (this.accounts[j][ress] >= outQueueCost[ress] + this.queues[j].getNext().getCost()[ress])
{
tempPrio[j] /= 2;
if (this.queues[j].length() !== 1)
{
var halfcost = this.queues[j].queue[1].getCost()[ress]*0.8;
maxNeed[j] += halfcost;
if (this.accounts[j][ress] >= outQueueCost[ress] + this.queues[j].getNext().getCost()[ress] + halfcost)
delete tempPrio[j];
}
}
if (tempPrio[j])
totalPriority += tempPrio[j];
}
}
// Now we allow resources to the accounts. We can at most allow "TempPriority/totalpriority*available"
// But we'll sometimes allow less if that would overflow.
for (var j in tempPrio) {
// we'll add at much what can be allowed to this queue.
var toAdd = Math.floor(tempPrio[j]/totalPriority * availableRes[ress]);
// let's check we're not adding too much.
var maxAdd = Math.min(maxNeed[j] - this.accounts[j][ress], toAdd);
this.accounts[j][ress] += maxAdd;
}
}
}
Engine.ProfileStop();
Engine.ProfileStart("Execute items");
var units_Techs_passed = 0;
// Handle output queues by executing items where possible
for (var p in this.queueArrays) {
var name = this.queueArrays[p][0];
var queue = this.queueArrays[p][1];
var next = queue.outQueueNext();
if (!next)
continue;
if (next.category === "building") {
if (gameState.buildingsBuilt == 0) {
if (next.canExecute(gameState)) {
this.accounts[name].subtract(next.getCost())
//debug ("Starting " + next.type + " substracted " + uneval(next.getCost()))
queue.executeNext(gameState);
gameState.buildingsBuilt += 1;
}
}
} else {
if (units_Techs_passed < 2 && queue.outQueueNext().canExecute(gameState)){
//debug ("Starting " + next.type + " substracted " + uneval(next.getCost()))
this.accounts[name].subtract(next.getCost())
queue.executeNext(gameState);
units_Techs_passed++;
}
}
if (units_Techs_passed >= 2)
continue;
}
Engine.ProfileStop();
Engine.ProfileStop();
};
QueueManager.prototype.addQueue = function(queueName, priority) {
if (this.queues[queueName] == undefined) {
this.queues[queueName] = new Queue();
this.priorities[queueName] = priority;
this.account[queueName] = 0;
this.accounts[queueName] = new Resources();
var self = this;
this.queueArrays = [];
for (var p in this.queues)
this.queueArrays.push([p,this.queues[p]]);
this.queueArrays.sort(function (a,b) { return (self.priorities[b[0]] - self.priorities[a[0]]) });
}
}
QueueManager.prototype.removeQueue = function(queueName) {
if (this.queues[queueName] !== undefined) {
if ( this.curItemQueue.indexOf(queueName) !== -1) {
this.curItemQueue.splice(this.curItemQueue.indexOf(queueName),1);
}
delete this.queues[queueName];
delete this.priorities[queueName];
delete this.account[queueName];
delete this.accounts[queueName];
var self = this;
this.queueArrays = [];
for (var p in this.queues)
this.queueArrays.push([p,this.queues[p]]);
this.queueArrays.sort(function (a,b) { return (self.priorities[b[0]] - self.priorities[a[0]]) });
}
}
QueueManager.prototype.changePriority = function(queueName, newPriority) {
var self = this;
if (this.queues[queueName] !== undefined)
this.priorities[queueName] = newPriority;
this.queueArrays = [];
for (var p in this.queues) {
this.queueArrays.push([p,this.queues[p]]);
}
this.queueArrays.sort(function (a,b) { return (self.priorities[b[0]] - self.priorities[a[0]]) });
}

View File

@ -1,152 +0,0 @@
/*
* Holds a list of wanted items to train or construct
*/
var Queue = function() {
this.queue = [];
this.outQueue = [];
};
Queue.prototype.empty = function() {
this.queue = [];
this.outQueue = [];
};
Queue.prototype.addItem = function(plan) {
for (var i in this.queue)
{
if (plan.category === "unit" && this.queue[i].type == plan.type && this.queue[i].number + plan.number <= this.queue[i].maxMerge)
{
this.queue[i].addItem(plan.number)
return;
}
}
this.queue.push(plan);
};
Queue.prototype.getNext = function() {
if (this.queue.length > 0) {
return this.queue[0];
} else {
return null;
}
};
Queue.prototype.outQueueNext = function(){
if (this.outQueue.length > 0) {
return this.outQueue[0];
} else {
return null;
}
};
Queue.prototype.outQueueCost = function(){
var cost = new Resources();
for (var key in this.outQueue){
cost.add(this.outQueue[key].getCost());
}
return cost;
};
Queue.prototype.queueCost = function(){
var cost = new Resources();
for (var key in this.queue){
cost.add(this.queue[key].getCost());
}
return cost;
};
Queue.prototype.nextToOutQueue = function(){
if (this.queue.length > 0){
this.outQueue.push(this.queue.shift());
}
};
Queue.prototype.executeNext = function(gameState) {
if (this.outQueue.length > 0) {
this.outQueue.shift().execute(gameState);
return true;
} else {
return false;
}
};
Queue.prototype.length = function() {
return this.queue.length;
};
Queue.prototype.countQueuedUnits = function(){
var count = 0;
for (var i in this.queue){
count += this.queue[i].number;
}
return count;
};
Queue.prototype.countOutQueuedUnits = function(){
var count = 0;
for (var i in this.outQueue){
count += this.outQueue[i].number;
}
return count;
};
Queue.prototype.countTotalQueuedUnits = function(){
var count = 0;
for (var i in this.queue){
count += this.queue[i].number;
}
for (var i in this.outQueue){
count += this.outQueue[i].number;
}
return count;
};
Queue.prototype.countTotalQueuedUnitsWithClass = function(classe){
var count = 0;
for (var i in this.queue){
if (this.queue[i].template && this.queue[i].template.hasClass(classe))
count += this.queue[i].number;
}
for (var i in this.outQueue){
if (this.outQueue[i].template && this.outQueue[i].template.hasClass(classe))
count += this.outQueue[i].number;
}
return count;
};
Queue.prototype.countTotalQueuedUnitsWithMetadata = function(data,value){
var count = 0;
for (var i in this.queue){
if (this.queue[i].metadata[data] && this.queue[i].metadata[data] == value)
count += this.queue[i].number;
}
for (var i in this.outQueue){
if (this.outQueue[i].metadata[data] && this.outQueue[i].metadata[data] == value)
count += this.outQueue[i].number;
}
return count;
};
Queue.prototype.totalLength = function(){
return this.queue.length + this.outQueue.length;
};
Queue.prototype.outQueueLength = function(){
return this.outQueue.length;
};
Queue.prototype.countAllByType = function(t){
var count = 0;
for (var i = 0; i < this.queue.length; i++){
if (this.queue[i].type === t){
count += this.queue[i].number;
}
}
for (var i = 0; i < this.outQueue.length; i++){
if (this.outQueue[i].type === t){
count += this.outQueue[i].number;
}
}
return count;
};

View File

@ -1,116 +0,0 @@
/*
* Used to know which templates I have, which templates I know I can train, things like that.
* Mostly unused.
*/
var TemplateManager = function(gameState) {
var self = this;
this.knownTemplatesList = [];
this.buildingTemplates = [];
this.unitTemplates = [];
this.templateCounters = {};
this.templateCounteredBy = {};
// this will store templates that exist
this.AcknowledgeTemplates(gameState);
this.getBuildableSubtemplates(gameState);
this.getTrainableSubtemplates(gameState);
this.getBuildableSubtemplates(gameState);
this.getTrainableSubtemplates(gameState);
// should be enough in 100% of the cases.
this.getTemplateCounters(gameState);
};
TemplateManager.prototype.AcknowledgeTemplates = function(gameState)
{
var self = this;
var myEntities = gameState.getOwnEntities();
myEntities.forEach(function(ent) { // }){
var template = ent._templateName;
if (self.knownTemplatesList.indexOf(template) === -1) {
self.knownTemplatesList.push(template);
if (ent.hasClass("Unit") && self.unitTemplates.indexOf(template) === -1)
self.unitTemplates.push(template);
else if (self.buildingTemplates.indexOf(template) === -1)
self.buildingTemplates.push(template);
}
});
}
TemplateManager.prototype.getBuildableSubtemplates = function(gameState)
{
for each (var templateName in this.knownTemplatesList) {
var template = gameState.getTemplate(templateName);
if (template !== null) {
var buildable = template.buildableEntities();
if (buildable !== undefined)
for each (var subtpname in buildable) {
if (this.knownTemplatesList.indexOf(subtpname) === -1) {
this.knownTemplatesList.push(subtpname);
var subtemplate = gameState.getTemplate(subtpname);
if (subtemplate.hasClass("Unit") && this.unitTemplates.indexOf(subtpname) === -1)
this.unitTemplates.push(subtpname);
else if (this.buildingTemplates.indexOf(subtpname) === -1)
this.buildingTemplates.push(subtpname);
}
}
}
}
}
TemplateManager.prototype.getTrainableSubtemplates = function(gameState)
{
for each (var templateName in this.knownTemplatesList) {
var template = gameState.getTemplate(templateName);
if (template !== null) {
var trainables = template.trainableEntities();
if (trainables !== undefined)
for each (var subtpname in trainables) {
if (this.knownTemplatesList.indexOf(subtpname) === -1) {
this.knownTemplatesList.push(subtpname);
var subtemplate = gameState.getTemplate(subtpname);
if (subtemplate.hasClass("Unit") && this.unitTemplates.indexOf(subtpname) === -1)
this.unitTemplates.push(subtpname);
else if (this.buildingTemplates.indexOf(subtpname) === -1)
this.buildingTemplates.push(subtpname);
}
}
}
}
}
TemplateManager.prototype.getTemplateCounters = function(gameState)
{
for (var i in this.unitTemplates)
{
var tp = gameState.getTemplate(this.unitTemplates[i]);
var tpname = this.unitTemplates[i];
this.templateCounters[tpname] = tp.getCounteredClasses();
}
}
// features auto-caching
TemplateManager.prototype.getCountersToClasses = function(gameState,classes,templateName)
{
if (templateName !== undefined && this.templateCounteredBy[templateName])
return this.templateCounteredBy[templateName];
var templates = [];
for (var i in this.templateCounters) {
var okay = false;
for each (var ticket in this.templateCounters[i]) {
var okaya = true;
for (var a in ticket[0]) {
if (classes.indexOf(ticket[0][a]) === -1)
okaya = false;
}
if (okaya && templates.indexOf(i) === -1)
templates.push([i, ticket[1]]);
}
}
templates.sort (function (a,b) { return -a[1] + b[1]; });
if (templateName !== undefined)
this.templateCounteredBy[templateName] = templates;
return templates;
}

View File

@ -1,106 +0,0 @@
//The Timer class // The instance of this class is created in the qBot object under the name 'timer'
//The methods that are available to call from this instance are:
//timer.setTimer : Creates a new timer with the given interval (miliseconds).
// Optionally set dalay or a limited repeat value.
//timer.checkTimer : Gives true if called at the time of the interval.
//timer.clearTimer : Deletes the timer permanently. No way to get the same timer back.
//timer.activateTimer : Sets the status of a deactivated timer to active.
//timer.deactivateTimer : Deactivates a timer. Deactivated timers will never give true.
// Currently totally unused, iirc.
//-EmjeR-// Timer class //
var Timer = function() {
///Private array.
var alarmList = [];
///Private methods
function num_alarms() {
return alarmList.length;
};
function get_alarm(id) {
return alarmList[id];
};
function add_alarm(index, alarm) {
alarmList[index] = alarm;
};
function delete_alarm(id) {
// Set the array element to undefined
delete alarmList[id];
};
///Privileged methods
// Add an new alarm to the list
this.setTimer = function(gameState, interval, delay, repeat) {
delay = delay || 0;
repeat = repeat || -1;
var index = num_alarms();
//Add a new alarm to the list
add_alarm(index, new alarm(gameState, index, interval, delay, repeat));
return index;
};
// Check if a alarm has reached its interval.
this.checkTimer = function(gameState,id) {
var alarm = get_alarm(id);
if (alarm === undefined)
return false;
if (!alarm.active)
return false;
var time = gameState.getTimeElapsed();
var alarmState = false;
// If repeat forever (repeat is -1). Or if the alarm has rung less times than repeat.
if (alarm.repeat < 0 || alarm.counter < alarm.repeat) {
var time_diffrence = time - alarm.start_time - alarm.delay - alarm.interval * alarm.counter;
if (time_diffrence > alarm.interval) {
alarmState = true;
alarm.counter++;
}
}
// Check if the alarm has rung 'alarm.repeat' times if so, delete the alarm.
if (alarm.counter >= alarm.repeat && alarm.repeat != -1) {
this.clearTimer(id);
}
return alarmState;
};
// Remove an alarm from the list.
this.clearTimer = function(id) {
delete_alarm(id);
};
// Activate a deactivated alarm.
this.activateTimer = function(id) {
var alarm = get_alarm(id);
alarm.active = true;
};
// Deactivate an active alarm but don't delete it.
this.deactivateTimer = function(id) {
var alarm = get_alarm(id);
alarm.active = false;
};
};
//-EmjeR-// Alarm class //
function alarm(gameState, id, interval, delay, repeat) {
this.id = id;
this.interval = interval;
this.delay = delay;
this.repeat = repeat;
this.start_time = gameState.getTimeElapsed();
this.active = true;
this.counter = 0;
};

View File

@ -1,26 +0,0 @@
function AssocArraytoArray(assocArray) {
var endArray = [];
for (var i in assocArray)
endArray.push(assocArray[i]);
return endArray;
};
// A is the reference, B must be in "range" of A
// this supposes the range is already squared
function inRange(a, b, range)// checks for X distance
{
// will avoid unnecessary checking for position in some rare cases... I'm lazy
if (a === undefined || b === undefined || range === undefined)
return undefined;
var dx = a[0] - b[0];
var dz = a[1] - b[1];
return ((dx*dx + dz*dz ) < range);
}
// slower than SquareVectorDistance, faster than VectorDistance but not exactly accurate.
function ManhattanDistance(a, b)
{
var dx = a[0] - b[0];
var dz = a[1] - b[1];
return Math.abs(dx) + Math.abs(dz);
}

View File

@ -1,511 +0,0 @@
/**
* This class makes a worker do as instructed by the economy manager
*/
var Worker = function(ent) {
this.ent = ent;
this.maxApproachTime = 45000;
this.unsatisfactoryResource = false; // if true we'll reguarly check if we can't have better now.
};
Worker.prototype.update = function(gameState) {
var subrole = this.ent.getMetadata(PlayerID, "subrole");
if (!this.ent.position() || (this.ent.getMetadata(PlayerID,"fleeing") && gameState.getTimeElapsed() - this.ent.getMetadata(PlayerID,"fleeing") < 8000)){
// If the worker has no position then no work can be done
return;
}
if (this.ent.getMetadata(PlayerID,"fleeing"))
this.ent.setMetadata(PlayerID,"fleeing", undefined);
if (subrole === "gatherer") {
if (this.ent.unitAIState().split(".")[1] !== "GATHER" && this.ent.unitAIState().split(".")[1] !== "COMBAT" && this.ent.unitAIState().split(".")[1] !== "RETURNRESOURCE"){
// TODO: handle combat for hunting animals
if (!this.ent.resourceCarrying() || this.ent.resourceCarrying().length === 0 ||
this.ent.resourceCarrying()[0].type === this.ent.getMetadata(PlayerID, "gather-type")){
Engine.ProfileStart("Start Gathering");
this.startGathering(gameState);
Engine.ProfileStop();
} else {
// Should deposit resources
Engine.ProfileStart("Return Resources");
if (!this.returnResources(gameState))
{
// no dropsite, abandon cargo.
// if we have a new order
if (this.ent.resourceCarrying()[0].type !== this.ent.getMetadata(PlayerID, "gather-type"))
this.startGathering(gameState);
else {
this.ent.setMetadata(PlayerID, "gather-type",undefined);
this.ent.setMetadata(PlayerID, "subrole", "idle");
this.ent.stopMoving();
}
}
Engine.ProfileStop();
}
this.startApproachingResourceTime = gameState.getTimeElapsed();
//Engine.PostCommand({"type": "set-shading-color", "entities": [this.ent.id()], "rgb": [10,0,0]});
} else if (this.ent.unitAIState().split(".")[1] === "GATHER") {
if (this.unsatisfactoryResource && (this.ent.id() + gameState.ai.playedTurn) % 20 === 0)
{
Engine.ProfileStart("Start Gathering");
this.startGathering(gameState);
Engine.ProfileStop();
}
/*if (gameState.getTimeElapsed() - this.startApproachingResourceTime > this.maxApproachTime) {
if (this.gatheringFrom) {
var ent = gameState.getEntityById(this.gatheringFrom);
if ((ent && ent.resourceSupplyAmount() == ent.resourceSupplyMax())) {
// if someone gathers from it, it's only that the pathfinder sucks.
debug (ent.toString() + " is inaccessible");
ent.setMetadata(PlayerID, "inaccessible", true);
this.ent.flee(ent);
this.ent.setMetadata(PlayerID, "subrole", "idle");
this.gatheringFrom = undefined;
}
}
}*/
} else if (this.ent.unitAIState().split(".")[1] === "COMBAT") {
/*if (gameState.getTimeElapsed() - this.startApproachingResourceTime > this.maxApproachTime) {
var ent = gameState.getEntityById(this.ent.unitAIOrderData()[0].target);
if (ent && !ent.isHurt()) {
// if someone gathers from it, it's only that the pathfinder sucks.
debug (ent.toString() + " is inaccessible from Combat");
ent.setMetadata(PlayerID, "inaccessible", true);
this.ent.flee(ent);
this.ent.setMetadata(PlayerID, "subrole", "idle");
this.gatheringFrom = undefined;
}
}*/
} else {
this.startApproachingResourceTime = gameState.getTimeElapsed();
}
} else if(subrole === "builder") {
if (this.ent.unitAIState().split(".")[1] !== "REPAIR"){
var target = this.ent.getMetadata(PlayerID, "target-foundation");
if (target.foundationProgress() === undefined && target.needsRepair() == false)
this.ent.setMetadata(PlayerID, "subrole", "idle");
else
this.ent.repair(target);
}
this.startApproachingResourceTime = gameState.getTimeElapsed();
//Engine.PostCommand({"type": "set-shading-color", "entities": [this.ent.id()], "rgb": [0,10,0]});
} else if(subrole === "hunter") {
if (!this.ent.resourceCarrying() || this.ent.resourceCarrying().length === 0){
Engine.ProfileStart("Start Hunting");
this.startHunting(gameState);
Engine.ProfileStop();
}
} else {
this.startApproachingResourceTime = gameState.getTimeElapsed();
}
};
Worker.prototype.startGathering = function(gameState){
var resource = this.ent.getMetadata(PlayerID, "gather-type");
var ent = this.ent;
if (!ent.position()){
// TODO: work out what to do when entity has no position
return;
}
this.unsatisfactoryResource = false;
// TODO: this is not necessarily optimal.
// find closest dropsite which has nearby resources of the correct type
var minDropsiteDist = Math.min(); // set to infinity initially
var nearestResources = undefined;
var nearestDropsite = undefined;
// first step: count how many dropsites we have that have enough resources "close" to them.
// TODO: this is a huge part of multi-base support. Count only those in the same base as the worker.
var number = 0;
var ourDropsites = gameState.getOwnDropsites(resource);
if (ourDropsites.length === 0)
{
debug ("We do not have a dropsite for " + resource + ", aborting");
return;
}
ourDropsites.forEach(function (dropsite) {
if (dropsite.getMetadata(PlayerID, "linked-resources-" +resource) !== undefined
&& dropsite.getMetadata(PlayerID, "resource-quantity-" +resource) !== undefined && dropsite.getMetadata(PlayerID, "resource-quantity-" +resource) > 200) {
number++;
}
});
//debug ("Available " +resource + " dropsites: " +ourDropsites.length);
// Allright second step, if there are any such dropsites, we pick the closest.
// we pick one with a lot of resource, or we pick the only one available (if it's high enough, otherwise we'll see with "far" below).
if (number > 0)
{
ourDropsites.forEach(function (dropsite) { //}){
if (dropsite.getMetadata(PlayerID, "resource-quantity-" +resource) == undefined)
return;
if (dropsite.position() && (dropsite.getMetadata(PlayerID, "resource-quantity-" +resource) > 700 || (number === 1 && dropsite.getMetadata(PlayerID, "resource-quantity-" +resource) > 200) ) ) {
var dist = SquareVectorDistance(ent.position(), dropsite.position());
if (dist < minDropsiteDist){
minDropsiteDist = dist;
nearestResources = dropsite.getMetadata(PlayerID, "linked-resources-" + resource);
nearestDropsite = dropsite;
}
}
});
}
//debug ("Nearest dropsite: " +nearestDropsite);
// Now if we have no dropsites, we repeat the process with resources "far" from dropsites but still linked with them.
// I add the "close" value for code sanity.
// Again, we choose a dropsite with a lot of resources left, or we pick the only one available (in this case whatever happens).
if (!nearestResources || nearestResources.length === 0) {
//debug ("here(1)");
gameState.getOwnDropsites(resource).forEach(function (dropsite){ //}){
var quantity = dropsite.getMetadata(PlayerID, "resource-quantity-" +resource)+dropsite.getMetadata(PlayerID, "resource-quantity-far-" +resource);
if (dropsite.position() && (quantity) > 700 || number === 1) {
var dist = SquareVectorDistance(ent.position(), dropsite.position());
if (dist < minDropsiteDist){
minDropsiteDist = dist;
nearestResources = dropsite.getMetadata(PlayerID, "linked-resources-" + resource);
nearestDropsite = dropsite;
}
}
});
this.unsatisfactoryResource = true;
//debug ("Nearest dropsite: " +nearestDropsite);
}
// If we still haven't found any fitting dropsite...
// Then we'll just pick any resource, and we'll check for the closest dropsite to that one
if (!nearestResources || nearestResources.length === 0){
//debug ("No fitting dropsite for " + resource + " found, iterating the map.");
nearestResources = gameState.getResourceSupplies(resource);
this.unsatisfactoryResource = true;
}
if (nearestResources.length === 0){
if (resource === "food")
{
if (this.buildAnyField(gameState))
return;
debug("No " + resource + " found! (1)");
}
else
debug("No " + resource + " found! (1)");
return;
}
//debug("Found " + nearestResources.length + "spots for " + resource);
/*if (!nearestDropsite) {
debug ("No dropsite for " +resource);
return;
}*/
var supplies = [];
var nearestSupplyDist = Math.min();
var nearestSupply = undefined;
// filter resources
// TODo: add a bonus for resources with a lot of resources left, perhaps, to spread gathering?
nearestResources.forEach(function(supply) { //}){
// sanity check, perhaps sheep could be garrisoned?
if (!supply.position()) {
//debug ("noposition");
return;
}
if (supply.getMetadata(PlayerID, "inaccessible") === true) {
//debug ("inaccessible");
return;
}
if (supply.isFull() === true || (supply.maxGatherers() - supply.resourceSupplyGatherers().length == 0) ||
(gameState.turnCache["ressGathererNB"] && gameState.turnCache["ressGathererNB"][supply.id()]
&& gameState.turnCache["ressGathererNB"][supply.id()] + supply.resourceSupplyGatherers().length >= supply.maxGatherers())) {
return;
}
// Don't gather enemy farms
if (!supply.isOwn(PlayerID) && supply.owner() !== 0) {
//debug ("enemy");
return;
}
// quickscope accessbility check.
if (!gameState.ai.accessibility.pathAvailable(gameState, ent.position(), supply.position(), true)) {
//debug ("nopath");
return;
}
// some simple check for chickens: if they're in a square that's inaccessible, we won't gather from them.
if (supply.footprintRadius() < 1)
{
var fakeMap = new Map(gameState,gameState.getMap().data);
var id = fakeMap.gamePosToMapPos(supply.position())[0] + fakeMap.width*fakeMap.gamePosToMapPos(supply.position())[1];
if ( (gameState.sharedScript.passabilityClasses["pathfinderObstruction"] & gameState.getMap().data[id]) )
{
supply.setMetadata(PlayerID, "inaccessible", true)
return;
}
}
// measure the distance to the resource (largely irrelevant)
var dist = SquareVectorDistance(supply.position(), ent.position());
if (dist > 4900 && supply.hasClass("Animal"))
return;
// Add on a factor for the nearest dropsite if one exists
if (nearestDropsite !== undefined ){
dist += 4*SquareVectorDistance(supply.position(), nearestDropsite.position());
dist /= 5.0;
}
var territoryOwner = Map.createTerritoryMap(gameState).getOwner(supply.position());
if (territoryOwner != PlayerID && territoryOwner != 0) {
dist *= 3.0;
//return;
}
// Go for treasure as a priority
if (dist < 40000 && supply.resourceSupplyType().generic == "treasure"){
dist /= 1000;
}
if (dist < nearestSupplyDist) {
nearestSupplyDist = dist;
nearestSupply = supply;
}
});
if (nearestSupply) {
var pos = nearestSupply.position();
// find a fitting dropsites in case we haven't already.
if (!nearestDropsite) {
ourDropsites.forEach(function (dropsite){ //}){
if (dropsite.position()){
var dist = SquareVectorDistance(pos, dropsite.position());
if (dist < minDropsiteDist){
minDropsiteDist = dist;
nearestDropsite = dropsite;
}
}
});
if (!nearestDropsite)
{
debug ("No dropsite for " +resource);
return;
}
}
// if the resource is far away, try to build a farm instead.
var tried = false;
if (resource === "food" && SquareVectorDistance(pos,this.ent.position()) > 22500)
{
tried = this.buildAnyField(gameState);
if (!tried && SquareVectorDistance(pos,this.ent.position()) > 62500) {
return; // wait. a farm should appear.
}
}
if (!tried) {
if (!gameState.turnCache["ressGathererNB"])
{
gameState.turnCache["ressGathererNB"] = {};
gameState.turnCache["ressGathererNB"][nearestSupply.id()] = 1;
} else if (!gameState.turnCache["ressGathererNB"][nearestSupply.id()])
gameState.turnCache["ressGathererNB"][nearestSupply.id()] = 1;
else
gameState.turnCache["ressGathererNB"][nearestSupply.id()]++;
this.maxApproachTime = Math.max(25000, VectorDistance(pos,this.ent.position()) * 1000);
ent.gather(nearestSupply);
ent.setMetadata(PlayerID, "target-foundation", undefined);
// check if the resource we've started gathering from is now full, in which case inform the dropsite.
if (gameState.turnCache["ressGathererNB"][nearestSupply.id()] + nearestSupply.resourceSupplyGatherers().length >= nearestSupply.maxGatherers()
&& nearestSupply.getMetadata(PlayerID, "linked-dropsite") != undefined)
{
var dropsite = gameState.getEntityById(nearestSupply.getMetadata(PlayerID, "linked-dropsite"));
if (dropsite == undefined || dropsite.getMetadata(PlayerID, "linked-resources-" + resource) === undefined)
return;
if (nearestSupply.getMetadata(PlayerID, "linked-dropsite-nearby") == true) {
dropsite.setMetadata(PlayerID, "resource-quantity-" + resource, +dropsite.getMetadata(PlayerID, "resource-quantity-" + resource) - (+nearestSupply.getMetadata(PlayerID, "dp-update-value")));
dropsite.getMetadata(PlayerID, "linked-resources-" + resource).updateEnt(nearestSupply);
dropsite.getMetadata(PlayerID, "nearby-resources-" + resource).updateEnt(nearestSupply);
} else {
dropsite.setMetadata(PlayerID, "resource-quantity-far-" + resource, +dropsite.getMetadata(PlayerID, "resource-quantity-" + resource) - (+nearestSupply.getMetadata(PlayerID, "dp-update-value")));
dropsite.getMetadata(PlayerID, "linked-resources-" + resource).updateEnt(nearestSupply);
}
}
}
} else {
if (resource === "food" && this.buildAnyField(gameState))
return;
debug("No " + resource + " found! (2)");
// If we had a fitting closest dropsite with a lot of resources, mark it as not good. It means it's probably full. Then retry.
// it'll be resetted next time it's counted anyway.
if (nearestDropsite && nearestDropsite.getMetadata(PlayerID, "resource-quantity-" +resource)+nearestDropsite.getMetadata(PlayerID, "resource-quantity-far-" +resource) > 400)
{
nearestDropsite.setMetadata(PlayerID, "resource-quantity-" +resource, 0);
nearestDropsite.setMetadata(PlayerID, "resource-quantity-far-" +resource, 0);
this.startGathering(gameState);
}
}
};
// Makes the worker deposit the currently carried resources at the closest dropsite
Worker.prototype.returnResources = function(gameState){
if (!this.ent.resourceCarrying() || this.ent.resourceCarrying().length === 0){
return true; // assume we're OK.
}
var resource = this.ent.resourceCarrying()[0].type;
var self = this;
if (!this.ent.position()){
// TODO: work out what to do when entity has no position
return true;
}
var closestDropsite = undefined;
var dist = Math.min();
gameState.getOwnDropsites(resource).forEach(function(dropsite){
if (dropsite.position()){
var d = SquareVectorDistance(self.ent.position(), dropsite.position());
if (d < dist){
dist = d;
closestDropsite = dropsite;
}
}
});
if (!closestDropsite){
debug("No dropsite found to deposit " + resource);
return false;
}
this.ent.returnResources(closestDropsite);
return true;
};
Worker.prototype.startHunting = function(gameState){
var ent = this.ent;
if (!ent.position() || ent.getMetadata(PlayerID, "stoppedHunting"))
return;
// So here we're doing it basic. We check what we can hunt, we hunt it. No fancies.
var resources = gameState.getResourceSupplies("food");
if (resources.length === 0){
debug("No food found to hunt!");
return;
}
var supplies = [];
var nearestSupplyDist = Math.min();
var nearestSupply = undefined;
resources.forEach(function(supply) { //}){
if (!supply.position())
return;
if (supply.getMetadata(PlayerID, "inaccessible") === true)
return;
if (supply.isFull() === true)
return;
if (!supply.hasClass("Animal"))
return;
// measure the distance to the resource
var dist = SquareVectorDistance(supply.position(), ent.position());
var territoryOwner = Map.createTerritoryMap(gameState).getOwner(supply.position());
if (territoryOwner != PlayerID && territoryOwner != 0) {
dist *= 3.0;
}
// quickscope accessbility check
if (!gameState.ai.accessibility.pathAvailable(gameState, ent.position(), supply.position(), true))
return;
if (dist < nearestSupplyDist) {
nearestSupplyDist = dist;
nearestSupply = supply;
}
});
if (nearestSupply) {
var pos = nearestSupply.position();
var nearestDropsite = 0;
var minDropsiteDist = 1000000;
// find a fitting dropsites in case we haven't already.
gameState.getOwnDropsites("food").forEach(function (dropsite){ //}){
if (dropsite.position()){
var dist = SquareVectorDistance(pos, dropsite.position());
if (dist < minDropsiteDist){
minDropsiteDist = dist;
nearestDropsite = dropsite;
}
}
});
if (!nearestDropsite)
{
ent.setMetadata(PlayerID, "stoppedHunting", true);
ent.setMetadata(PlayerID, "role", undefined);
debug ("No dropsite for hunting food");
return;
}
if (minDropsiteDist > 45000) {
ent.setMetadata(PlayerID, "stoppedHunting", true);
ent.setMetadata(PlayerID, "role", undefined);
} else {
ent.gather(nearestSupply);
ent.setMetadata(PlayerID, "target-foundation", undefined);
}
} else {
ent.setMetadata(PlayerID, "stoppedHunting", true);
ent.setMetadata(PlayerID, "role", undefined);
debug("No food found for hunting! (2)");
}
};
Worker.prototype.getResourceType = function(type){
if (!type || !type.generic){
return undefined;
}
if (type.generic === "treasure"){
return type.specific;
}else{
return type.generic;
}
};
Worker.prototype.buildAnyField = function(gameState){
var self = this;
var okay = false;
var foundations = gameState.getOwnFoundations();
foundations.filterNearest(this.ent.position(), foundations.length);
foundations.forEach(function (found) {
if (found._template.BuildRestrictions.Category === "Field" && !okay) {
self.ent.repair(found);
okay = true;
return;
}
});
return okay;
};