Adding an experimental version of qBot. This is half a crossover with my former Marilyn bot (defense manager, attack plans) and some improvements here and there that I believe could help improve the bot.
This was SVN commit r12267.
This commit is contained in:
parent
0d5366fd7b
commit
45ee419171
1
binaries/data/mods/public/simulation/ai/qbot-wc/_init.js
Normal file
1
binaries/data/mods/public/simulation/ai/qbot-wc/_init.js
Normal file
@ -0,0 +1 @@
|
||||
Engine.IncludeModule("common-api-v2");
|
@ -0,0 +1,205 @@
|
||||
function AttackMoveToCC(gameState, militaryManager){
|
||||
this.minAttackSize = 20;
|
||||
this.maxAttackSize = 60;
|
||||
this.idList=[];
|
||||
|
||||
this.previousTime = 0;
|
||||
this.state = "unexecuted";
|
||||
|
||||
this.healthRecord = [];
|
||||
};
|
||||
|
||||
// Returns true if the attack can be executed at the current time
|
||||
AttackMoveToCC.prototype.canExecute = function(gameState, militaryManager){
|
||||
var enemyStrength = militaryManager.measureEnemyStrength(gameState);
|
||||
var enemyCount = militaryManager.measureEnemyCount(gameState);
|
||||
|
||||
// We require our army to be >= this strength
|
||||
var targetStrength = enemyStrength * 1.5;
|
||||
|
||||
var availableCount = militaryManager.countAvailableUnits();
|
||||
var availableStrength = militaryManager.measureAvailableStrength();
|
||||
|
||||
debug("Troops needed for attack: " + this.minAttackSize + " Have: " + availableCount);
|
||||
debug("Troops strength for attack: " + targetStrength + " Have: " + availableStrength);
|
||||
|
||||
return ((availableStrength >= targetStrength && availableCount >= this.minAttackSize)
|
||||
|| availableCount >= this.maxAttackSize);
|
||||
};
|
||||
|
||||
// Executes the attack plan, after this is executed the update function will be run every turn
|
||||
AttackMoveToCC.prototype.execute = function(gameState, militaryManager){
|
||||
var availableCount = militaryManager.countAvailableUnits();
|
||||
this.idList = militaryManager.getAvailableUnits(availableCount);
|
||||
|
||||
var pending = EntityCollectionFromIds(gameState, this.idList);
|
||||
|
||||
// Find the critical enemy buildings we could attack
|
||||
var targets = militaryManager.getEnemyBuildings(gameState,"ConquestCritical");
|
||||
// If there are no critical structures, attack anything else that's critical
|
||||
if (targets.length == 0) {
|
||||
targets = gameState.entities.filter(function(ent) {
|
||||
return (gameState.isEntityEnemy(ent) && ent.hasClass("ConquestCritical") && ent.owner() !== 0 && ent.position());
|
||||
});
|
||||
}
|
||||
// If there's nothing, attack anything else that's less critical
|
||||
if (targets.length == 0) {
|
||||
targets = militaryManager.getEnemyBuildings(gameState,"Town");
|
||||
}
|
||||
if (targets.length == 0) {
|
||||
targets = militaryManager.getEnemyBuildings(gameState,"Village");
|
||||
}
|
||||
|
||||
// If we have a target, move to it
|
||||
if (targets.length) {
|
||||
// Add an attack role so the economic manager doesn't try and use them
|
||||
pending.forEach(function(ent) {
|
||||
ent.setMetadata("role", "attack");
|
||||
});
|
||||
|
||||
var curPos = pending.getCentrePosition();
|
||||
|
||||
var target = targets.toEntityArray()[0];
|
||||
this.targetPos = target.position();
|
||||
|
||||
// Find possible distinct paths to the enemy
|
||||
var pathFinder = new PathFinder(gameState);
|
||||
var pathsToEnemy = pathFinder.getPaths(curPos, this.targetPos);
|
||||
if (! pathsToEnemy){
|
||||
pathsToEnemy = [this.targetPos];
|
||||
}
|
||||
|
||||
var rand = Math.floor(Math.random() * pathsToEnemy.length);
|
||||
this.path = pathsToEnemy[rand];
|
||||
|
||||
pending.move(this.path[0][0], this.path[0][1]);
|
||||
} else if (targets.length == 0 ) {
|
||||
gameState.ai.gameFinished = true;
|
||||
}
|
||||
|
||||
this.state = "walking";
|
||||
};
|
||||
|
||||
// Runs every turn after the attack is executed
|
||||
// This removes idle units from the attack
|
||||
AttackMoveToCC.prototype.update = function(gameState, militaryManager, events){
|
||||
|
||||
// keep the list of units in good order by pruning ids with no corresponding entities (i.e. dead units)
|
||||
var removeList = [];
|
||||
var totalHealth = 0;
|
||||
for (var idKey in this.idList){
|
||||
var id = this.idList[idKey];
|
||||
var ent = militaryManager.entity(id);
|
||||
if (ent === undefined){
|
||||
removeList.push(id);
|
||||
}else{
|
||||
if (ent.hitpoints()){
|
||||
totalHealth += ent.hitpoints();
|
||||
}
|
||||
}
|
||||
}
|
||||
for (var i in removeList){
|
||||
this.idList.splice(this.idList.indexOf(removeList[i]),1);
|
||||
}
|
||||
|
||||
var units = EntityCollectionFromIds(gameState, this.idList);
|
||||
|
||||
if (this.path.length === 0){
|
||||
var idleCount = 0;
|
||||
var self = this;
|
||||
units.forEach(function(ent){
|
||||
if (ent.isIdle()){
|
||||
if (ent.position() && VectorDistance(ent.position(), self.targetPos) > 30){
|
||||
ent.move(self.targetPos[0], self.targetPos[1]);
|
||||
}else{
|
||||
militaryManager.unassignUnit(ent.id());
|
||||
}
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
var deltaHealth = 0;
|
||||
var deltaTime = 1;
|
||||
var time = gameState.getTimeElapsed();
|
||||
this.healthRecord.push([totalHealth, time]);
|
||||
if (this.healthRecord.length > 1){
|
||||
for (var i = this.healthRecord.length - 1; i >= 0; i--){
|
||||
deltaHealth = totalHealth - this.healthRecord[i][0];
|
||||
deltaTime = time - this.healthRecord[i][1];
|
||||
if (this.healthRecord[i][1] < time - 5*1000){
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var numUnits = this.idList.length;
|
||||
if (numUnits < 1) return;
|
||||
var damageRate = -deltaHealth / deltaTime * 1000;
|
||||
var centrePos = units.getCentrePosition();
|
||||
if (! centrePos) return;
|
||||
|
||||
var idleCount = 0;
|
||||
// Looks for idle units away from the formations centre
|
||||
for (var idKey in this.idList){
|
||||
var id = this.idList[idKey];
|
||||
var ent = militaryManager.entity(id);
|
||||
if (ent.isIdle()){
|
||||
if (ent.position() && VectorDistance(ent.position(), centrePos) > 20){
|
||||
var dist = VectorDistance(ent.position(), centrePos);
|
||||
var vector = [centrePos[0] - ent.position()[0], centrePos[1] - ent.position()[1]];
|
||||
vector[0] *= 10/dist;
|
||||
vector[1] *= 10/dist;
|
||||
ent.move(centrePos[0] + vector[0], centrePos[1] + vector[1]);
|
||||
}else{
|
||||
idleCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ((damageRate / Math.sqrt(numUnits)) > 2){
|
||||
if (this.state === "walking"){
|
||||
var sumAttackerPos = [0,0];
|
||||
var numAttackers = 0;
|
||||
|
||||
for (var key in events){
|
||||
var e = events[key];
|
||||
//{type:"Attacked", msg:{attacker:736, target:1133, type:"Melee"}}
|
||||
if (e.type === "Attacked" && e.msg){
|
||||
if (this.idList.indexOf(e.msg.target) !== -1){
|
||||
var attacker = militaryManager.entity(e.msg.attacker);
|
||||
if (attacker && attacker.position()){
|
||||
sumAttackerPos[0] += attacker.position()[0];
|
||||
sumAttackerPos[1] += attacker.position()[1];
|
||||
numAttackers += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (numAttackers > 0){
|
||||
var avgAttackerPos = [sumAttackerPos[0]/numAttackers, sumAttackerPos[1]/numAttackers];
|
||||
// Stop moving
|
||||
units.move(centrePos[0], centrePos[1]);
|
||||
this.state = "attacking";
|
||||
}
|
||||
}
|
||||
}else{
|
||||
if (this.state === "attacking"){
|
||||
units.move(this.path[0][0], this.path[0][1]);
|
||||
this.state = "walking";
|
||||
}
|
||||
}
|
||||
|
||||
if (this.state === "walking"){
|
||||
if (VectorDistance(centrePos, this.path[0]) < 20 || idleCount/numUnits > 0.8){
|
||||
this.path.shift();
|
||||
if (this.path.length > 0){
|
||||
units.move(this.path[0][0], this.path[0][1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.previousTime = time;
|
||||
this.previousHealth = totalHealth;
|
||||
};
|
||||
|
@ -0,0 +1,238 @@
|
||||
function AttackMoveToLocation(gameState, militaryManager, minAttackSize, maxAttackSize, targetFinder){
|
||||
this.minAttackSize = minAttackSize || Config.attack.minAttackSize;
|
||||
this.maxAttackSize = maxAttackSize || Config.attack.maxAttackSize;
|
||||
this.idList=[];
|
||||
|
||||
this.previousTime = 0;
|
||||
this.state = "unexecuted";
|
||||
|
||||
this.targetFinder = targetFinder || this.defaultTargetFinder;
|
||||
|
||||
this.healthRecord = [];
|
||||
};
|
||||
|
||||
// Returns true if the attack can be executed at the current time
|
||||
AttackMoveToLocation.prototype.canExecute = function(gameState, militaryManager){
|
||||
var enemyStrength = militaryManager.measureEnemyStrength(gameState);
|
||||
var enemyCount = militaryManager.measureEnemyCount(gameState);
|
||||
|
||||
// We require our army to be >= this strength
|
||||
var targetStrength = enemyStrength * Config.attack.enemyRatio;
|
||||
|
||||
var availableCount = militaryManager.countAvailableUnits();
|
||||
var availableStrength = militaryManager.measureAvailableStrength();
|
||||
|
||||
debug("Troops needed for attack: " + this.minAttackSize + " Have: " + availableCount);
|
||||
debug("Troops strength for attack: " + targetStrength + " Have: " + availableStrength);
|
||||
|
||||
return ((availableStrength >= targetStrength && availableCount >= this.minAttackSize)
|
||||
|| availableCount >= this.maxAttackSize);
|
||||
};
|
||||
|
||||
// Default target finder aims for conquest critical targets
|
||||
AttackMoveToLocation.prototype.defaultTargetFinder = function(gameState, militaryManager){
|
||||
// Find the critical enemy buildings we could attack
|
||||
var targets = militaryManager.getEnemyBuildings(gameState,"ConquestCritical");
|
||||
// If there are no critical structures, attack anything else that's critical
|
||||
if (targets.length == 0) {
|
||||
targets = gameState.entities.filter(function(ent) {
|
||||
return (gameState.isEntityEnemy(ent) && ent.hasClass("ConquestCritical") && ent.owner() !== 0 && ent.position());
|
||||
});
|
||||
}
|
||||
// If there's nothing, attack anything else that's less critical
|
||||
if (targets.length == 0) {
|
||||
targets = militaryManager.getEnemyBuildings(gameState,"Town");
|
||||
}
|
||||
if (targets.length == 0) {
|
||||
targets = militaryManager.getEnemyBuildings(gameState,"Village");
|
||||
}
|
||||
return targets;
|
||||
};
|
||||
|
||||
// Executes the attack plan, after this is executed the update function will be run every turn
|
||||
AttackMoveToLocation.prototype.execute = function(gameState, militaryManager){
|
||||
var availableCount = militaryManager.countAvailableUnits();
|
||||
var numWanted = Math.min(availableCount, this.maxAttackSize);
|
||||
this.idList = militaryManager.getAvailableUnits(numWanted);
|
||||
|
||||
var pending = EntityCollectionFromIds(gameState, this.idList);
|
||||
|
||||
var targets = this.targetFinder(gameState, militaryManager);
|
||||
|
||||
if (targets.length === 0){
|
||||
targets = this.defaultTargetFinder(gameState, militaryManager);
|
||||
}
|
||||
|
||||
// If we have a target, move to it
|
||||
if (targets.length) {
|
||||
// Add an attack role so the economic manager doesn't try and use them
|
||||
pending.forEach(function(ent) {
|
||||
ent.setMetadata("role", "attack");
|
||||
});
|
||||
|
||||
var curPos = pending.getCentrePosition();
|
||||
|
||||
// pick a random target from the list
|
||||
var rand = Math.floor((Math.random()*targets.length));
|
||||
this.targetPos = undefined;
|
||||
var count = 0;
|
||||
while (!this.targetPos){
|
||||
var target = targets.toEntityArray()[rand];
|
||||
this.targetPos = target.position();
|
||||
count++;
|
||||
if (count > 1000){
|
||||
warn("No target with a valid position found");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Find possible distinct paths to the enemy
|
||||
var pathFinder = new PathFinder(gameState);
|
||||
var pathsToEnemy = pathFinder.getPaths(curPos, this.targetPos);
|
||||
if (!pathsToEnemy || !pathsToEnemy[0] || pathsToEnemy[0][0] === undefined || pathsToEnemy[0][1] === undefined){
|
||||
pathsToEnemy = [[this.targetPos]];
|
||||
}
|
||||
|
||||
var rand = Math.floor(Math.random() * pathsToEnemy.length);
|
||||
this.path = pathsToEnemy[rand];
|
||||
|
||||
pending.move(this.path[0][0], this.path[0][1]);
|
||||
} else if (targets.length == 0 ) {
|
||||
gameState.ai.gameFinished = true;
|
||||
return;
|
||||
}
|
||||
|
||||
this.state = "walking";
|
||||
};
|
||||
|
||||
// Runs every turn after the attack is executed
|
||||
// This removes idle units from the attack
|
||||
AttackMoveToLocation.prototype.update = function(gameState, militaryManager, events){
|
||||
|
||||
if (!this.targetPos){
|
||||
for (var idKey in this.idList){
|
||||
var id = this.idList[idKey];
|
||||
militaryManager.unassignUnit(id);
|
||||
}
|
||||
this.idList = [];
|
||||
}
|
||||
|
||||
// keep the list of units in good order by pruning ids with no corresponding entities (i.e. dead units)
|
||||
var removeList = [];
|
||||
var totalHealth = 0;
|
||||
for (var idKey in this.idList){
|
||||
var id = this.idList[idKey];
|
||||
var ent = militaryManager.entity(id);
|
||||
if (ent === undefined){
|
||||
removeList.push(id);
|
||||
}else{
|
||||
if (ent.hitpoints()){
|
||||
totalHealth += ent.hitpoints();
|
||||
}
|
||||
}
|
||||
}
|
||||
for (var i in removeList){
|
||||
this.idList.splice(this.idList.indexOf(removeList[i]),1);
|
||||
}
|
||||
|
||||
var units = EntityCollectionFromIds(gameState, this.idList);
|
||||
|
||||
if (!this.path || this.path.length === 0){
|
||||
var idleCount = 0;
|
||||
var self = this;
|
||||
units.forEach(function(ent){
|
||||
if (ent.isIdle()){
|
||||
if (ent.position() && VectorDistance(ent.position(), self.targetPos) > 30){
|
||||
ent.move(self.targetPos[0], self.targetPos[1]);
|
||||
}else{
|
||||
militaryManager.unassignUnit(ent.id());
|
||||
}
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
var deltaHealth = 0;
|
||||
var deltaTime = 1;
|
||||
var time = gameState.getTimeElapsed();
|
||||
this.healthRecord.push([totalHealth, time]);
|
||||
if (this.healthRecord.length > 1){
|
||||
for (var i = this.healthRecord.length - 1; i >= 0; i--){
|
||||
deltaHealth = totalHealth - this.healthRecord[i][0];
|
||||
deltaTime = time - this.healthRecord[i][1];
|
||||
if (this.healthRecord[i][1] < time - 5*1000){
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var numUnits = this.idList.length;
|
||||
if (numUnits < 1) return;
|
||||
var damageRate = -deltaHealth / deltaTime * 1000;
|
||||
var centrePos = units.getCentrePosition();
|
||||
if (! centrePos) return;
|
||||
|
||||
var idleCount = 0;
|
||||
// Looks for idle units away from the formations centre
|
||||
for (var idKey in this.idList){
|
||||
var id = this.idList[idKey];
|
||||
var ent = militaryManager.entity(id);
|
||||
if (ent.isIdle()){
|
||||
if (ent.position() && VectorDistance(ent.position(), centrePos) > 20){
|
||||
var dist = VectorDistance(ent.position(), centrePos);
|
||||
var vector = [centrePos[0] - ent.position()[0], centrePos[1] - ent.position()[1]];
|
||||
vector[0] *= 10/dist;
|
||||
vector[1] *= 10/dist;
|
||||
ent.move(centrePos[0] + vector[0], centrePos[1] + vector[1]);
|
||||
}else{
|
||||
idleCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ((damageRate / Math.sqrt(numUnits)) > 2){
|
||||
if (this.state === "walking"){
|
||||
var sumAttackerPos = [0,0];
|
||||
var numAttackers = 0;
|
||||
|
||||
for (var key in events){
|
||||
var e = events[key];
|
||||
//{type:"Attacked", msg:{attacker:736, target:1133, type:"Melee"}}
|
||||
if (e.type === "Attacked" && e.msg){
|
||||
if (this.idList.indexOf(e.msg.target) !== -1){
|
||||
var attacker = militaryManager.entity(e.msg.attacker);
|
||||
if (attacker && attacker.position()){
|
||||
sumAttackerPos[0] += attacker.position()[0];
|
||||
sumAttackerPos[1] += attacker.position()[1];
|
||||
numAttackers += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (numAttackers > 0){
|
||||
var avgAttackerPos = [sumAttackerPos[0]/numAttackers, sumAttackerPos[1]/numAttackers];
|
||||
// Stop moving
|
||||
units.move(centrePos[0], centrePos[1]);
|
||||
this.state = "attacking";
|
||||
}
|
||||
}
|
||||
}else{
|
||||
if (this.state === "attacking"){
|
||||
units.move(this.path[0][0], this.path[0][1]);
|
||||
this.state = "walking";
|
||||
}
|
||||
}
|
||||
|
||||
if (this.state === "walking"){
|
||||
if (VectorDistance(centrePos, this.path[0]) < 20 || idleCount/numUnits > 0.8){
|
||||
this.path.shift();
|
||||
if (this.path.length > 0){
|
||||
units.move(this.path[0][0], this.path[0][1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.previousTime = time;
|
||||
this.previousHealth = totalHealth;
|
||||
};
|
||||
|
592
binaries/data/mods/public/simulation/ai/qbot-wc/attack_plan.js
Executable file
592
binaries/data/mods/public/simulation/ai/qbot-wc/attack_plan.js
Executable file
@ -0,0 +1,592 @@
|
||||
// basically an attack plan. The name is an artifact.
|
||||
function CityAttack(gameState, militaryManager, uniqueID, targetEnemy, type , targetFinder){
|
||||
|
||||
//This is the list of IDs of the units in the plan
|
||||
this.idList=[];
|
||||
|
||||
this.state = "unexecuted";
|
||||
this.targetPlayer = targetEnemy;
|
||||
if (this.targetPlayer === -1 || this.targetPlayer === undefined) {
|
||||
// let's find our prefered target, basically counting our enemies units.
|
||||
var enemyCount = {};
|
||||
for (var i = 1; i <=8; i++)
|
||||
enemyCount[i] = 0;
|
||||
gameState.getEntities().forEach(function(ent) { if (gameState.isEntityEnemy(ent) && ent.owner() !== 0) { enemyCount[ent.owner()]++; } });
|
||||
var max = 0;
|
||||
for (i in enemyCount)
|
||||
if (enemyCount[i] >= max)
|
||||
{
|
||||
this.targetPlayer = +i;
|
||||
max = enemyCount[i];
|
||||
}
|
||||
}
|
||||
debug ("Target = " +this.targetPlayer);
|
||||
this.targetFinder = targetFinder || this.defaultTargetFinder;
|
||||
this.type = type || "normal";
|
||||
this.name = uniqueID;
|
||||
this.healthRecord = [];
|
||||
|
||||
this.timeOfPlanStart = gameState.getTimeElapsed(); // we get the time at which we decided to start the attack
|
||||
this.maxPreparationTime = 300*1000;
|
||||
|
||||
this.pausingStart = 0;
|
||||
this.totalPausingTime = 0;
|
||||
this.paused = false;
|
||||
|
||||
this.onArrivalReaction = "proceedOnTargets";
|
||||
|
||||
this.unitStat = {};
|
||||
this.unitStat["RangedInfantry"] = { "priority" : 1, "minSize" : 4, "targetSize" : 10, "batchSize" : 5, "classes" : ["Infantry","Ranged"], "templates" : [] };
|
||||
this.unitStat["MeleeInfantry"] = { "priority" : 1, "minSize" : 4, "targetSize" : 10, "batchSize" : 5, "classes" : ["Infantry","Melee"], "templates" : [] };
|
||||
this.unitStat["MeleeCavalry"] = { "priority" : 1, "minSize" : 3, "targetSize" : 8 , "batchSize" : 3, "classes" : ["Cavalry","Ranged"], "templates" : [] };
|
||||
this.unitStat["RangedCavalry"] = { "priority" : 1, "minSize" : 3, "targetSize" : 8 , "batchSize" : 3, "classes" : ["Cavalry","Melee"], "templates" : [] };
|
||||
this.unitStat["Siege"] = { "priority" : 1, "minSize" : 0, "targetSize" : 2 , "batchSize" : 1, "classes" : ["Siege"], "templates" : [] };
|
||||
|
||||
var filter = Filters.and(Filters.byMetadata("plan",this.name),Filters.byOwner(gameState.player));
|
||||
this.unitCollection = gameState.getOwnEntities().filter(filter);
|
||||
this.unitCollection.registerUpdates();
|
||||
this.unitCollection.length;
|
||||
|
||||
this.unit = {};
|
||||
|
||||
// each array is [ratio, [associated classes], associated EntityColl, associated unitStat, name ]
|
||||
this.buildOrder = [];
|
||||
|
||||
// defining the entity collections. Will look for units I own, that are part of this plan.
|
||||
// Also defining the buildOrders.
|
||||
for (unitCat in this.unitStat) {
|
||||
var cat = unitCat;
|
||||
var Unit = this.unitStat[cat];
|
||||
|
||||
var filter = Filters.and(Filters.byClassesAnd(Unit["classes"]),Filters.and(Filters.byMetadata("plan",this.name),Filters.byOwner(gameState.player)));
|
||||
this.unit[cat] = gameState.getOwnEntities().filter(filter);
|
||||
this.unit[cat].registerUpdates();
|
||||
this.unit[cat].length;
|
||||
this.buildOrder.push([0, Unit["classes"], this.unit[cat], Unit, cat]);
|
||||
}
|
||||
/*if (gameState.getTimeElapsed() > 900000) // 15 minutes
|
||||
{
|
||||
|
||||
this.unitStat.Cavalry.Ranged["minSize"] = 5;
|
||||
this.unitStat.Cavalry.Melee["minSize"] = 5;
|
||||
this.unitStat.Infantry.Ranged["minSize"] = 10;
|
||||
this.unitStat.Infantry.Melee["minSize"] = 10;
|
||||
this.unitStat.Cavalry.Ranged["targetSize"] = 10;
|
||||
this.unitStat.Cavalry.Melee["targetSize"] = 10;
|
||||
this.unitStat.Infantry.Ranged["targetSize"] = 20;
|
||||
this.unitStat.Infantry.Melee["targetSize"] = 20;
|
||||
this.unitStat.Siege["targetSize"] = 5;
|
||||
this.unitStat.Siege["minSize"] = 2;
|
||||
|
||||
} else {
|
||||
this.maxPreparationTime = 180000;
|
||||
}*/
|
||||
// todo: REACTIVATE (in all caps)
|
||||
if (type === "harass_raid" && 0 == 1)
|
||||
{
|
||||
this.targetFinder = this.raidingTargetFinder;
|
||||
this.onArrivalReaction = "huntVillagers";
|
||||
|
||||
this.type = "harass_raid";
|
||||
// This is a Cavalry raid against villagers. A Cavalry Swordsman has a bonus against these. Only build these
|
||||
this.maxPreparationTime = 180000; // 3 minutes.
|
||||
if (gameState.playerData.civ === "hele") // hellenes have an ealry Cavalry Swordsman
|
||||
{
|
||||
this.unitCount.Cavalry.Melee = { "subCat" : ["Swordsman"] , "usesSubcategories" : true, "Swordsman" : undefined, "priority" : 1, "currentAmount" : 0, "minimalAmount" : 0, "preferedAmount" : 0 };
|
||||
this.unitCount.Cavalry.Melee.Swordsman = { "priority" : 1, "currentAmount" : 0, "minimalAmount" : 4, "preferedAmount" : 7, "fallback" : "abort" };
|
||||
} else {
|
||||
this.unitCount.Cavalry.Melee = { "subCat" : undefined , "usesSubcategories" : false, "priority" : 1, "currentAmount" : 0, "minimalAmount" : 4, "preferedAmount" : 7 };
|
||||
}
|
||||
this.unitCount.Cavalry.Ranged["minimalAmount"] = 0;
|
||||
this.unitCount.Cavalry.Ranged["preferedAmount"] = 0;
|
||||
this.unitCount.Infantry.Ranged["minimalAmount"] = 0;
|
||||
this.unitCount.Infantry.Ranged["preferedAmount"] = 0;
|
||||
this.unitCount.Infantry.Melee["minimalAmount"] = 0;
|
||||
this.unitCount.Infantry.Melee["preferedAmount"] = 0;
|
||||
this.unitCount.Siege["preferedAmount"] = 0;
|
||||
}
|
||||
this.anyNotMinimal = true; // used for support plans
|
||||
|
||||
// taking this so that fortresses won't crash it for now. TODO: change the rally point if it becomes invalid
|
||||
if(gameState.ai.pathsToMe.length > 1)
|
||||
var position = [(gameState.ai.pathsToMe[0][0]+gameState.ai.pathsToMe[1][0])/2.0,(gameState.ai.pathsToMe[0][1]+gameState.ai.pathsToMe[1][1])/2.0];
|
||||
else
|
||||
var position = [gameState.ai.pathsToMe[0][0],gameState.ai.pathsToMe[0][1]];
|
||||
|
||||
var CCs = gameState.getOwnEntities().filter(Filters.byClass("CivCentre"));
|
||||
var nearestCCArray = CCs.filterNearest(position, 1).toEntityArray();
|
||||
var CCpos = nearestCCArray[0].position();
|
||||
this.rallyPoint = [0,0];
|
||||
this.rallyPoint[0] = (position[0]*3 + CCpos[0]) / 4.0;
|
||||
this.rallyPoint[1] = (position[1]*3 + CCpos[1]) / 4.0;
|
||||
if (type == 'harass_raid')
|
||||
{
|
||||
this.rallyPoint[0] = (position[0]*3.9 + 0.1 * CCpos[0]) / 4.0;
|
||||
this.rallyPoint[1] = (position[1]*3.9 + 0.1 * CCpos[1]) / 4.0;
|
||||
}
|
||||
|
||||
// some variables for during the attack
|
||||
this.lastPosition = [0,0];
|
||||
this.position = [0,0];
|
||||
|
||||
this.threatList = []; // sounds so FBI
|
||||
this.tactics = undefined;
|
||||
|
||||
gameState.ai.queueManager.addQueue("plan_" + this.name, 100);
|
||||
this.queue = gameState.ai.queues["plan_" + this.name];
|
||||
|
||||
|
||||
this.assignUnits(gameState);
|
||||
|
||||
};
|
||||
|
||||
CityAttack.prototype.getName = function(){
|
||||
return this.name;
|
||||
};
|
||||
CityAttack.prototype.getType = function(){
|
||||
return this.type;
|
||||
};
|
||||
// Returns true if the attack can be executed at the current time
|
||||
// Basically his checks we have enough units.
|
||||
// We run a count of our units.
|
||||
CityAttack.prototype.canStart = function(gameState){
|
||||
for (unitCat in this.unitStat) {
|
||||
var Unit = this.unitStat[unitCat];
|
||||
if (this.unit[unitCat].length < Unit["minSize"])
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
|
||||
// TODO: check if our target is valid and a few other stuffs (good moment to attack?)
|
||||
};
|
||||
CityAttack.prototype.isStarted = function(){
|
||||
return !(this.state == "unexecuted");
|
||||
};
|
||||
|
||||
CityAttack.prototype.isPaused = function(){
|
||||
return this.paused;
|
||||
};
|
||||
CityAttack.prototype.setPaused = function(gameState, boolValue){
|
||||
if (!this.paused && boolValue === true) {
|
||||
this.pausingStart = gameState.getTimeElapsed();
|
||||
this.paused = true;
|
||||
debug ("Pausing attack plan " +this.name);
|
||||
} else if (this.paused && boolValue === false) {
|
||||
this.totalPausingTime += gameState.getTimeElapsed() - this.pausingStart;
|
||||
this.paused = false;
|
||||
debug ("Unpausing attack plan " +this.name);
|
||||
}
|
||||
};
|
||||
CityAttack.prototype.mustStart = function(gameState){
|
||||
var MaxReachedEverywhere = true;
|
||||
for (unitCat in this.unitStat) {
|
||||
var Unit = this.unitStat[unitCat];
|
||||
if (this.unit[unitCat].length < Unit["targetSize"])
|
||||
MaxReachedEverywhere = false;
|
||||
}
|
||||
if (MaxReachedEverywhere)
|
||||
return true;
|
||||
return (this.maxPreparationTime + this.timeOfPlanStart + this.totalPausingTime < gameState.getTimeElapsed());
|
||||
};
|
||||
|
||||
// Three returns possible: 1 is "keep going", 0 is "failed plan", 2 is "start"
|
||||
CityAttack.prototype.updatePreparation = function(gameState, militaryManager,events) {
|
||||
if (this.isPaused())
|
||||
return 0; // continue
|
||||
|
||||
Engine.ProfileStart("Update Preparation");
|
||||
|
||||
// let's sort by training advancement, ie 'current size / target size'
|
||||
this.buildOrder.sort(function (a,b) {
|
||||
a[0] = a[2].length/a[3]["targetSize"];
|
||||
b[0] = b[2].length/b[3]["targetSize"];
|
||||
return (a[0]) - (b[0]);
|
||||
});
|
||||
|
||||
this.assignUnits(gameState);
|
||||
|
||||
if ( (gameState.ai.turn + gameState.ai.player) % 40 == 0)
|
||||
this.AllToRallyPoint(gameState);
|
||||
|
||||
var canstart = this.canStart(gameState);
|
||||
|
||||
Engine.ProfileStart("Creating units and looking through events");
|
||||
|
||||
// gets the number in training of the same kind as the first one.
|
||||
var specialData = "Plan_"+this.name+"_"+this.buildOrder[0][4];
|
||||
var inTraining = gameState.countOwnQueuedEntitiesWithMetadata("special",specialData);
|
||||
if (this.queue.countTotalQueuedUnits() + inTraining + this.buildOrder[0][2].length < Math.min(15,this.buildOrder[0][3]["targetSize"]) ) {
|
||||
if (this.buildOrder[0][0] < 1 && this.queue.countTotalQueuedUnits() < 5) {
|
||||
|
||||
var template = militaryManager.findBestTrainableUnit(gameState, this.buildOrder[0][1], [ ["strength",1], ["cost",1] ] );
|
||||
//debug ("tried " + uneval(this.buildOrder[0][1]) +", and " + template);
|
||||
// HACK (TODO replace) : if we have no trainable template... Then we'll simply remove the buildOrder, effectively removing the unit from the plan.
|
||||
if (template === undefined) {
|
||||
debug ("Abandonning the idea of recruiting " + uneval(this.buildOrder[0][1]) + " as no recruitable template were found" );
|
||||
this.buildOrder.splice(0,1);
|
||||
} else {
|
||||
this.queue.addItem( new UnitTrainingPlan(gameState,template, { "role" : "attack", "plan" : this.name, "special" : specialData },this.buildOrder[0][3]["batchSize"] ) );
|
||||
}
|
||||
}
|
||||
}
|
||||
// can happen for now
|
||||
if (this.buildOrder.length === 0) {
|
||||
return 0; // will abort the plan, should return something else
|
||||
}
|
||||
|
||||
for (var key in events){
|
||||
var e = events[key];
|
||||
if (e.type === "Attacked" && e.msg){
|
||||
if (this.unitCollection.toIdArray().indexOf(e.msg.target) !== -1){
|
||||
var attacker = gameState.getEntityById(e.msg.attacker);
|
||||
if (attacker && attacker.position()) {
|
||||
this.unitCollection.attack(e.msg.attacker);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Engine.ProfileStop();
|
||||
// we count our units by triggering "canStart"
|
||||
// returns false if we can no longer have time and cannot start.
|
||||
// returns 0 if I must start and can't, returns 1 if I don't have to start, and returns 2 if I must start and can
|
||||
if (!this.mustStart(gameState))
|
||||
return 1;
|
||||
else if (canstart)
|
||||
return 2;
|
||||
else
|
||||
return 0;
|
||||
return 0;
|
||||
};
|
||||
CityAttack.prototype.assignUnits = function(gameState){
|
||||
var self = this;
|
||||
|
||||
// TODO: assign myself units that fit only, right now I'm getting anything.
|
||||
|
||||
/*
|
||||
// I'll take any unit set to "Defense" that has no subrole (ie is set to be a defensive unit, but has no particular task)
|
||||
// I assign it to myself, and then it's mine, the entity collection will detect it.
|
||||
var Defenders = gameState.getOwnEntitiesByRole("defence");
|
||||
Defenders.forEach(function(ent) {
|
||||
if (ent.getMetadata("subrole") == "idle" || !ent.getMetadata("subrole")) {
|
||||
ent.setMetadata("role", "attack");
|
||||
ent.setMetadata("plan", self.name);
|
||||
}
|
||||
});*/
|
||||
// Assign all no-roles that fit (after a plan aborts, for example).
|
||||
var NoRole = gameState.getOwnEntitiesByRole(undefined);
|
||||
NoRole.forEach(function(ent) {
|
||||
ent.setMetadata("role", "attack");
|
||||
ent.setMetadata("plan", self.name);
|
||||
});
|
||||
|
||||
};
|
||||
// this sends a unit by ID back to the "rally point"
|
||||
CityAttack.prototype.ToRallyPoint = function(gameState,id)
|
||||
{
|
||||
// Move back to nearest rallypoint
|
||||
gameState.getEntityById(id).move(this.rallyPoint[0],this.rallyPoint[1]);
|
||||
}
|
||||
// this sends all units back to the "rally point" by entity collections.
|
||||
CityAttack.prototype.AllToRallyPoint = function(gameState) {
|
||||
for (unitCat in this.unit) {
|
||||
this.unit[unitCat].move(this.rallyPoint[0],this.rallyPoint[1]);
|
||||
}
|
||||
}
|
||||
|
||||
// Default target finder aims for conquest critical targets
|
||||
CityAttack.prototype.defaultTargetFinder = function(gameState, militaryManager){
|
||||
var targets = undefined;
|
||||
|
||||
targets = militaryManager.enemyWatchers[this.targetPlayer].getEnemyBuildings("ConquestCritical");
|
||||
// If there's nothing, attack anything else that's less critical
|
||||
if (targets.length == 0) {
|
||||
targets = militaryManager.enemyWatchers[this.targetPlayer].getEnemyBuildings("Town");
|
||||
}
|
||||
if (targets.length == 0) {
|
||||
targets = militaryManager.enemyWatchers[this.targetPlayer].getEnemyBuildings("Village");
|
||||
}
|
||||
return targets;
|
||||
};
|
||||
|
||||
// tupdate
|
||||
CityAttack.prototype.raidingTargetFinder = function(gameState, militaryManager, Target){
|
||||
var targets = undefined;
|
||||
if (Target == "villager")
|
||||
{
|
||||
// let's aim for any resource dropsite. We assume villagers are in the neighborhood (note: the human player could certainly troll us... small (scouting) TODO here.)
|
||||
targets = gameState.entities.filter(function(ent) {
|
||||
return (ent.hasClass("Structure") && ent.resourceDropsiteTypes() !== undefined && !ent.hasClass("CivCentre") && ent.owner() === this.targetPlayer && ent.position());
|
||||
});
|
||||
if (targets.length == 0) {
|
||||
targets = gameState.entities.filter(function(ent) {
|
||||
return (ent.hasClass("CivCentre") && ent.resourceDropsiteTypes() !== undefined && ent.owner() === this.targetPlayer && ent.position());
|
||||
});
|
||||
}
|
||||
if (targets.length == 0) {
|
||||
// if we're here, it means they also don't have no CC... So I'll just take any building at this point.
|
||||
targets = gameState.entities.filter(function(ent) {
|
||||
return (ent.hasClass("Structure") && ent.owner() === this.targetPlayer && ent.position());
|
||||
});
|
||||
}
|
||||
return targets;
|
||||
} else {
|
||||
return this.defaultTargetFinder(gameState, militaryManager);
|
||||
}
|
||||
};
|
||||
|
||||
// Executes the attack plan, after this is executed the update function will be run every turn
|
||||
// If we're here, it's because we have in our IDlist enough units.
|
||||
// now the IDlist units are treated turn by turn
|
||||
CityAttack.prototype.StartAttack = function(gameState, militaryManager){
|
||||
|
||||
var targets = [];
|
||||
if (this.type === "harass_raid")
|
||||
targets = this.targetFinder(gameState, militaryManager, "villager");
|
||||
else
|
||||
{
|
||||
targets = this.targetFinder(gameState, militaryManager);
|
||||
|
||||
if (targets.length === 0){
|
||||
targets = this.defaultTargetFinder(gameState, militaryManager);
|
||||
}
|
||||
}
|
||||
|
||||
// If we have a target, move to it
|
||||
if (targets.length) {
|
||||
var curPos = this.unitCollection.getCentrePosition();
|
||||
|
||||
// pick a random target from the list
|
||||
var rand = Math.floor((Math.random()*targets.length));
|
||||
this.targetPos = undefined;
|
||||
var count = 0;
|
||||
while (!this.targetPos){
|
||||
var target = targets.toEntityArray()[rand];
|
||||
this.targetPos = target.position();
|
||||
count++;
|
||||
if (count > 1000){
|
||||
warn("No target with a valid position found");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Find possible distinct paths to the enemy
|
||||
var pathFinder = new PathFinder(gameState);
|
||||
var pathsToEnemy = pathFinder.getPaths(curPos, this.targetPos);
|
||||
if (! pathsToEnemy){
|
||||
pathsToEnemy = [[this.targetPos]];
|
||||
}
|
||||
this.path = [];
|
||||
|
||||
if (this.type !== "harass_raid")
|
||||
{
|
||||
var rand = Math.floor(Math.random() * pathsToEnemy.length);
|
||||
this.path = pathsToEnemy[rand];
|
||||
} else {
|
||||
this.path = pathsToEnemy[Math.min(2,pathsToEnemy.length-1)];
|
||||
}
|
||||
|
||||
this.unitCollection.forEach(function(ent) { ent.setMetadata("subrole", "attacking");});
|
||||
|
||||
// filtering by those that started to attack only
|
||||
var filter = Filters.byMetadata("subrole","attacking");
|
||||
this.unitCollection = this.unitCollection.filter(filter);
|
||||
//this.unitCollection.registerUpdates();
|
||||
//this.unitCollection.length;
|
||||
|
||||
for (unitCat in this.unitStat) {
|
||||
var cat = unitCat;
|
||||
this.unit[cat] = this.unit[cat].filter(filter);
|
||||
}
|
||||
|
||||
this.unitCollection.move(this.path[0][0], this.path[0][1]);
|
||||
debug ("Started to attack with the plan " + this.name);
|
||||
this.state = "walking";
|
||||
} else if (targets.length == 0 ) {
|
||||
gameState.ai.gameFinished = true;
|
||||
debug ("I do not have any target. So I'll just assume I won the game.");
|
||||
return true;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
// Runs every turn after the attack is executed
|
||||
CityAttack.prototype.update = function(gameState, militaryManager, events){
|
||||
Engine.ProfileStart("Update Attack");
|
||||
|
||||
// we're marching towards the target
|
||||
// Check for attacked units in our band.
|
||||
var bool_attacked = false;
|
||||
// raids don't care about attacks much
|
||||
|
||||
this.position = this.unitCollection.getCentrePosition();
|
||||
|
||||
var IDs = this.unitCollection.toIdArray();
|
||||
|
||||
// this actually doesn't do anything right now.
|
||||
if (this.state === "walking") {
|
||||
|
||||
var toProcess = {};
|
||||
var armyToProcess = {};
|
||||
// Let's check if any of our unit has been attacked. In case yes, we'll determine if we're simply off against an enemy army, a lone unit/builing
|
||||
// or if we reached the enemy base. Different plans may react differently.
|
||||
for (var key in events) {
|
||||
var e = events[key];
|
||||
if (e.type === "Attacked" && e.msg) {
|
||||
if (IDs.indexOf(e.msg.target) !== -1) {
|
||||
var attacker = gameState.getEntityById(e.msg.attacker);
|
||||
if (attacker && attacker.position() && attacker.hasClass("Unit") && attacker.owner() != 0) {
|
||||
toProcess[attacker.id()] = attacker;
|
||||
|
||||
var armyID = militaryManager.enemyWatchers[attacker.owner()].getArmyFromMember(attacker.id());
|
||||
armyToProcess[armyID[0]] = armyID[1];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// I don't process attacks if I'm in their base because I'll have already gone to "attacking" mode.
|
||||
// I'll process by army
|
||||
var total = 0;
|
||||
for (armyID in armyToProcess) {
|
||||
total += armyToProcess[armyID].length;
|
||||
// TODO: if it's a big army, we may want to refer the scouting/defense manager
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
|
||||
}&& this.type !== "harass_raid"){ // walking toward the target
|
||||
var sumAttackerPos = [0,0];
|
||||
var numAttackers = 0;
|
||||
// let's check if one of our unit is not under attack, by any chance.
|
||||
for (var key in events){
|
||||
var e = events[key];
|
||||
if (e.type === "Attacked" && e.msg){
|
||||
if (this.unitCollection.toIdArray().indexOf(e.msg.target) !== -1){
|
||||
var attacker = HeadQuarters.entity(e.msg.attacker);
|
||||
if (attacker && attacker.position()){
|
||||
sumAttackerPos[0] += attacker.position()[0];
|
||||
sumAttackerPos[1] += attacker.position()[1];
|
||||
numAttackers += 1;
|
||||
bool_attacked = true;
|
||||
// todo: differentiate depending on attacker type... If it's a ship, let's not do anythin, a building, depends on the attack type/
|
||||
if (this.threatList.indexOf(e.msg.attacker) === -1)
|
||||
{
|
||||
var enemySoldiers = HeadQuarters.getEnemySoldiers().toEntityArray();
|
||||
for (j in enemySoldiers)
|
||||
{
|
||||
var enemy = enemySoldiers[j];
|
||||
if (enemy.position() === undefined) // likely garrisoned
|
||||
continue;
|
||||
if (inRange(enemy.position(), attacker.position(), 1000) && this.threatList.indexOf(enemy.id()) === -1)
|
||||
this.threatList.push(enemy.id());
|
||||
}
|
||||
this.threatList.push(e.msg.attacker);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (bool_attacked > 0){
|
||||
var avgAttackerPos = [sumAttackerPos[0]/numAttackers, sumAttackerPos[1]/numAttackers];
|
||||
units.move(avgAttackerPos[0], avgAttackerPos[1]); // let's run towards it.
|
||||
this.tactics = new Tactics(gameState,HeadQuarters, this.idList,this.threatList,true);
|
||||
this.state = "attacking_threat";
|
||||
}
|
||||
}else if (this.state === "attacking_threat"){
|
||||
this.tactics.eventMetadataCleanup(events,HeadQuarters);
|
||||
var removeList = this.tactics.removeTheirDeads(HeadQuarters);
|
||||
this.tactics.removeMyDeads(HeadQuarters);
|
||||
for (var i in removeList){
|
||||
this.threatList.splice(this.threatList.indexOf(removeList[i]),1);
|
||||
}
|
||||
if (this.threatList.length <= 0)
|
||||
{
|
||||
this.tactics.disband(HeadQuarters,events);
|
||||
this.tactics = undefined;
|
||||
this.state = "walking";
|
||||
units.move(this.path[0][0], this.path[0][1]);
|
||||
}else
|
||||
{
|
||||
this.tactics.reassignAttacks(HeadQuarters);
|
||||
}
|
||||
}*/
|
||||
}
|
||||
if (this.state === "walking"){
|
||||
if (SquareVectorDistance(this.unitCollection.getCentrePosition(), this.path[0]) < 400){
|
||||
this.path.shift();
|
||||
if (this.path.length > 0){
|
||||
this.unitCollection.move(this.path[0][0], this.path[0][1]);
|
||||
} else {
|
||||
debug ("Attack Plan " +this.type +" " +this.name +" has arrived to destination.");
|
||||
// we must assume we've arrived at the end of the trail.
|
||||
this.state = "arrived";
|
||||
}
|
||||
}
|
||||
if (this.position == this.lastPosition)
|
||||
this.unitCollection.move(this.path[0][0], this.path[0][1]);
|
||||
}
|
||||
// todo: re-implement raiding
|
||||
/*
|
||||
if (this.state === "arrived"){
|
||||
// let's proceed on with whatever happens now.
|
||||
// There's a ton of TODOs on this part.
|
||||
if (this.onArrivalReaction == "huntVillagers")
|
||||
{
|
||||
// let's get any villager and target them with a tactics manager
|
||||
var enemyCitizens = gameState.entities.filter(function(ent) {
|
||||
return (gameState.isEntityEnemy(ent) && ent.hasClass("Support") && ent.owner() !== 0 && ent.position());
|
||||
});
|
||||
var targetList = [];
|
||||
enemyCitizens.forEach( function (enemy) {
|
||||
if (inRange(enemy.position(), units.getCentrePosition(), 2500) && targetList.indexOf(enemy.id()) === -1)
|
||||
targetList.push(enemy.id());
|
||||
});
|
||||
if (targetList.length > 0)
|
||||
{
|
||||
this.tactics = new Tactics(gameState,HeadQuarters, this.idList,targetList);
|
||||
this.state = "huntVillagers";
|
||||
} else {
|
||||
this.state = "";
|
||||
}
|
||||
}
|
||||
}
|
||||
if (this.state === "huntVillagers")
|
||||
{
|
||||
this.tactics.eventMetadataCleanup(events,HeadQuarters);
|
||||
this.tactics.removeTheirDeads(HeadQuarters);
|
||||
this.tactics.removeMyDeads(HeadQuarters);
|
||||
if (this.tactics.isBattleOver())
|
||||
{
|
||||
this.tactics.disband(HeadQuarters,events);
|
||||
this.tactics = undefined;
|
||||
this.state = "";
|
||||
return 0; // assume over
|
||||
} else
|
||||
this.tactics.reassignAttacks(HeadQuarters);
|
||||
}*/
|
||||
this.lastPosition = this.position;
|
||||
Engine.ProfileStop();
|
||||
return this.unitCollection.length;
|
||||
};
|
||||
CityAttack.prototype.totalCountUnits = function(gameState){
|
||||
var totalcount = 0;
|
||||
for (i in this.idList)
|
||||
{
|
||||
totalcount++;
|
||||
}
|
||||
return totalcount;
|
||||
};
|
||||
// reset any units
|
||||
CityAttack.prototype.Abort = function(gameState){
|
||||
this.unitCollection.forEach(function(ent) {
|
||||
ent.setMetadata("role",undefined);
|
||||
ent.setMetadata("subrole",undefined);
|
||||
ent.setMetadata("plan",undefined);
|
||||
});
|
||||
for (unitCat in this.unitStat)
|
||||
delete this.unit[unitCat];
|
||||
delete this.unitCollection;
|
||||
gameState.ai.queueManager.removeQueue("plan_" + this.name);
|
||||
};
|
64
binaries/data/mods/public/simulation/ai/qbot-wc/config.js
Normal file
64
binaries/data/mods/public/simulation/ai/qbot-wc/config.js
Normal file
@ -0,0 +1,64 @@
|
||||
var baseConfig = {
|
||||
"attack" : {
|
||||
"minAttackSize" : 20, // attackMoveToLocation
|
||||
"maxAttackSize" : 60, // attackMoveToLocation
|
||||
"enemyRatio" : 1.5, // attackMoveToLocation
|
||||
"groupSize" : 10 // military
|
||||
},
|
||||
|
||||
// defence
|
||||
"defence" : {
|
||||
"acquireDistance" : 220,
|
||||
"releaseDistance" : 250,
|
||||
"groupRadius" : 20,
|
||||
"groupBreakRadius" : 40,
|
||||
"groupMergeRadius" : 10,
|
||||
"defenderRatio" : 2
|
||||
},
|
||||
|
||||
// military
|
||||
"buildings" : {
|
||||
"moderate" : {
|
||||
"default" : [ "structures/{civ}_barracks" ]
|
||||
},
|
||||
"advanced" : {
|
||||
"hele" : [ "structures/{civ}_gymnasion", "structures/{civ}_fortress" ],
|
||||
"athen" : [ "structures/{civ}_gymnasion", "structures/{civ}_fortress" ],
|
||||
"spart" : [ "structures/{civ}_syssiton", "structures/{civ}_fortress" ],
|
||||
"mace" : [ "structures/{civ}_fortress" ],
|
||||
"cart" : [ "structures/{civ}_fortress", "structures/{civ}_embassy_celtic",
|
||||
"structures/{civ}_embassy_iberian", "structures/{civ}_embassy_italiote" ],
|
||||
"celt" : [ "structures/{civ}_kennel", "structures/{civ}_fortress_b", "structures/{civ}_fortress_g" ],
|
||||
"iber" : [ "structures/{civ}_fortress" ],
|
||||
"pers" : [ "structures/{civ}_fortress", "structures/{civ}_stables", "structures/{civ}_apadana" ],
|
||||
"rome" : [ "structures/{civ}_army_camp", "structures/{civ}_fortress" ],
|
||||
"maur" : [ "structures/{civ}_elephant_stables", "structures/{civ}_fortress" ]
|
||||
},
|
||||
"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" : 500,
|
||||
"citizenSoldier" : 100,
|
||||
"villager" : 150,
|
||||
"economicBuilding" : 30,
|
||||
"field" : 20,
|
||||
"advancedSoldier" : 30,
|
||||
"siege" : 10,
|
||||
"militaryBuilding" : 50,
|
||||
"defenceBuilding" : 17,
|
||||
"civilCentre" : 1000
|
||||
},
|
||||
|
||||
"debug" : true
|
||||
};
|
||||
|
||||
var Config = {
|
||||
"debug": true
|
||||
};
|
||||
|
||||
Config.__proto__ = baseConfig;
|
@ -0,0 +1,5 @@
|
||||
{
|
||||
"name": "qBot-xp\n(experimental)",
|
||||
"description": "Improvements over qBot by Wraitii. Still experimental(bugs possible).\nThis bot may be harder to defeat than the regular qBot. Please report any problems on the Wildfire forums.",
|
||||
"constructor": "QBotAI"
|
||||
}
|
447
binaries/data/mods/public/simulation/ai/qbot-wc/defence.js
Executable file
447
binaries/data/mods/public/simulation/ai/qbot-wc/defence.js
Executable file
@ -0,0 +1,447 @@
|
||||
// directly imported from Marilyn, with slight modifications to work with qBot.
|
||||
|
||||
function Defence(){
|
||||
this.DefenceRatio = 1.35; // How many defenders we want per attacker. Need to balance fewer losses vs. lost economy
|
||||
|
||||
this.totalAttackNb = 0; // used for attack IDs
|
||||
this.attacks = [];
|
||||
this.toKill = [];
|
||||
this.defenders = {};
|
||||
|
||||
// keeps a list of targeted enemy at instant T
|
||||
this.attackerCache = {};
|
||||
this.listOfEnemies = {};
|
||||
|
||||
// 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.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
|
||||
// 6 (or more): no danger whatsoever detected
|
||||
// 5: local zones of danger (ie a tower somewhere, things like that)
|
||||
// 4: a few enemy units inbound, like a scout or something. (local danger). Usually seen as the last level before a true "attack"
|
||||
// 3: reasonnably sized enemy army inbound, local danger
|
||||
// 2: well sized enemy army inbound, general danger
|
||||
// 1: Sizable enemy army inside of my base, general danger.
|
||||
|
||||
|
||||
Defence.prototype.update = function(gameState, events, militaryManager){
|
||||
|
||||
Engine.ProfileStart("Defence Manager");
|
||||
|
||||
// a litlle cache-ing
|
||||
if (!this.idleDefs) {
|
||||
var filter = Filters.and(Filters.byMetadata("role", "defence"), Filters.isIdle());
|
||||
this.idleDefs = gameState.getOwnEntities().filter(filter);
|
||||
this.idleDefs.registerUpdates();
|
||||
}
|
||||
this.myBuildings = gameState.getOwnEntities().filter(Filters.byClass("Structure")).toEntityArray();
|
||||
this.myUnits = gameState.getOwnEntities().filter(Filters.byClass("Unit"));
|
||||
|
||||
this.territoryMap = Map.createTerritoryMap(gameState); // used by many func
|
||||
|
||||
// First step: we deal with enemy armies, those are the highest priority.
|
||||
this.defendFromEnemyArmies(gameState, events, militaryManager);
|
||||
|
||||
// second step: we loop through messages, and sort things as needed (dangerous buildings, attack by animals, ships, lone units, whatever).
|
||||
// TODO
|
||||
this.MessageProcess(gameState,events,militaryManager);
|
||||
|
||||
this.DealWithWantedUnits(gameState,events,militaryManager);
|
||||
|
||||
// putting unneeded units at rest
|
||||
this.idleDefs.forEach(function(ent) {
|
||||
ent.setMetadata("role", ent.getMetadata("formerrole") );
|
||||
ent.setMetadata("subrole", undefined);
|
||||
});
|
||||
|
||||
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 (i in armies) {
|
||||
var pos = armies[i].getCentrePosition();
|
||||
if (+this.territoryMap.point(armies[i].getCentrePosition()) - 64 === +gameState.player) {
|
||||
stillDangerousArmies[i] = armies[i];
|
||||
continue;
|
||||
}
|
||||
for (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 (i in armies) {
|
||||
if (armies[i].getCentrePosition() && +this.territoryMap.point(armies[i].getCentrePosition()) - 64 === +gameState.player) {
|
||||
DangerousArmies[i] = armies[i];
|
||||
}
|
||||
}
|
||||
return DangerousArmies;
|
||||
}
|
||||
// This deals with incoming enemy armies, setting the defcon if needed. It will take new soldiers, and assign them to attack
|
||||
// it's still a fair share of dumb, so TODO improve
|
||||
Defence.prototype.defendFromEnemyArmies = function(gameState, events, militaryManager) {
|
||||
|
||||
// The enemy Watchers keep a list of armies. This class here tells them if an army is dangerous, and they manage the merging/splitting/disbanding.
|
||||
// With this system, we can get any dangerous armies. Thus, we can know where the danger is, and react.
|
||||
// So Defence deals with attacks from animals too (which aren't watched).
|
||||
// The attackrs here are dealt with on a per unit basis.
|
||||
// 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 dangerArmies = {};
|
||||
this.enemyUnits = {};
|
||||
|
||||
// for now armies are never seen as "no longer dangerous"... TODO
|
||||
for (enemyID in militaryManager.enemyWatchers) {
|
||||
this.enemyUnits[enemyID] = militaryManager.enemyWatchers[enemyID].getAllEnemySoldiers();
|
||||
|
||||
var dangerousArmies = militaryManager.enemyWatchers[enemyID].getDangerousArmies();
|
||||
// we check if all the dangerous armies are still dangerous.
|
||||
var newDangerArmies = this.reevaluateDangerousArmies(gameState,dangerousArmies);
|
||||
|
||||
var safeArmies = militaryManager.enemyWatchers[enemyID].getSafeArmies();
|
||||
// we check not dangerous armies, to see if they suddenly became dangerous
|
||||
var unsafeArmies = this.evaluateArmies(gameState,safeArmies);
|
||||
for (i in unsafeArmies)
|
||||
newDangerArmies[i] = unsafeArmies[i];
|
||||
|
||||
// and any dangerous armies we push in "dangerArmies"
|
||||
militaryManager.enemyWatchers[enemyID].resetDangerousArmies();
|
||||
for (o in newDangerArmies)
|
||||
militaryManager.enemyWatchers[enemyID].setAsDangerous(o);
|
||||
|
||||
for (i in newDangerArmies)
|
||||
dangerArmies[i] = newDangerArmies[i];
|
||||
}
|
||||
|
||||
var self = this;
|
||||
|
||||
var nbOfAttackers = 0;
|
||||
|
||||
// clean up before adding new units (slight speeding up, since new units can't already be dead)
|
||||
for (i in this.listOfEnemies) {
|
||||
if (this.listOfEnemies[i].length === 0) {
|
||||
// if we had defined the attackerCache, ie if we had tried to attack this unit.
|
||||
if (this.attackerCache[i] !== undefined) {
|
||||
this.attackerCache[i].forEach(function(ent) { ent.stopMoving(); });
|
||||
delete this.attackerCache[i];
|
||||
}
|
||||
delete this.listOfEnemies[i];
|
||||
} else {
|
||||
var unit = this.listOfEnemies[i].toEntityArray()[0];
|
||||
var enemyWatcher = militaryManager.enemyWatchers[unit.owner()];
|
||||
if (enemyWatcher.isPartOfDangerousArmy(unit.id())) {
|
||||
nbOfAttackers++;
|
||||
} else {
|
||||
// if we had defined the attackerCache, ie if we had tried to attack this unit.
|
||||
if (this.attackerCache[unit.id()] != undefined) {
|
||||
this.attackerCache[unit.id()].forEach(function(ent) { ent.stopMoving(); });
|
||||
delete this.attackerCache[unit.id()];
|
||||
}
|
||||
delete this.listOfEnemies[unit.id()];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// okay so now, for every dangerous armies, we loop.
|
||||
for (armyID in dangerArmies) {
|
||||
// looping through army units
|
||||
dangerArmies[armyID].forEach(function(ent) {
|
||||
// do we have already registered an entityCollection for it?
|
||||
if (self.listOfEnemies[ent.id()] === undefined) {
|
||||
// no, we register a new entity collection in listOfEnemies, listing exactly one unit as long as it remains alive and owned by my enemy.
|
||||
// can't be bothered to recode everything
|
||||
var owner = ent.owner();
|
||||
var filter = Filters.and(Filters.byOwner(owner),Filters.byID(ent.id()));
|
||||
self.listOfEnemies[ent.id()] = self.enemyUnits[owner].filter(filter);
|
||||
self.listOfEnemies[ent.id()].registerUpdates();
|
||||
self.listOfEnemies[ent.id()].length;
|
||||
|
||||
// let's also register an entity collection for units attacking this unit (so we can new if it's attacked)
|
||||
filter = Filters.and(Filters.byOwner(gameState.player),Filters.byTargetedEntity(ent.id()));
|
||||
self.attackerCache[ent.id()] = self.myUnits.filter(filter);
|
||||
self.attackerCache[ent.id()].registerUpdates();
|
||||
nbOfAttackers++;
|
||||
}
|
||||
});
|
||||
}
|
||||
// Reordering attack because the pathfinder is for now not dynamically updated
|
||||
for (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 (nbOfAttackers === 0) {
|
||||
militaryManager.unpauseAllPlans(gameState);
|
||||
return;
|
||||
}
|
||||
// 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 (nbOfAttackers === 0) {
|
||||
return;
|
||||
} else if (nbOfAttackers < 5){
|
||||
gameState.upDefcon(4); // few local units
|
||||
} else if (nbOfAttackers >= 5){
|
||||
gameState.upDefcon(3); // local attack, dangerous but not hugely threatening for my survival
|
||||
}
|
||||
|
||||
if (this.idleDefs.length < nbOfAttackers) {
|
||||
gameState.upDefcon(2); // general danger
|
||||
}
|
||||
*/
|
||||
|
||||
// if here, there are known enemy attackers.
|
||||
this.idleDefs.forEach(function(ent) {
|
||||
// okaaay we attack
|
||||
for (o in self.listOfEnemies) {
|
||||
if (self.attackerCache[o].length === 0) {
|
||||
ent.setMetadata("subrole", "defending");
|
||||
ent.attack(+o);
|
||||
nbOfAttackers--;
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// okay so if we lacked units with the Defence role that could be used, we'll sort through those from attack plans, pausing the plans if needed.
|
||||
var newSoldiers = gameState.getOwnEntitiesByRole("attack");
|
||||
newSoldiers.forEach(function(ent) {
|
||||
if (ent.getMetadata("subrole","attacking"))
|
||||
return;
|
||||
// okaaay we attack
|
||||
for (o in self.listOfEnemies) {
|
||||
if (self.attackerCache[o].length === 0) {
|
||||
if (ent.getMetadata("plan") != undefined)
|
||||
militaryManager.pausePlan(gameState,ent.getMetadata("plan"));
|
||||
ent.setMetadata("formerrole", "attack");
|
||||
ent.setMetadata("role","defence");
|
||||
ent.setMetadata("subrole","defending");
|
||||
ent.attack(+o);
|
||||
nbOfAttackers--;
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// still some undealt with attackers, launch the citizen soldiers
|
||||
if (nbOfAttackers > 0) {
|
||||
var newSoldiers = gameState.getOwnEntitiesByRole("worker");
|
||||
newSoldiers.forEach(function(ent) {
|
||||
// If we're not female, we attack
|
||||
if (ent.hasClass("CitizenSoldier"))
|
||||
for (o in self.listOfEnemies) {
|
||||
if (self.attackerCache[o].length === 0) {
|
||||
ent.setMetadata("formerrole", "worker");
|
||||
ent.setMetadata("role","defence");
|
||||
ent.setMetadata("subrole","defending");
|
||||
ent.attack(+o);
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
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) {
|
||||
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
|
||||
if (attacker !== 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;
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
// anyway we'll register the animal as dangerous, and attack it.
|
||||
var filter = Filters.byID(attacker.id());
|
||||
this.listOfWantedUnits[attacker.id()] = gameState.getEntities().filter(filter);
|
||||
this.listOfWantedUnits[attacker.id()].registerUpdates();
|
||||
this.listOfWantedUnits[attacker.id()].length;
|
||||
filter = Filters.and(Filters.byOwner(gameState.player),Filters.byTargetedEntity(attacker.id()));
|
||||
this.WantedUnitsAttacker[attacker.id()] = this.myUnits.filter(filter);
|
||||
this.WantedUnitsAttacker[attacker.id()].registerUpdates();
|
||||
this.WantedUnitsAttacker[attacker.id()].length;
|
||||
} else if (territory != attacker.owner()) { // preliminary check: attacks in enemy territory are not counted as attacks
|
||||
// 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.
|
||||
} 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. We'll ask the enemy manager if it's part of a big army, in which case we'll list it as dangerous (so it'll be treated next turn by the other manager)
|
||||
// If it's not part of a big army, depending on our priority we may want to kill it (using the same things as animals for that)
|
||||
// TODO (perhaps not any more, but let's mark it anyway)
|
||||
var army = militaryManager.enemyWatchers[attacker.owner()].getArmyFromMember(attacker.id());
|
||||
if (army[1].length > 5) {
|
||||
militaryManager.enemyWatchers[attacker.owner()].setAsDangerous(army[0]);
|
||||
} else if (!militaryManager.enemyWatchers[attacker.owner()].isDangerous(army[0])) {
|
||||
// we register this unit as wanted, TODO register the whole army
|
||||
// another function will deal with it.
|
||||
var filter = Filters.and(Filters.byOwner(attacker.owner()),Filters.byID(attacker.id()));
|
||||
this.listOfWantedUnits[attacker.id()] = this.enemyUnits[attacker.owner()].filter(filter);
|
||||
this.listOfWantedUnits[attacker.id()].registerUpdates();
|
||||
this.listOfWantedUnits[attacker.id()].length;
|
||||
filter = Filters.and(Filters.byOwner(gameState.player),Filters.byTargetedEntity(attacker.id()));
|
||||
this.WantedUnitsAttacker[attacker.id()] = this.myUnits.filter(filter);
|
||||
this.WantedUnitsAttacker[attacker.id()].registerUpdates();
|
||||
this.WantedUnitsAttacker[attacker.id()].length;
|
||||
}
|
||||
if (ourUnit && ourUnit.hasClass("Unit") && !ourUnit.getMetadata("role","attack")) {
|
||||
if (ourUnit.hasClass("Support")) {
|
||||
// TODO: it's a villager. Garrison it.
|
||||
// TODO: make other neighboring villagers garrison
|
||||
|
||||
// Right now we'll flee from the attacker.
|
||||
ourUnit.flee(attacker);
|
||||
} else {
|
||||
// It's a soldier. Right now we'll retaliate
|
||||
// TODO: check for stronger units against this type, check for fleeing options, etc.
|
||||
ourUnit.attack(e.msg.attacker);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
// At most, this will put defcon to 5
|
||||
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 (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 two enemies at once.
|
||||
if (nbOfDealtWith >= 2)
|
||||
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 < 2 && nbOfAttackers > 0 && ent.getMetadata("plan") == undefined)
|
||||
for (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("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.upDefcon(5);
|
||||
|
||||
var newSoldiers = gameState.getOwnEntitiesByRole("worker");
|
||||
newSoldiers.forEach(function(ent) {
|
||||
// If we're not female, we attack
|
||||
if (ent.hasClass("CitizenSoldier"))
|
||||
if (nbOfDealtWith < 2 && nbOfAttackers > 0)
|
||||
for (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("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;
|
||||
}
|
628
binaries/data/mods/public/simulation/ai/qbot-wc/economy.js
Normal file
628
binaries/data/mods/public/simulation/ai/qbot-wc/economy.js
Normal file
@ -0,0 +1,628 @@
|
||||
var EconomyManager = function() {
|
||||
this.targetNumBuilders = 3; // number of workers we want building stuff
|
||||
this.targetNumFields = 3;
|
||||
|
||||
this.resourceMaps = {}; // Contains maps showing the density of wood, stone and metal
|
||||
|
||||
this.setCount = 0; //stops villagers being reassigned to other resources too frequently, count a set number of
|
||||
//turns before trying to reassign them.
|
||||
|
||||
this.femaleRatio = 0.4;
|
||||
|
||||
this.dropsiteNumbers = {wood: 2, stone: 1, metal: 1};
|
||||
};
|
||||
// More initialisation for stuff that needs the gameState
|
||||
EconomyManager.prototype.init = function(gameState){
|
||||
this.targetNumWorkers = Math.max(Math.floor(gameState.getPopulationMax()/2.5), 1);
|
||||
};
|
||||
|
||||
// okay, so here we'll create both females and male workers.
|
||||
// We'll try to keep close to the "ratio" defined atop.
|
||||
// qBot picks the best citizen soldier available: the cheapest and the fastest walker
|
||||
// some civs such as Macedonia have 2 kinds of citizen soldiers: phalanx that are slow
|
||||
// (speed:6) and peltasts that are very fast (speed: 11). Here, qBot will choose the peltast
|
||||
// resulting in faster resource gathering.
|
||||
// I'll also avoid creating citizen soldiers in the beginning because it's slower.
|
||||
EconomyManager.prototype.trainMoreWorkers = function(gameState, queues) {
|
||||
// Count the workers in the world and in progress
|
||||
var numFemales = gameState.countEntitiesAndQueuedByType(gameState.applyCiv("units/{civ}_support_female_citizen"));
|
||||
numFemales += queues.villager.countTotalQueuedUnits();
|
||||
var numWorkers = gameState.countOwnEntitiesAndQueuedWithRole("worker");
|
||||
numWorkers += queues.citizenSoldier.countTotalQueuedUnits();
|
||||
var numTotal = numWorkers + queues.villager.countTotalQueuedUnits() + queues.citizenSoldier.countTotalQueuedUnits();
|
||||
|
||||
// If we have too few, train more
|
||||
if (numTotal < this.targetNumWorkers && (queues.villager.countTotalQueuedUnits() < 10 || queues.citizenSoldier.countTotalQueuedUnits() < 10) ) {
|
||||
var template = "units/{civ}_support_female_citizen";
|
||||
var size = 1;
|
||||
if (numFemales/numWorkers > this.femaleRatio && gameState.getTimeElapsed() > 60*1000) {
|
||||
template = this.findBestTrainableUnit(gameState, ["CitizenSoldier", "Infantry"], [ ["cost",1], ["speed",0.5]]);
|
||||
size = 5;
|
||||
if (!template) {
|
||||
template = "units/{civ}_support_female_citizen";
|
||||
size = 1;
|
||||
}
|
||||
}
|
||||
if (size == 5)
|
||||
queues.citizenSoldier.addItem(new UnitTrainingPlan(gameState, template, { "role" : "worker" },size ));
|
||||
else
|
||||
queues.villager.addItem(new UnitTrainingPlan(gameState, template, { "role" : "worker" },size ));
|
||||
}
|
||||
};
|
||||
// picks the best template based on parameters and classes
|
||||
EconomyManager.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 (i in parameters) {
|
||||
var param = parameters[i];
|
||||
|
||||
if (param[0] == "base") {
|
||||
aTopParam = param[1];
|
||||
bTopParam = param[1];
|
||||
}
|
||||
if (param[0] == "strength") {
|
||||
aTopParam += a[1].getMaxStrength() * param[1];
|
||||
bTopParam += b[1].getMaxStrength() * 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];
|
||||
}
|
||||
}
|
||||
return -(aTopParam/(aDivParam+1)) + (bTopParam/(bDivParam+1));
|
||||
});
|
||||
return units[0][0];
|
||||
};
|
||||
|
||||
|
||||
|
||||
// Pick the resource which most needs another worker
|
||||
EconomyManager.prototype.pickMostNeededResources = function(gameState) {
|
||||
|
||||
var self = this;
|
||||
|
||||
// Find what resource type we're most in need of
|
||||
if (!gameState.turnCache["gather-weights-calculated"]){
|
||||
this.gatherWeights = gameState.ai.queueManager.futureNeeds(gameState);
|
||||
gameState.turnCache["gather-weights-calculated"] = true;
|
||||
}
|
||||
|
||||
var numGatherers = {};
|
||||
for ( var type in this.gatherWeights){
|
||||
numGatherers[type] = gameState.updatingCollection("workers-gathering-" + type,
|
||||
Filters.byMetadata("gather-type", type), gameState.getOwnEntitiesByRole("worker")).length;
|
||||
}
|
||||
|
||||
var types = Object.keys(this.gatherWeights);
|
||||
types.sort(function(a, b) {
|
||||
// Prefer fewer gatherers (divided by weight)
|
||||
var va = numGatherers[a] / (self.gatherWeights[a]+1);
|
||||
var vb = numGatherers[b] / (self.gatherWeights[b]+1);
|
||||
return va-vb;
|
||||
});
|
||||
|
||||
return types;
|
||||
};
|
||||
|
||||
EconomyManager.prototype.reassignRolelessUnits = function(gameState) {
|
||||
//TODO: Move this out of the economic section
|
||||
var roleless = gameState.getOwnEntitiesByRole(undefined);
|
||||
|
||||
roleless.forEach(function(ent) {
|
||||
if (ent.hasClass("Worker")){
|
||||
ent.setMetadata("role", "worker");
|
||||
}else if(ent.hasClass("CitizenSoldier") || ent.hasClass("Champion")){
|
||||
ent.setMetadata("role", "soldier");
|
||||
}else{
|
||||
ent.setMetadata("role", "unknown");
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// If the numbers of workers on the resources is unbalanced then set some of workers to idle so
|
||||
// they can be reassigned by reassignIdleWorkers.
|
||||
EconomyManager.prototype.setWorkersIdleByPriority = function(gameState){
|
||||
this.gatherWeights = gameState.ai.queueManager.futureNeeds(gameState);
|
||||
|
||||
var numGatherers = {};
|
||||
var totalGatherers = 0;
|
||||
var totalWeight = 0;
|
||||
for ( var type in this.gatherWeights){
|
||||
numGatherers[type] = 0;
|
||||
totalWeight += this.gatherWeights[type];
|
||||
}
|
||||
|
||||
gameState.getOwnEntitiesByRole("worker").forEach(function(ent) {
|
||||
if (ent.getMetadata("subrole") === "gatherer"){
|
||||
numGatherers[ent.getMetadata("gather-type")] += 1;
|
||||
totalGatherers += 1;
|
||||
}
|
||||
});
|
||||
|
||||
for ( var type in this.gatherWeights){
|
||||
var allocation = Math.floor(totalGatherers * (this.gatherWeights[type]/totalWeight));
|
||||
if (allocation < numGatherers[type]){
|
||||
var numToTake = numGatherers[type] - allocation;
|
||||
gameState.getOwnEntitiesByRole("worker").forEach(function(ent) {
|
||||
if (ent.getMetadata("subrole") === "gatherer" && ent.getMetadata("gather-type") === type && numToTake > 0){
|
||||
ent.setMetadata("subrole", "idle");
|
||||
numToTake -= 1;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
EconomyManager.prototype.reassignIdleWorkers = function(gameState) {
|
||||
|
||||
var self = this;
|
||||
|
||||
// Search for idle workers, and tell them to gather resources based on demand
|
||||
var filter = Filters.or(Filters.isIdle(), Filters.byMetadata("subrole", "idle"));
|
||||
var idleWorkers = gameState.updatingCollection("idle-workers", filter, gameState.getOwnEntitiesByRole("worker"));
|
||||
|
||||
if (idleWorkers.length) {
|
||||
var resourceSupplies;
|
||||
|
||||
idleWorkers.forEach(function(ent) {
|
||||
// Check that the worker isn't garrisoned
|
||||
if (ent.position() === undefined){
|
||||
return;
|
||||
}
|
||||
|
||||
var types = self.pickMostNeededResources(gameState);
|
||||
|
||||
ent.setMetadata("subrole", "gatherer");
|
||||
ent.setMetadata("gather-type", types[0]);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
EconomyManager.prototype.workersBySubrole = function(gameState, subrole) {
|
||||
var workers = gameState.getOwnEntitiesByRole("worker");
|
||||
return gameState.updatingCollection("subrole-" + subrole, Filters.byMetadata("subrole", subrole), workers);
|
||||
};
|
||||
|
||||
EconomyManager.prototype.assignToFoundations = function(gameState) {
|
||||
// If we have some foundations, and we don't have enough
|
||||
// builder-workers,
|
||||
// try reassigning some other workers who are nearby
|
||||
|
||||
var foundations = gameState.getOwnFoundations();
|
||||
|
||||
// Check if nothing to build
|
||||
if (!foundations.length){
|
||||
return;
|
||||
}
|
||||
var workers = gameState.getOwnEntitiesByRole("worker");
|
||||
|
||||
var builderWorkers = this.workersBySubrole(gameState, "builder");
|
||||
|
||||
// Check if enough builders
|
||||
var extraNeeded = this.targetNumBuilders*foundations.length - builderWorkers.length;
|
||||
if (extraNeeded <= 0){
|
||||
return;
|
||||
}
|
||||
|
||||
// Pick non-builders who are closest to the first foundation,
|
||||
// and tell them to start building it
|
||||
|
||||
var target = foundations.toEntityArray()[0];
|
||||
|
||||
var nonBuilderWorkers = workers.filter(function(ent) {
|
||||
// check position so garrisoned units aren't tasked
|
||||
return (ent.getMetadata("subrole") !== "builder" && ent.position() !== undefined);
|
||||
});
|
||||
|
||||
var nearestNonBuilders = nonBuilderWorkers.filterNearest(target.position(), extraNeeded);
|
||||
|
||||
// Order each builder individually, not as a formation
|
||||
nearestNonBuilders.forEach(function(ent) {
|
||||
ent.setMetadata("subrole", "builder");
|
||||
ent.setMetadata("target-foundation", target);
|
||||
});
|
||||
};
|
||||
|
||||
EconomyManager.prototype.buildMoreFields = function(gameState, queues) {
|
||||
// give time for treasures to be gathered
|
||||
if (gameState.getTimeElapsed() < 30 * 1000)
|
||||
return;
|
||||
|
||||
var numFood = 0;
|
||||
|
||||
gameState.updatingCollection("active-dropsite-food", Filters.byMetadata("active-dropsite-food", true),
|
||||
gameState.getOwnDropsites("food")).forEach(function (dropsite){
|
||||
numFood += dropsite.getMetadata("nearby-resources-food").length;
|
||||
});
|
||||
|
||||
var numFarms = gameState.countFoundationsWithType(gameState.applyCiv("structures/{civ}_field"));
|
||||
numFarms += queues.field.countTotalQueuedUnits();
|
||||
|
||||
if (gameState.countEntitiesByType(gameState.applyCiv("structures/{civ}_field")) == 0)
|
||||
numFood = Math.floor(numFood/1.5);
|
||||
if (numFood+numFarms < this.targetNumFields)
|
||||
queues.field.addItem(new BuildingConstructionPlan(gameState, "structures/{civ}_field"));
|
||||
};
|
||||
|
||||
// If all the CC's are destroyed then build a new one
|
||||
EconomyManager.prototype.buildNewCC= function(gameState, queues) {
|
||||
var numCCs = gameState.countEntitiesAndQueuedByType(gameState.applyCiv("structures/{civ}_civil_centre"));
|
||||
numCCs += queues.civilCentre.totalLength();
|
||||
|
||||
for ( var i = numCCs; i < 1; i++) {
|
||||
queues.civilCentre.addItem(new BuildingConstructionPlan(gameState, "structures/{civ}_civil_centre"));
|
||||
}
|
||||
};
|
||||
|
||||
//creates and maintains a map of tree density
|
||||
EconomyManager.prototype.updateResourceMaps = function(gameState, events){
|
||||
// The weight of the influence function is amountOfResource/decreaseFactor
|
||||
var decreaseFactor = {'wood': 15, 'stone': 100, 'metal': 100, 'food': 20};
|
||||
// This is the maximum radius of the influence
|
||||
var radius = {'wood':13, 'stone': 10, 'metal': 10, 'food': 10};
|
||||
|
||||
var self = this;
|
||||
|
||||
for (var resource in radius){
|
||||
// if there is no resourceMap create one with an influence for everything with that resource
|
||||
if (! this.resourceMaps[resource]){
|
||||
this.resourceMaps[resource] = new Map(gameState);
|
||||
|
||||
var supplies = gameState.getResourceSupplies(resource);
|
||||
supplies.forEach(function(ent){
|
||||
if (!ent.position()){
|
||||
return;
|
||||
}
|
||||
var x = Math.round(ent.position()[0] / gameState.cellSize);
|
||||
var z = Math.round(ent.position()[1] / gameState.cellSize);
|
||||
var strength = Math.round(ent.resourceSupplyMax()/decreaseFactor[resource]);
|
||||
self.resourceMaps[resource].addInfluence(x, z, radius[resource], strength);
|
||||
});
|
||||
}
|
||||
// TODO: fix for treasure and move out of loop
|
||||
// Look for destroy events and subtract the entities original influence from the resourceMap
|
||||
for (var i in events) {
|
||||
var e = events[i];
|
||||
|
||||
if (e.type === "Destroy") {
|
||||
if (e.msg.entityObj){
|
||||
var ent = e.msg.entityObj;
|
||||
if (ent && ent.position() && ent.resourceSupplyType() && ent.resourceSupplyType().generic === resource){
|
||||
var x = Math.round(ent.position()[0] / gameState.cellSize);
|
||||
var z = Math.round(ent.position()[1] / gameState.cellSize);
|
||||
var strength = Math.round(ent.resourceSupplyMax()/decreaseFactor[resource]);
|
||||
this.resourceMaps[resource].addInfluence(x, z, radius[resource], -strength);
|
||||
}
|
||||
}
|
||||
}else if (e.type === "Create") {
|
||||
if (e.msg.entityObj){
|
||||
var ent = e.msg.entityObj;
|
||||
if (ent && ent.position() && ent.resourceSupplyType() && ent.resourceSupplyType().generic === resource){
|
||||
var x = Math.round(ent.position()[0] / gameState.cellSize);
|
||||
var z = Math.round(ent.position()[1] / gameState.cellSize);
|
||||
var strength = Math.round(ent.resourceSupplyMax()/decreaseFactor[resource]);
|
||||
this.resourceMaps[resource].addInfluence(x, z, radius[resource], strength);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//this.resourceMaps['wood'].dumpIm("tree_density.png");
|
||||
};
|
||||
|
||||
// Returns the position of the best place to build a new dropsite for the specified resource
|
||||
EconomyManager.prototype.getBestResourceBuildSpot = function(gameState, resource){
|
||||
// A map which gives a positive weight for all CCs and adds a negative weight near all dropsites
|
||||
var friendlyTiles = new Map(gameState);
|
||||
gameState.getOwnEntities().forEach(function(ent) {
|
||||
// We want to build near a CC of ours
|
||||
if (ent.hasClass("CivCentre")){
|
||||
var infl = 200;
|
||||
|
||||
var pos = ent.position();
|
||||
var x = Math.round(pos[0] / gameState.cellSize);
|
||||
var z = Math.round(pos[1] / gameState.cellSize);
|
||||
friendlyTiles.addInfluence(x, z, infl, 0.1 * infl);
|
||||
friendlyTiles.addInfluence(x, z, infl/2, 0.1 * infl);
|
||||
}
|
||||
// We don't want multiple dropsites at one spot so add a negative for all dropsites
|
||||
if (ent.resourceDropsiteTypes() && ent.resourceDropsiteTypes().indexOf(resource) !== -1){
|
||||
var infl = 20;
|
||||
|
||||
var pos = ent.position();
|
||||
var x = Math.round(pos[0] / gameState.cellSize);
|
||||
var z = Math.round(pos[1] / gameState.cellSize);
|
||||
|
||||
friendlyTiles.addInfluence(x, z, infl, -50, 'quadratic');
|
||||
}
|
||||
});
|
||||
|
||||
// Multiply by tree density to get a combination of the two maps
|
||||
friendlyTiles.multiply(this.resourceMaps[resource]);
|
||||
|
||||
//friendlyTiles.dumpIm(resource + "_density_fade.png", 10000);
|
||||
|
||||
var obstructions = Map.createObstructionMap(gameState);
|
||||
obstructions.expandInfluences();
|
||||
|
||||
var bestIdx = friendlyTiles.findBestTile(4, obstructions)[0];
|
||||
|
||||
// Convert from 1d map pixel coordinates to game engine coordinates
|
||||
var x = ((bestIdx % friendlyTiles.width) + 0.5) * gameState.cellSize;
|
||||
var z = (Math.floor(bestIdx / friendlyTiles.width) + 0.5) * gameState.cellSize;
|
||||
return [x,z];
|
||||
};
|
||||
|
||||
EconomyManager.prototype.updateResourceConcentrations = function(gameState){
|
||||
var self = this;
|
||||
var resources = ["food", "wood", "stone", "metal"];
|
||||
for (var key in resources){
|
||||
var resource = resources[key];
|
||||
gameState.getOwnEntities().forEach(function(ent) {
|
||||
if (ent.resourceDropsiteTypes() && ent.resourceDropsiteTypes().indexOf(resource) !== -1){
|
||||
var radius = 14;
|
||||
|
||||
var pos = ent.position();
|
||||
var x = Math.round(pos[0] / gameState.cellSize);
|
||||
var z = Math.round(pos[1] / gameState.cellSize);
|
||||
|
||||
var quantity = self.resourceMaps[resource].sumInfluence(x, z, radius);
|
||||
|
||||
ent.setMetadata("resourceQuantity_" + resource, quantity);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Stores lists of nearby resources
|
||||
EconomyManager.prototype.updateNearbyResources = function(gameState){
|
||||
var self = this;
|
||||
var resources = ["food", "wood", "stone", "metal"];
|
||||
var resourceSupplies;
|
||||
var radius = 100;
|
||||
for (var key in resources){
|
||||
var resource = resources[key];
|
||||
|
||||
gameState.getOwnDropsites(resource).forEach(function(ent) {
|
||||
if (ent.getMetadata("nearby-resources-" + resource) === undefined){
|
||||
var filterPos = Filters.byStaticDistance(ent.position(), radius);
|
||||
|
||||
var collection = gameState.getResourceSupplies(resource).filter(filterPos);
|
||||
collection.registerUpdates();
|
||||
|
||||
ent.setMetadata("nearby-resources-" + resource, collection);
|
||||
ent.setMetadata("active-dropsite-" + resource, true);
|
||||
}
|
||||
|
||||
if (ent.getMetadata("nearby-resources-" + resource).length === 0){
|
||||
ent.setMetadata("active-dropsite-" + resource, false);
|
||||
}else{
|
||||
ent.setMetadata("active-dropsite-" + resource, true);
|
||||
}
|
||||
/*
|
||||
// Make resources glow wildly
|
||||
if (resource == "food"){
|
||||
ent.getMetadata("nearby-resources-" + resource).forEach(function(ent){
|
||||
Engine.PostCommand({"type": "set-shading-color", "entities": [ent.id()], "rgb": [10,0,0]});
|
||||
});
|
||||
}
|
||||
if (resource == "wood"){
|
||||
ent.getMetadata("nearby-resources-" + resource).forEach(function(ent){
|
||||
Engine.PostCommand({"type": "set-shading-color", "entities": [ent.id()], "rgb": [0,10,0]});
|
||||
});
|
||||
}
|
||||
if (resource == "metal"){
|
||||
ent.getMetadata("nearby-resources-" + resource).forEach(function(ent){
|
||||
Engine.PostCommand({"type": "set-shading-color", "entities": [ent.id()], "rgb": [0,0,10]});
|
||||
});
|
||||
}*/
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
//return the number of resource dropsites with an acceptable amount of the resource nearby
|
||||
EconomyManager.prototype.checkResourceConcentrations = function(gameState, resource){
|
||||
//TODO: make these values adaptive
|
||||
var requiredInfluence = {wood: 16000, stone: 300, metal: 300};
|
||||
var count = 0;
|
||||
gameState.getOwnEntities().forEach(function(ent) {
|
||||
if (ent.resourceDropsiteTypes() && ent.resourceDropsiteTypes().indexOf(resource) !== -1){
|
||||
var quantity = ent.getMetadata("resourceQuantity_" + resource);
|
||||
|
||||
if (quantity >= requiredInfluence[resource]){
|
||||
count ++;
|
||||
}
|
||||
}
|
||||
});
|
||||
return count;
|
||||
};
|
||||
|
||||
EconomyManager.prototype.buildMarket = function(gameState, queues){
|
||||
if (gameState.getTimeElapsed() > 600 * 1000){
|
||||
if (queues.economicBuilding.countTotalQueuedUnitsWithClass("BarterMarket") === 0 &&
|
||||
gameState.countEntitiesAndQueuedByType(gameState.applyCiv("structures/{civ}_market")) === 0){
|
||||
//only ever build one mill/CC/market at a time
|
||||
queues.economicBuilding.addItem(new BuildingConstructionPlan(gameState, "structures/{civ}_market"));
|
||||
}
|
||||
}
|
||||
};
|
||||
// if qBot has resources it doesn't need, it'll try to barter it for resources it needs
|
||||
// once per turn because the info doesn't update between a turn and I don't want to fix it.
|
||||
// pretty efficient.
|
||||
EconomyManager.prototype.tryBartering = function(gameState){
|
||||
var done = false;
|
||||
if (gameState.countEntitiesByType(gameState.applyCiv("structures/{civ}_market")) >= 1) {
|
||||
|
||||
var needs = gameState.ai.queueManager.futureNeeds(gameState,true);
|
||||
var ress = gameState.ai.queueManager.getAvailableResources(gameState);
|
||||
|
||||
for (sell in needs) {
|
||||
for (buy in needs) {
|
||||
if (!done && buy != sell && needs[sell] <= 0 && ress[sell] > 400) { // if we don't need it and have a buffer
|
||||
if ( (ress[buy] < 400) || needs[buy] > 0) { // if we need that other resource/ have too little of it
|
||||
var markets = gameState.getOwnEntitiesByType(gameState.applyCiv("structures/{civ}_market")).toEntityArray();
|
||||
markets[0].barter(buy,sell,100);
|
||||
//debug ("bartered " +sell +" for " + buy + ", value 100");
|
||||
done = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
EconomyManager.prototype.buildDropsites = function(gameState, queues){
|
||||
if (queues.economicBuilding.totalLength() === 0 &&
|
||||
gameState.countFoundationsWithType(gameState.applyCiv("structures/{civ}_mill")) === 0 &&
|
||||
gameState.countFoundationsWithType(gameState.applyCiv("structures/{civ}_civil_centre")) === 0){
|
||||
//only ever build one mill/CC/market at a time
|
||||
if (gameState.getTimeElapsed() > 30 * 1000){
|
||||
for (var resource in this.dropsiteNumbers){
|
||||
if (this.checkResourceConcentrations(gameState, resource) < this.dropsiteNumbers[resource]){
|
||||
var spot = this.getBestResourceBuildSpot(gameState, resource);
|
||||
|
||||
var myCivCentres = gameState.getOwnEntities().filter(function(ent) {
|
||||
if (!ent.hasClass("CivCentre") || ent.position() === undefined){
|
||||
return false;
|
||||
}
|
||||
var dx = (spot[0]-ent.position()[0]);
|
||||
var dy = (spot[1]-ent.position()[1]);
|
||||
var dist2 = dx*dx + dy*dy;
|
||||
return (ent.hasClass("CivCentre") && dist2 < 180*180);
|
||||
});
|
||||
|
||||
if (myCivCentres.length === 0){
|
||||
queues.economicBuilding.addItem(new BuildingConstructionPlan(gameState, "structures/{civ}_civil_centre", spot));
|
||||
}else{
|
||||
queues.economicBuilding.addItem(new BuildingConstructionPlan(gameState, "structures/{civ}_mill", spot));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
EconomyManager.prototype.update = function(gameState, queues, events) {
|
||||
Engine.ProfileStart("economy update");
|
||||
|
||||
this.reassignRolelessUnits(gameState);
|
||||
|
||||
this.buildNewCC(gameState,queues);
|
||||
|
||||
Engine.ProfileStart("Train workers and build farms");
|
||||
this.trainMoreWorkers(gameState, queues);
|
||||
|
||||
this.buildMoreFields(gameState,queues);
|
||||
Engine.ProfileStop();
|
||||
|
||||
//Later in the game we want to build stuff faster.
|
||||
if (gameState.countEntitiesByType(gameState.applyCiv("units/{civ}_support_female_citizen")) > this.targetNumWorkers * 0.5) {
|
||||
this.targetNumBuilders = 6;
|
||||
}else{
|
||||
this.targetNumBuilders = 3;
|
||||
}
|
||||
|
||||
if (gameState.countEntitiesByType(gameState.applyCiv("units/{civ}_support_female_citizen")) > this.targetNumWorkers * 0.8) {
|
||||
this.dropsiteNumbers = {wood: 3, stone: 2, metal: 2};
|
||||
}else{
|
||||
this.dropsiteNumbers = {wood: 2, stone: 1, metal: 1};
|
||||
}
|
||||
|
||||
Engine.ProfileStart("Update Resource Maps and Concentrations");
|
||||
this.updateResourceMaps(gameState, events);
|
||||
this.updateResourceConcentrations(gameState);
|
||||
this.updateNearbyResources(gameState);
|
||||
Engine.ProfileStop();
|
||||
|
||||
Engine.ProfileStart("Build new Dropsites");
|
||||
this.buildDropsites(gameState, queues);
|
||||
Engine.ProfileStop();
|
||||
|
||||
this.tryBartering(gameState);
|
||||
this.buildMarket(gameState, queues);
|
||||
|
||||
// TODO: implement a timer based system for this
|
||||
this.setCount += 1;
|
||||
if (this.setCount >= 20){
|
||||
this.setWorkersIdleByPriority(gameState);
|
||||
this.setCount = 0;
|
||||
}
|
||||
|
||||
|
||||
Engine.ProfileStart("Assign builders");
|
||||
this.assignToFoundations(gameState);
|
||||
Engine.ProfileStop();
|
||||
|
||||
Engine.ProfileStart("Reassign Idle Workers");
|
||||
this.reassignIdleWorkers(gameState);
|
||||
Engine.ProfileStop();
|
||||
|
||||
Engine.ProfileStart("Swap Workers");
|
||||
var gathererGroups = {};
|
||||
gameState.getOwnEntitiesByRole("worker").forEach(function(ent){
|
||||
var key = uneval(ent.resourceGatherRates());
|
||||
if (!gathererGroups[key]){
|
||||
gathererGroups[key] = {"food": [], "wood": [], "metal": [], "stone": []};
|
||||
}
|
||||
if (ent.getMetadata("gather-type") in gathererGroups[key]){
|
||||
gathererGroups[key][ent.getMetadata("gather-type")].push(ent);
|
||||
}
|
||||
});
|
||||
|
||||
for (var i in gathererGroups){
|
||||
for (var j in gathererGroups){
|
||||
var a = eval(i);
|
||||
var b = eval(j);
|
||||
if (a["food.grain"]/b["food.grain"] > a["wood.tree"]/b["wood.tree"] && gathererGroups[i]["wood"].length > 0 && gathererGroups[j]["food"].length > 0){
|
||||
for (var k = 0; k < Math.min(gathererGroups[i]["wood"].length, gathererGroups[j]["food"].length); k++){
|
||||
gathererGroups[i]["wood"][k].setMetadata("gather-type", "food");
|
||||
gathererGroups[j]["food"][k].setMetadata("gather-type", "wood");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Engine.ProfileStop();
|
||||
|
||||
Engine.ProfileStart("Run Workers");
|
||||
gameState.getOwnEntitiesByRole("worker").forEach(function(ent){
|
||||
if (!ent.getMetadata("worker-object")){
|
||||
ent.setMetadata("worker-object", new Worker(ent));
|
||||
}
|
||||
ent.getMetadata("worker-object").update(gameState);
|
||||
});
|
||||
|
||||
// Gatherer count updates for non-workers
|
||||
var filter = Filters.and(Filters.not(Filters.byMetadata("worker-object", undefined)),
|
||||
Filters.not(Filters.byMetadata("role", "worker")));
|
||||
gameState.updatingCollection("reassigned-workers", filter, gameState.getOwnEntities()).forEach(function(ent){
|
||||
ent.getMetadata("worker-object").updateGathererCounts(gameState);
|
||||
});
|
||||
|
||||
// Gatherer count updates for destroyed units
|
||||
for (var i in events) {
|
||||
var e = events[i];
|
||||
|
||||
if (e.type === "Destroy") {
|
||||
if (e.msg.metadata && e.msg.metadata[gameState.getPlayerID()] && e.msg.metadata[gameState.getPlayerID()]["worker-object"]){
|
||||
e.msg.metadata[gameState.getPlayerID()]["worker-object"].updateGathererCounts(gameState, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
Engine.ProfileStop();
|
||||
|
||||
Engine.ProfileStop();
|
||||
};
|
195
binaries/data/mods/public/simulation/ai/qbot-wc/enemy-watcher.js
Executable file
195
binaries/data/mods/public/simulation/ai/qbot-wc/enemy-watcher.js
Executable file
@ -0,0 +1,195 @@
|
||||
/*
|
||||
* A class that keeps track of enem 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.
|
||||
*/
|
||||
|
||||
var enemyWatcher = function(gameState, playerToWatch) {
|
||||
|
||||
this.watched = playerToWatch;
|
||||
|
||||
// creating fitting entity collections
|
||||
var filter = Filters.and(Filters.byClass("Structure"), Filters.byOwner(this.watched));
|
||||
this.enemyBuildings = gameState.getEnemyEntities().filter(filter);
|
||||
this.enemyBuildings.registerUpdates();
|
||||
|
||||
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();
|
||||
|
||||
// okay now we register here only enemy soldiers that we are monitoring (ie we see as part of an army…)
|
||||
filter = Filters.and(Filters.byClassesOr(["CitizenSoldier", "Hero", "Champion", "Siege"]), Filters.and(Filters.byMetadata("monitored","true"),Filters.byOwner(this.watched)));
|
||||
this.monitoredEnemySoldiers = gameState.getEnemyEntities().filter(filter);
|
||||
this.monitoredEnemySoldiers.registerUpdates();
|
||||
|
||||
// and here those that we do not monitor
|
||||
filter = Filters.and(Filters.byClassesOr(["CitizenSoldier","Hero","Champion","Siege"]), Filters.and(Filters.not(Filters.byMetadata("monitored","true")),Filters.byOwner(this.watched)));
|
||||
this.unmonitoredEnemySoldiers = gameState.getEnemyEntities().filter(filter);
|
||||
this.unmonitoredEnemySoldiers.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(specialClass, OneTime) {
|
||||
var filter = Filters.byClass(specialClass);
|
||||
var returnable = this.enemyBuildings.filter(filter);
|
||||
|
||||
if (!this.enemyBuildingClass[specialClass] && !OneTime) {
|
||||
this.enemyBuildingClass[specialClass] = returnable;
|
||||
this.enemyBuildingClass[specialClass].registerUpdates();
|
||||
return this.enemyBuildingClass[specialClass];
|
||||
}
|
||||
return returnable;
|
||||
};
|
||||
enemyWatcher.prototype.getDangerousArmies = function() {
|
||||
var toreturn = {};
|
||||
for (i in this.dangerousArmies)
|
||||
toreturn[this.dangerousArmies[i]] = this.armies[this.dangerousArmies[i]];
|
||||
return toreturn;
|
||||
};
|
||||
enemyWatcher.prototype.getSafeArmies = function() {
|
||||
var toreturn = {};
|
||||
for (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 (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 (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;
|
||||
// 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("monitored","true");
|
||||
var armyID = uneval( gameState.player + "" + self.totalNBofArmies);
|
||||
self.totalNBofArmies++,
|
||||
enemy.setMetadata("EnemyWatcherArmy",armyID);
|
||||
var filter = Filters.byMetadata("EnemyWatcherArmy",armyID);
|
||||
var army = self.enemySoldiers.filter(filter);
|
||||
self.armies[armyID] = army;
|
||||
self.armies[armyID].registerUpdates();
|
||||
self.armies[armyID].length;
|
||||
});
|
||||
this.mergeArmies(); // calls "scrap empty armies"
|
||||
this.splitArmies(gameState);
|
||||
};
|
||||
// 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 (army in this.armies) {
|
||||
var firstArmy = this.armies[army];
|
||||
if (firstArmy.length > 0)
|
||||
for (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(firstArmy.getCentrePosition(),secondArmy.getCentrePosition(), 3000 ) ) {
|
||||
// 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("EnemyWatcherArmy",army);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
this.ScrapEmptyArmies();
|
||||
};
|
||||
enemyWatcher.prototype.ScrapEmptyArmies = function(){
|
||||
var removelist = [];
|
||||
for (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 (toRemove in removelist) {
|
||||
delete this.armies[toRemove];
|
||||
}
|
||||
};
|
||||
// splits any unit too far from the centerposition
|
||||
enemyWatcher.prototype.splitArmies = function(gameState){
|
||||
var self = this;
|
||||
for (armyID in this.armies) {
|
||||
var army = this.armies[armyID];
|
||||
var centre = army.getCentrePosition();
|
||||
army.forEach( function (enemy) {
|
||||
if (enemy.position() == undefined)
|
||||
return;
|
||||
if (!inRange(enemy.position(),centre, 3500) ) {
|
||||
var newArmyID = uneval( gameState.player + "" + self.totalNBofArmies);
|
||||
if (self.dangerousArmies.indexOf(armyID) !== -1)
|
||||
self.dangerousArmies.push(newArmyID);
|
||||
|
||||
self.totalNBofArmies++,
|
||||
enemy.setMetadata("EnemyWatcherArmy",newArmyID);
|
||||
var filter = Filters.byMetadata("EnemyWatcherArmy",newArmyID);
|
||||
var newArmy = self.enemySoldiers.filter(filter);
|
||||
self.armies[newArmyID] = newArmy;
|
||||
self.armies[newArmyID].registerUpdates();
|
||||
self.armies[newArmyID].length;
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
152
binaries/data/mods/public/simulation/ai/qbot-wc/entity-extend.js
Normal file
152
binaries/data/mods/public/simulation/ai/qbot-wc/entity-extend.js
Normal file
@ -0,0 +1,152 @@
|
||||
EntityTemplate.prototype.genericName = function() {
|
||||
if (!this._template.Identity || !this._template.Identity.GenericName)
|
||||
return undefined;
|
||||
return this._template.Identity.GenericName;
|
||||
};
|
||||
EntityTemplate.prototype.walkSpeed = function() {
|
||||
if (!this._template.UnitMotion || !this._template.UnitMotion.WalkSpeed)
|
||||
return undefined;
|
||||
return this._template.UnitMotion.WalkSpeed;
|
||||
};
|
||||
EntityTemplate.prototype.buildTime = function() {
|
||||
if (!this._template.Cost || !this._template.Cost.buildTime)
|
||||
return undefined;
|
||||
return this._template.Cost.buildTime;
|
||||
};
|
||||
EntityTemplate.prototype.getPopulationBonus = function() {
|
||||
if (!this._template.Cost || !this._template.Cost.PopulationBonus)
|
||||
return undefined;
|
||||
|
||||
return this._template.Cost.PopulationBonus;
|
||||
};
|
||||
// will return either "food", "wood", "stone", "metal" and not treasure.
|
||||
EntityTemplate.prototype.getResourceType = function() {
|
||||
if (!this._template.ResourceSupply)
|
||||
return undefined;
|
||||
var [type, subtype] = this._template.ResourceSupply.Type.split('.');
|
||||
if (type == "treasure")
|
||||
return subtype;
|
||||
return type;
|
||||
};
|
||||
EntityTemplate.prototype.garrisonMax = function() {
|
||||
if (!this._template.GarrisonHolder)
|
||||
return undefined;
|
||||
return this._template.GarrisonHolder.Max;
|
||||
};
|
||||
EntityTemplate.prototype.getMaxStrength = function()
|
||||
{
|
||||
var strength = 0.0;
|
||||
var attackTypes = this.attackTypes();
|
||||
var armourStrength = this.armourStrengths();
|
||||
var hp = this.maxHitpoints() / 100.0; // some normalization
|
||||
for (var typeKey in attackTypes) {
|
||||
var type = attackTypes[typeKey];
|
||||
var attackStrength = this.attackStrengths(type);
|
||||
var attackRange = this.attackRange(type);
|
||||
var attackTimes = this.attackTimes(type);
|
||||
for (var str in attackStrength) {
|
||||
var val = parseFloat(attackStrength[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;
|
||||
}
|
||||
}
|
||||
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;
|
||||
};
|
||||
|
||||
EntityTemplate.prototype.costSum = function() {
|
||||
if (!this._template.Cost)
|
||||
return undefined;
|
||||
|
||||
var ret = 0;
|
||||
for (var type in this._template.Cost.Resources)
|
||||
ret += +this._template.Cost.Resources[type];
|
||||
return ret;
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
Entity.prototype.deleteMetadata = function(id) {
|
||||
delete this._ai._entityMetadata[this.id()];
|
||||
};
|
||||
|
||||
Entity.prototype.unload = function(id) {
|
||||
if (!this._template.GarrisonHolder)
|
||||
return undefined;
|
||||
Engine.PostCommand({"type": "unload", "garrisonHolder": this.id(), "entity": id});
|
||||
return this;
|
||||
};
|
||||
|
||||
Entity.prototype.unloadAll = function() {
|
||||
if (!this._template.GarrisonHolder)
|
||||
return undefined;
|
||||
Engine.PostCommand({"type": "unload-all", "garrisonHolder": this.id()});
|
||||
return this;
|
||||
};
|
||||
|
||||
Entity.prototype.garrison = function(target) {
|
||||
Engine.PostCommand({"type": "garrison", "entities": [this.id()], "target": target.id(),"queued": false});
|
||||
return this;
|
||||
};
|
||||
|
||||
Entity.prototype.attack = function(unitId)
|
||||
{
|
||||
Engine.PostCommand({"type": "attack", "entities": [this.id()], "target": unitId, "queued": false});
|
||||
return this;
|
||||
};
|
||||
|
||||
Entity.prototype.stopMoving = function() {
|
||||
if (this.position() !== undefined)
|
||||
Engine.PostCommand({"type": "walk", "entities": [this.id()], "x": this.position()[0], "z": this.position()[1], "queued": false});
|
||||
};
|
||||
// from from a unit in the opposite direction.
|
||||
Entity.prototype.flee = function(unitToFleeFrom) {
|
||||
if (this.position() !== undefined && unitToFleeFrom.position() !== undefined) {
|
||||
var FleeDirection = [unitToFleeFrom.position()[0] - this.position()[0],unitToFleeFrom.position()[1] - this.position()[1]];
|
||||
|
||||
Engine.PostCommand({"type": "walk", "entities": [this.id()], "x": this.position()[0] + FleeDirection[0]*5, "z": this.position()[1] + FleeDirection[1]*5, "queued": false});
|
||||
}
|
||||
return this;
|
||||
};
|
||||
Entity.prototype.barter = function(buyType, sellType, amount) {
|
||||
|
||||
Engine.PostCommand({"type": "barter", "sell" : sellType, "buy" : buyType, "amount" : amount });
|
||||
return this;
|
||||
};
|
@ -0,0 +1,46 @@
|
||||
EntityCollection.prototype.attack = function(unit)
|
||||
{
|
||||
var unitId;
|
||||
if (typeof(unit) === "Entity"){
|
||||
unitId = unit.id();
|
||||
}else{
|
||||
unitId = unit;
|
||||
}
|
||||
|
||||
Engine.PostCommand({"type": "attack", "entities": this.toIdArray(), "target": unitId, "queued": false});
|
||||
return this;
|
||||
};
|
||||
|
||||
EntityCollection.prototype.attackMove = function(x, z){
|
||||
Engine.PostCommand({"type": "attack-move", "entities": this.toIdArray(), "x": x, "z": z, "queued": false});
|
||||
return this;
|
||||
};
|
||||
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
EntityCollection.prototype.getCentrePosition = function(){
|
||||
var sumPos = [0, 0];
|
||||
var count = 0;
|
||||
this.forEach(function(ent){
|
||||
if (ent.position()){
|
||||
sumPos[0] += ent.position()[0];
|
||||
sumPos[1] += ent.position()[1];
|
||||
count ++;
|
||||
}
|
||||
});
|
||||
if (count === 0){
|
||||
return undefined;
|
||||
}else{
|
||||
return [sumPos[0]/count, sumPos[1]/count];
|
||||
}
|
||||
};
|
@ -0,0 +1,33 @@
|
||||
// Some new filters I use in entity Collections
|
||||
|
||||
Filters["byID"] =
|
||||
function(id){
|
||||
return {"func": function(ent){
|
||||
return (ent.id() == id);
|
||||
},
|
||||
"dynamicProperties": ['id']};
|
||||
};
|
||||
Filters["byTargetedEntity"] =
|
||||
function(targetID){
|
||||
return {"func": function(ent){
|
||||
return (ent.unitAIOrderData() && ent.unitAIOrderData()["target"] && ent.unitAIOrderData()["target"] == targetID);
|
||||
},
|
||||
"dynamicProperties": ['unitAIOrderData']};
|
||||
};
|
||||
Filters["byHasMetadata"] =
|
||||
function(key){
|
||||
return {"func" : function(ent){
|
||||
return (ent.getMetadata(key) != undefined);
|
||||
},
|
||||
"dynamicProperties": ['metadata.' + key]};
|
||||
};
|
||||
Filters["byTerritory"] = function(Map, territoryIndex){
|
||||
return {"func": function(ent){
|
||||
if (Map.point(ent.position()) == territoryIndex) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
"dynamicProperties": ['position']};
|
||||
};
|
358
binaries/data/mods/public/simulation/ai/qbot-wc/gamestate.js
Normal file
358
binaries/data/mods/public/simulation/ai/qbot-wc/gamestate.js
Normal file
@ -0,0 +1,358 @@
|
||||
/**
|
||||
* Provides an API for the rest of the AI scripts to query the world state at a
|
||||
* higher level than the raw data.
|
||||
*/
|
||||
var GameState = function(ai) {
|
||||
MemoizeInit(this);
|
||||
|
||||
this.ai = ai;
|
||||
this.timeElapsed = ai.timeElapsed;
|
||||
this.templates = ai.templates;
|
||||
this.entities = ai.entities;
|
||||
this.player = ai.player;
|
||||
this.playerData = ai.playerData;
|
||||
this.buildingsBuilt = 0;
|
||||
|
||||
if (!this.ai._gameStateStore){
|
||||
this.ai._gameStateStore = {};
|
||||
}
|
||||
this.store = this.ai._gameStateStore;
|
||||
|
||||
this.cellSize = 4; // Size of each map tile
|
||||
|
||||
this.turnCache = {};
|
||||
};
|
||||
|
||||
GameState.prototype.updatingCollection = function(id, filter, collection){
|
||||
if (!this.store[id]){
|
||||
this.store[id] = collection.filter(filter);
|
||||
this.store[id].registerUpdates();
|
||||
}
|
||||
|
||||
return this.store[id];
|
||||
};
|
||||
|
||||
GameState.prototype.getTimeElapsed = function() {
|
||||
return this.timeElapsed;
|
||||
};
|
||||
|
||||
GameState.prototype.getTemplate = function(type) {
|
||||
if (!this.templates[type]){
|
||||
return null;
|
||||
}
|
||||
|
||||
return new EntityTemplate(this.templates[type]);
|
||||
};
|
||||
|
||||
GameState.prototype.applyCiv = function(str) {
|
||||
return str.replace(/\{civ\}/g, this.playerData.civ);
|
||||
};
|
||||
|
||||
/**
|
||||
* @returns {Resources}
|
||||
*/
|
||||
GameState.prototype.getResources = function() {
|
||||
return new Resources(this.playerData.resourceCounts);
|
||||
};
|
||||
|
||||
GameState.prototype.getMap = function() {
|
||||
return this.ai.passabilityMap;
|
||||
};
|
||||
|
||||
GameState.prototype.getTerritoryMap = function() {
|
||||
return Map.createTerritoryMap(this);
|
||||
};
|
||||
|
||||
GameState.prototype.getPopulation = function() {
|
||||
return this.playerData.popCount;
|
||||
};
|
||||
|
||||
GameState.prototype.getPopulationLimit = function() {
|
||||
return this.playerData.popLimit;
|
||||
};
|
||||
|
||||
GameState.prototype.getPopulationMax = function() {
|
||||
return this.playerData.popMax;
|
||||
};
|
||||
|
||||
GameState.prototype.getPassabilityClassMask = function(name) {
|
||||
if (!(name in this.ai.passabilityClasses)){
|
||||
error("Tried to use invalid passability class name '" + name + "'");
|
||||
}
|
||||
return this.ai.passabilityClasses[name];
|
||||
};
|
||||
|
||||
GameState.prototype.getPlayerID = function() {
|
||||
return this.player;
|
||||
};
|
||||
|
||||
GameState.prototype.isPlayerAlly = function(id) {
|
||||
return this.playerData.isAlly[id];
|
||||
};
|
||||
|
||||
GameState.prototype.isPlayerEnemy = function(id) {
|
||||
return this.playerData.isEnemy[id];
|
||||
};
|
||||
|
||||
GameState.prototype.getEnemies = function(){
|
||||
var ret = [];
|
||||
for (var i in this.playerData.isEnemy){
|
||||
if (this.playerData.isEnemy[i]){
|
||||
ret.push(i);
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
};
|
||||
|
||||
GameState.prototype.isEntityAlly = function(ent) {
|
||||
if (ent && ent.owner && (typeof ent.owner) === "function"){
|
||||
return this.playerData.isAlly[ent.owner()];
|
||||
} else if (ent && ent.owner){
|
||||
return this.playerData.isAlly[ent.owner];
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
GameState.prototype.isEntityEnemy = function(ent) {
|
||||
if (ent && ent.owner && (typeof ent.owner) === "function"){
|
||||
return this.playerData.isEnemy[ent.owner()];
|
||||
} else if (ent && ent.owner){
|
||||
return this.playerData.isEnemy[ent.owner];
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
GameState.prototype.isEntityOwn = function(ent) {
|
||||
if (ent && ent.owner && (typeof ent.owner) === "function"){
|
||||
return ent.owner() == this.player;
|
||||
} else if (ent && ent.owner){
|
||||
return ent.owner == this.player;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
GameState.prototype.getOwnEntities = function() {
|
||||
if (!this.store.ownEntities){
|
||||
this.store.ownEntities = this.getEntities().filter(Filters.byOwner(this.player));
|
||||
this.store.ownEntities.registerUpdates();
|
||||
}
|
||||
|
||||
return this.store.ownEntities;
|
||||
};
|
||||
|
||||
GameState.prototype.getEnemyEntities = function() {
|
||||
var diplomacyChange = false;
|
||||
var enemies = this.getEnemies();
|
||||
if (this.store.enemies){
|
||||
if (this.store.enemies.length != enemies.length){
|
||||
diplomacyChange = true;
|
||||
}else{
|
||||
for (var i = 0; i < enemies.length; i++){
|
||||
if (enemies[i] !== this.store.enemies[i]){
|
||||
diplomacyChange = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (diplomacyChange || !this.store.enemyEntities){
|
||||
var filter = Filters.byOwners(enemies);
|
||||
this.store.enemyEntities = this.getEntities().filter(filter);
|
||||
this.store.enemyEntities.registerUpdates();
|
||||
this.store.enemies = enemies;
|
||||
}
|
||||
|
||||
return this.store.enemyEntities;
|
||||
};
|
||||
|
||||
GameState.prototype.getEntities = function() {
|
||||
return this.entities;
|
||||
};
|
||||
|
||||
GameState.prototype.getEntityById = function(id){
|
||||
if (this.entities._entities[id]) {
|
||||
return this.entities._entities[id];
|
||||
}else{
|
||||
//debug("Entity " + id + " requested does not exist");
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
GameState.prototype.getOwnEntitiesByMetadata = function(key, value){
|
||||
if (!this.store[key + "-" + value]){
|
||||
var filter = Filters.byMetadata(key, value);
|
||||
this.store[key + "-" + value] = this.getOwnEntities().filter(filter);
|
||||
this.store[key + "-" + value].registerUpdates();
|
||||
}
|
||||
|
||||
return this.store[key + "-" + value];
|
||||
};
|
||||
|
||||
GameState.prototype.getOwnEntitiesByRole = function(role){
|
||||
return this.getOwnEntitiesByMetadata("role", role);
|
||||
};
|
||||
|
||||
// TODO: fix this so it picks up not in use training stuff
|
||||
GameState.prototype.getOwnTrainingFacilities = function(){
|
||||
return this.updatingCollection("own-training-facilities", Filters.byTrainingQueue(), this.getOwnEntities());
|
||||
};
|
||||
|
||||
GameState.prototype.getOwnEntitiesByType = function(type){
|
||||
var filter = Filters.byType(type);
|
||||
return this.updatingCollection("own-by-type-" + type, filter, this.getOwnEntities());
|
||||
};
|
||||
|
||||
GameState.prototype.countEntitiesByType = function(type) {
|
||||
return this.getOwnEntitiesByType(type).length;
|
||||
};
|
||||
|
||||
GameState.prototype.countEntitiesAndQueuedByType = function(type) {
|
||||
var count = this.countEntitiesByType(type);
|
||||
|
||||
// Count building foundations
|
||||
count += this.countEntitiesByType("foundation|" + type);
|
||||
|
||||
// Count entities in building production queues
|
||||
this.getOwnTrainingFacilities().forEach(function(ent){
|
||||
ent.trainingQueue().forEach(function(item) {
|
||||
if (item.template == type){
|
||||
count += item.count;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
return count;
|
||||
};
|
||||
|
||||
GameState.prototype.countFoundationsWithType = function(type) {
|
||||
var foundationType = "foundation|" + type;
|
||||
var count = 0;
|
||||
this.getOwnEntities().forEach(function(ent) {
|
||||
var t = ent.templateName();
|
||||
if (t == foundationType)
|
||||
++count;
|
||||
});
|
||||
return count;
|
||||
};
|
||||
|
||||
GameState.prototype.countOwnEntitiesByRole = function(role) {
|
||||
return this.getOwnEntitiesByRole(role).length;
|
||||
};
|
||||
|
||||
GameState.prototype.countOwnEntitiesAndQueuedWithRole = function(role) {
|
||||
var count = this.countOwnEntitiesByRole(role);
|
||||
|
||||
// Count entities in building production queues
|
||||
this.getOwnTrainingFacilities().forEach(function(ent) {
|
||||
ent.trainingQueue().forEach(function(item) {
|
||||
if (item.metadata && item.metadata.role == role)
|
||||
count += item.count;
|
||||
});
|
||||
});
|
||||
return count;
|
||||
};
|
||||
|
||||
GameState.prototype.countOwnQueuedEntitiesWithMetadata = function(data, value) {
|
||||
// Count entities in building production queues
|
||||
var count = 0;
|
||||
this.getOwnTrainingFacilities().forEach(function(ent) {
|
||||
ent.trainingQueue().forEach(function(item) {
|
||||
if (item.metadata && item.metadata.data && item.metadata.data == value)
|
||||
count += item.count;
|
||||
});
|
||||
});
|
||||
return count;
|
||||
};
|
||||
|
||||
/**
|
||||
* Find buildings that are capable of training the given unit type, and aren't
|
||||
* already too busy.
|
||||
*/
|
||||
GameState.prototype.findTrainers = function(template) {
|
||||
var maxQueueLength = 2; // avoid tying up resources in giant training queues
|
||||
|
||||
return this.getOwnTrainingFacilities().filter(function(ent) {
|
||||
|
||||
var trainable = ent.trainableEntities();
|
||||
if (!trainable || trainable.indexOf(template) == -1)
|
||||
return false;
|
||||
|
||||
var queue = ent.trainingQueue();
|
||||
if (queue) {
|
||||
if (queue.length >= maxQueueLength)
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Find units that are capable of constructing the given building type.
|
||||
*/
|
||||
GameState.prototype.findBuilders = function(template) {
|
||||
return this.getOwnEntities().filter(function(ent) {
|
||||
|
||||
var buildable = ent.buildableEntities();
|
||||
if (!buildable || buildable.indexOf(template) == -1)
|
||||
return false;
|
||||
|
||||
return true;
|
||||
});
|
||||
};
|
||||
|
||||
GameState.prototype.getOwnFoundations = function() {
|
||||
return this.updatingCollection("ownFoundations", Filters.isFoundation(), this.getOwnEntities());
|
||||
};
|
||||
|
||||
GameState.prototype.getOwnDropsites = function(resource){
|
||||
return this.updatingCollection("dropsite-own-" + resource, Filters.isDropsite(resource), this.getOwnEntities());
|
||||
};
|
||||
|
||||
GameState.prototype.getResourceSupplies = function(resource){
|
||||
return this.updatingCollection("resource-" + resource, Filters.byResource(resource), this.getEntities());
|
||||
};
|
||||
|
||||
GameState.prototype.getBuildLimits = function() {
|
||||
return this.playerData.buildLimits;
|
||||
};
|
||||
|
||||
GameState.prototype.getBuildCounts = function() {
|
||||
return this.playerData.buildCounts;
|
||||
};
|
||||
|
||||
// Checks whether the maximum number of buildings have been cnstructed for a certain catergory
|
||||
GameState.prototype.isBuildLimitReached = function(category) {
|
||||
if(this.playerData.buildLimits[category] === undefined || this.playerData.buildCounts[category] === undefined)
|
||||
return false;
|
||||
if(this.playerData.buildLimits[category].LimitsPerCivCentre != undefined)
|
||||
return (this.playerData.buildCounts[category] >= this.playerData.buildCounts["CivilCentre"]*this.playerData.buildLimits[category].LimitPerCivCentre);
|
||||
else
|
||||
return (this.playerData.buildCounts[category] >= this.playerData.buildLimits[category]);
|
||||
};
|
||||
|
||||
GameState.prototype.findTrainableUnits = function(classes){
|
||||
var allTrainable = [];
|
||||
this.getOwnEntities().forEach(function(ent) {
|
||||
var trainable = ent.trainableEntities();
|
||||
for (var i in trainable){
|
||||
if (allTrainable.indexOf(trainable[i]) === -1){
|
||||
allTrainable.push(trainable[i]);
|
||||
}
|
||||
}
|
||||
});
|
||||
var ret = [];
|
||||
for (var i in allTrainable) {
|
||||
var template = this.getTemplate(allTrainable[i]);
|
||||
var okay = true;
|
||||
for (o in classes)
|
||||
if (!template.hasClass(classes[o]))
|
||||
okay = false;
|
||||
if (template.hasClass("Hero")) // disabling heroes for now
|
||||
okay = false;
|
||||
if (okay)
|
||||
ret.push( [allTrainable[i], template] );
|
||||
}
|
||||
return ret;
|
||||
};
|
||||
|
||||
|
29
binaries/data/mods/public/simulation/ai/qbot-wc/housing.js
Normal file
29
binaries/data/mods/public/simulation/ai/qbot-wc/housing.js
Normal file
@ -0,0 +1,29 @@
|
||||
// Decides when to a new house needs to be built
|
||||
var HousingManager = function() {
|
||||
|
||||
};
|
||||
|
||||
HousingManager.prototype.buildMoreHouses = function(gameState, queues) {
|
||||
// temporary 'remaining population space' based check, need to do
|
||||
// predictive in future
|
||||
if (gameState.getPopulationLimit() - gameState.getPopulation() < 20
|
||||
&& gameState.getPopulationLimit() < gameState.getPopulationMax()) {
|
||||
var numConstructing = gameState.countEntitiesByType(gameState.applyCiv("foundation|structures/{civ}_house"));
|
||||
var numPlanned = queues.house.totalLength();
|
||||
|
||||
var additional = Math.ceil((20 - (gameState.getPopulationLimit() - gameState.getPopulation())) / 10)
|
||||
- numConstructing - numPlanned;
|
||||
|
||||
for ( var i = 0; i < additional; i++) {
|
||||
queues.house.addItem(new BuildingConstructionPlan(gameState, "structures/{civ}_house"));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
HousingManager.prototype.update = function(gameState, queues) {
|
||||
Engine.ProfileStart("housing update");
|
||||
|
||||
this.buildMoreHouses(gameState, queues);
|
||||
|
||||
Engine.ProfileStop();
|
||||
};
|
@ -0,0 +1,339 @@
|
||||
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.
|
263
binaries/data/mods/public/simulation/ai/qbot-wc/map-module.js
Normal file
263
binaries/data/mods/public/simulation/ai/qbot-wc/map-module.js
Normal file
@ -0,0 +1,263 @@
|
||||
const TERRITORY_PLAYER_MASK = 0x3F;
|
||||
|
||||
//TODO: Make this cope with negative cell values
|
||||
function Map(gameState, originalMap){
|
||||
// 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;
|
||||
if (originalMap){
|
||||
this.map = originalMap;
|
||||
}else{
|
||||
this.map = new Uint16Array(this.length);
|
||||
}
|
||||
this.cellSize = gameState.cellSize;
|
||||
}
|
||||
|
||||
Map.prototype.gamePosToMapPos = function(p){
|
||||
return [Math.round(p[0]/this.cellSize), Math.round(p[1]/this.cellSize)];
|
||||
};
|
||||
|
||||
Map.prototype.point = function(p){
|
||||
var q = this.gamePosToMapPos(p);
|
||||
return this.map[q[0] + this.width * q[1]];
|
||||
};
|
||||
|
||||
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");
|
||||
// Only accept valid land tiles (we don't handle docks yet)
|
||||
switch(placementType){
|
||||
case "shore":
|
||||
obstructionMask |= gameState.getPassabilityClassMask("building-shore");
|
||||
break;
|
||||
case "land":
|
||||
default:
|
||||
obstructionMask |= gameState.getPassabilityClassMask("building-land");
|
||||
break;
|
||||
}
|
||||
|
||||
var playerID = gameState.getPlayerID();
|
||||
|
||||
var obstructionTiles = new Uint16Array(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.accessibility.map[i] == 1);
|
||||
obstructionTiles[i] = (!tileAccessible || invalidTerritory || (passabilityMap.data[i] & obstructionMask)) ? 0 : 65535;
|
||||
}
|
||||
|
||||
var map = new Map(gameState, obstructionTiles);
|
||||
|
||||
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, -65535, '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;
|
||||
}
|
||||
|
||||
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;
|
||||
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 (-1 * quant > this.map[x + y * this.width]){
|
||||
this.map[x + y * this.width] = 0; //set anything which would have gone negative to 0
|
||||
}else{
|
||||
this.map[x + y * this.width] += quant;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Map.prototype.sumInfluence = function(cx, cy, radius){
|
||||
var x0 = Math.max(0, cx - radius);
|
||||
var y0 = Math.max(0, cy - radius);
|
||||
var x1 = Math.min(this.width, cx + radius);
|
||||
var y1 = Math.min(this.height, cy + radius);
|
||||
var radius2 = radius * radius;
|
||||
|
||||
var sum = 0;
|
||||
|
||||
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 < radius2){
|
||||
sum += this.map[x + y * this.width];
|
||||
}
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
};
|
||||
|
||||
/**
|
||||
* Make each cell's 16-bit value at least one greater than each of its
|
||||
* neighbours' values. (If the grid is initialised with 0s and 65535s, the
|
||||
* result of each cell is its Manhattan distance to the nearest 0.)
|
||||
*
|
||||
* TODO: maybe this should be 8-bit (and clamp at 255)?
|
||||
*/
|
||||
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 = 65535;
|
||||
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 = 65535;
|
||||
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];
|
||||
};
|
||||
|
||||
// Multiplies current map by the parameter map pixelwise
|
||||
Map.prototype.multiply = function(map){
|
||||
for (var i = 0; i < this.length; i++){
|
||||
this.map[i] *= map.map[i];
|
||||
}
|
||||
};
|
||||
|
||||
Map.prototype.dumpIm = function(name, threshold){
|
||||
name = name ? name : "default.png";
|
||||
threshold = threshold ? threshold : 256;
|
||||
Engine.DumpImage(name, this.map, this.width, this.height, threshold);
|
||||
};
|
637
binaries/data/mods/public/simulation/ai/qbot-wc/military.js
Executable file
637
binaries/data/mods/public/simulation/ai/qbot-wc/military.js
Executable file
@ -0,0 +1,637 @@
|
||||
/*
|
||||
* Military strategy:
|
||||
* * Try training an attack squad of a specified size
|
||||
* * When it's the appropriate size, send it to attack the enemy
|
||||
* * Repeat forever
|
||||
*
|
||||
*/
|
||||
|
||||
var MilitaryAttackManager = function() {
|
||||
// these use the structure soldiers[unitId] = true|false to register the units
|
||||
this.attackManagers = [AttackMoveToLocation];
|
||||
this.availableAttacks = [];
|
||||
this.currentAttacks = [];
|
||||
|
||||
// Counts how many attacks we have sent at the enemy.
|
||||
this.attackCount = 0;
|
||||
this.lastAttackTime = 0;
|
||||
|
||||
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]);
|
||||
}
|
||||
|
||||
this.getEconomicTargets = function(gameState, militaryManager){
|
||||
return militaryManager.getEnemyBuildings(gameState, "Economic");
|
||||
};
|
||||
// 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 = {};
|
||||
for (var i = 1; i <= 8; i++)
|
||||
if (gameState.player != i && gameState.isPlayerEnemy(i)) {
|
||||
this.enemyWatchers[i] = new enemyWatcher(gameState, i);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* @param (GameState) gameState
|
||||
* @param (string) soldierTypes
|
||||
* @returns array of soldiers for which training buildings exist
|
||||
*/
|
||||
MilitaryAttackManager.prototype.findTrainableUnits = function(gameState, soldierType){
|
||||
var allTrainable = [];
|
||||
gameState.getOwnEntities().forEach(function(ent) {
|
||||
var trainable = ent.trainableEntities();
|
||||
for (var i in trainable){
|
||||
if (allTrainable.indexOf(trainable[i]) === -1){
|
||||
allTrainable.push(trainable[i]);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
var ret = [];
|
||||
for (var i in allTrainable){
|
||||
var template = gameState.getTemplate(allTrainable[i]);
|
||||
if (soldierType == this.getSoldierType(template)){
|
||||
ret.push(allTrainable[i]);
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
};
|
||||
|
||||
// Returns the type of a soldier, either citizenSoldier, advanced or siege
|
||||
MilitaryAttackManager.prototype.getSoldierType = function(ent){
|
||||
if (ent.hasClass("Hero")){
|
||||
return undefined;
|
||||
}
|
||||
if (ent.hasClass("CitizenSoldier") && !ent.hasClass("Cavalry")){
|
||||
return "citizenSoldier";
|
||||
}else if (ent.hasClass("Champion") || ent.hasClass("CitizenSoldier")){
|
||||
return "advanced";
|
||||
}else if (ent.hasClass("Siege")){
|
||||
return "siege";
|
||||
}else{
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the unit type we should begin training. (Currently this is whatever
|
||||
* we have least of.)
|
||||
*/
|
||||
MilitaryAttackManager.prototype.findBestNewUnit = function(gameState, queue, soldierType) {
|
||||
var units = this.findTrainableUnits(gameState, soldierType);
|
||||
// Count each type
|
||||
var types = [];
|
||||
for ( var tKey in units) {
|
||||
var t = units[tKey];
|
||||
types.push([t, gameState.countEntitiesAndQueuedByType(gameState.applyCiv(t))
|
||||
+ queue.countAllByType(gameState.applyCiv(t)) ]);
|
||||
}
|
||||
|
||||
// Sort by increasing count
|
||||
types.sort(function(a, b) {
|
||||
return a[1] - b[1];
|
||||
});
|
||||
|
||||
if (types.length === 0){
|
||||
return false;
|
||||
}
|
||||
return types[0][0];
|
||||
};
|
||||
// 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 (i in parameters) {
|
||||
var param = parameters[i];
|
||||
|
||||
if (param[0] == "base") {
|
||||
aTopParam = param[1];
|
||||
bTopParam = param[1];
|
||||
}
|
||||
if (param[0] == "strength") {
|
||||
aTopParam += a[1].getMaxStrength() * param[1];
|
||||
bTopParam += b[1].getMaxStrength() * 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];
|
||||
}
|
||||
}
|
||||
return -(aTopParam/(aDivParam+1)) + (bTopParam/(bDivParam+1));
|
||||
});
|
||||
return units[0][0];
|
||||
};
|
||||
|
||||
|
||||
|
||||
MilitaryAttackManager.prototype.registerSoldiers = function(gameState) {
|
||||
var soldiers = gameState.getOwnEntitiesByRole("soldier");
|
||||
var self = this;
|
||||
|
||||
soldiers.forEach(function(ent) {
|
||||
ent.setMetadata("role", "military");
|
||||
ent.setMetadata("military", "unassigned");
|
||||
});
|
||||
};
|
||||
|
||||
// return count of enemy buildings for a given building class
|
||||
MilitaryAttackManager.prototype.getEnemyBuildings = function(gameState,cls) {
|
||||
var targets = gameState.entities.filter(function(ent) {
|
||||
return (gameState.isEntityEnemy(ent) && ent.hasClass("Structure") && ent.hasClass(cls) && ent.owner() !== 0 && ent.position());
|
||||
});
|
||||
return targets;
|
||||
};
|
||||
|
||||
// return n available units and makes these units unavailable
|
||||
MilitaryAttackManager.prototype.getAvailableUnits = function(n, filter) {
|
||||
var ret = [];
|
||||
var count = 0;
|
||||
|
||||
var units = undefined;
|
||||
|
||||
if (filter){
|
||||
units = this.getUnassignedUnits().filter(filter);
|
||||
}else{
|
||||
units = this.getUnassignedUnits();
|
||||
}
|
||||
|
||||
units.forEach(function(ent){
|
||||
ret.push(ent.id());
|
||||
ent.setMetadata("military", "assigned");
|
||||
ent.setMetadata("role", "military");
|
||||
count++;
|
||||
if (count >= n) {
|
||||
return;
|
||||
}
|
||||
});
|
||||
return ret;
|
||||
};
|
||||
|
||||
// Takes a single unit id, and marks it unassigned
|
||||
MilitaryAttackManager.prototype.unassignUnit = function(unit){
|
||||
this.entity(unit).setMetadata("military", "unassigned");
|
||||
};
|
||||
|
||||
// Takes an array of unit id's and marks all of them unassigned
|
||||
MilitaryAttackManager.prototype.unassignUnits = function(units){
|
||||
for (var i in units){
|
||||
this.unassignUnit(units[i]);
|
||||
}
|
||||
};
|
||||
|
||||
MilitaryAttackManager.prototype.getUnassignedUnits = function(){
|
||||
return this.gameState.getOwnEntitiesByMetadata("military", "unassigned");
|
||||
};
|
||||
|
||||
MilitaryAttackManager.prototype.countAvailableUnits = function(filter){
|
||||
var count = 0;
|
||||
if (filter){
|
||||
return this.getUnassignedUnits().filter(filter).length;
|
||||
}else{
|
||||
return this.getUnassignedUnits().length;
|
||||
}
|
||||
};
|
||||
|
||||
// Takes an entity id and returns an entity object or undefined if there is no entity with that id
|
||||
// Also sends a debug message warning if the id has no entity
|
||||
MilitaryAttackManager.prototype.entity = function(id) {
|
||||
return this.gameState.getEntityById(id);
|
||||
};
|
||||
|
||||
// Returns the military strength of unit
|
||||
MilitaryAttackManager.prototype.getUnitStrength = function(ent){
|
||||
var strength = 0.0;
|
||||
var attackTypes = ent.attackTypes();
|
||||
var armourStrength = ent.armourStrengths();
|
||||
var hp = 2 * ent.hitpoints() / (160 + 1*ent.maxHitpoints()); //100 = typical number of hitpoints
|
||||
for (var typeKey in attackTypes) {
|
||||
var type = attackTypes[typeKey];
|
||||
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]);
|
||||
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;
|
||||
};
|
||||
|
||||
// Returns the strength of the available units of ai army
|
||||
MilitaryAttackManager.prototype.measureAvailableStrength = function(){
|
||||
var strength = 0.0;
|
||||
var self = this;
|
||||
this.getUnassignedUnits(this.gameState).forEach(function(ent){
|
||||
strength += self.getUnitStrength(ent);
|
||||
});
|
||||
return strength;
|
||||
};
|
||||
|
||||
MilitaryAttackManager.prototype.getEnemySoldiers = function(){
|
||||
return this.enemySoldiers;
|
||||
};
|
||||
|
||||
// Returns the number of units in the largest enemy army
|
||||
MilitaryAttackManager.prototype.measureEnemyCount = function(gameState){
|
||||
// Measure enemy units
|
||||
var isEnemy = gameState.playerData.isEnemy;
|
||||
var enemyCount = [];
|
||||
var maxCount = 0;
|
||||
for ( var i = 1; i < isEnemy.length; i++) {
|
||||
enemyCount[i] = 0;
|
||||
}
|
||||
|
||||
// Loop through the enemy soldiers and add one to the count for that soldiers player's count
|
||||
this.enemySoldiers.forEach(function(ent) {
|
||||
enemyCount[ent.owner()]++;
|
||||
|
||||
if (enemyCount[ent.owner()] > maxCount) {
|
||||
maxCount = enemyCount[ent.owner()];
|
||||
}
|
||||
});
|
||||
|
||||
return maxCount;
|
||||
};
|
||||
|
||||
// Returns the strength of the largest enemy army
|
||||
MilitaryAttackManager.prototype.measureEnemyStrength = function(gameState){
|
||||
// Measure enemy strength
|
||||
var isEnemy = gameState.playerData.isEnemy;
|
||||
var enemyStrength = [];
|
||||
var maxStrength = 0;
|
||||
var self = this;
|
||||
|
||||
for ( var i = 1; i < isEnemy.length; i++) {
|
||||
enemyStrength[i] = 0;
|
||||
}
|
||||
|
||||
// Loop through the enemy soldiers and add the strength to that soldiers player's total strength
|
||||
this.enemySoldiers.forEach(function(ent) {
|
||||
enemyStrength[ent.owner()] += self.getUnitStrength(ent);
|
||||
|
||||
if (enemyStrength[ent.owner()] > maxStrength) {
|
||||
maxStrength = enemyStrength[ent.owner()];
|
||||
}
|
||||
});
|
||||
|
||||
return maxStrength;
|
||||
};
|
||||
|
||||
// Adds towers to the defenceBuilding queue
|
||||
MilitaryAttackManager.prototype.buildDefences = function(gameState, queues){
|
||||
if (gameState.countEntitiesAndQueuedByType(gameState.applyCiv('structures/{civ}_defense_tower'))
|
||||
+ queues.defenceBuilding.totalLength() < gameState.getBuildLimits()["DefenseTower"]) {
|
||||
|
||||
|
||||
gameState.getOwnEntities().forEach(function(dropsiteEnt) {
|
||||
if (dropsiteEnt.resourceDropsiteTypes() && dropsiteEnt.getMetadata("defenseTower") !== true){
|
||||
var position = dropsiteEnt.position();
|
||||
if (position){
|
||||
queues.defenceBuilding.addItem(new BuildingConstructionPlan(gameState, 'structures/{civ}_defense_tower', position));
|
||||
}
|
||||
dropsiteEnt.setMetadata("defenseTower", true);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
var numFortresses = 0;
|
||||
for (var i in this.bFort){
|
||||
numFortresses += gameState.countEntitiesAndQueuedByType(gameState.applyCiv(this.bFort[i]));
|
||||
}
|
||||
|
||||
if (numFortresses + queues.defenceBuilding.totalLength() < 1){ //gameState.getBuildLimits()["Fortress"]) {
|
||||
if (gameState.getTimeElapsed() > 720 * 1000 + numFortresses * 300 * 1000){
|
||||
if (gameState.ai.pathsToMe && gameState.ai.pathsToMe.length > 0){
|
||||
var position = gameState.ai.pathsToMe.shift();
|
||||
// TODO: pick a fort randomly from the list.
|
||||
queues.defenceBuilding.addItem(new BuildingConstructionPlan(gameState, this.bFort[0], position));
|
||||
}else{
|
||||
queues.defenceBuilding.addItem(new BuildingConstructionPlan(gameState, this.bFort[0]));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
MilitaryAttackManager.prototype.constructTrainingBuildings = function(gameState, queues) {
|
||||
// Build more military buildings
|
||||
// TODO: make military building better
|
||||
Engine.ProfileStart("Build buildings");
|
||||
if (gameState.countEntitiesByType(gameState.applyCiv("units/{civ}_support_female_citizen")) > 35) {
|
||||
if (gameState.countEntitiesAndQueuedByType(gameState.applyCiv(this.bModerate[0]))
|
||||
+ queues.militaryBuilding.totalLength() < 1) {
|
||||
queues.militaryBuilding.addItem(new BuildingConstructionPlan(gameState, this.bModerate[0]));
|
||||
}
|
||||
}
|
||||
//build advanced military buildings
|
||||
if (gameState.getTimeElapsed() > 720*1000){
|
||||
if (queues.militaryBuilding.totalLength() === 0){
|
||||
for (var i in this.bAdvanced){
|
||||
if (gameState.countEntitiesAndQueuedByType(gameState.applyCiv(this.bAdvanced[i])) < 1){
|
||||
queues.militaryBuilding.addItem(new BuildingConstructionPlan(gameState, this.bAdvanced[i]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Engine.ProfileStop();
|
||||
};
|
||||
|
||||
MilitaryAttackManager.prototype.trainMilitaryUnits = function(gameState, queues){
|
||||
Engine.ProfileStart("Train Units");
|
||||
// Continually try training new units, in batches of 5
|
||||
if (queues.citizenSoldier.length() < 6) {
|
||||
var newUnit = this.findBestNewUnit(gameState, queues.citizenSoldier, "citizenSoldier");
|
||||
if (newUnit){
|
||||
queues.citizenSoldier.addItem(new UnitTrainingPlan(gameState, newUnit, {
|
||||
"role" : "soldier"
|
||||
}, 5));
|
||||
}
|
||||
}
|
||||
if (queues.advancedSoldier.length() < 2) {
|
||||
var newUnit = this.findBestNewUnit(gameState, queues.advancedSoldier, "advanced");
|
||||
if (newUnit){
|
||||
queues.advancedSoldier.addItem(new UnitTrainingPlan(gameState, newUnit, {
|
||||
"role" : "soldier"
|
||||
}, 5));
|
||||
}
|
||||
}
|
||||
if (queues.siege.length() < 4) {
|
||||
var newUnit = this.findBestNewUnit(gameState, queues.siege, "siege");
|
||||
if (newUnit){
|
||||
queues.siege.addItem(new UnitTrainingPlan(gameState, newUnit, {
|
||||
"role" : "soldier"
|
||||
}, 2));
|
||||
}
|
||||
}
|
||||
Engine.ProfileStop();
|
||||
};
|
||||
MilitaryAttackManager.prototype.pausePlan = function(gameState, planName) {
|
||||
for (attackType in this.upcomingAttacks) {
|
||||
for (i in this.upcomingAttacks[attackType]) {
|
||||
var attack = this.upcomingAttacks[attackType][i];
|
||||
if (attack.getName() == planName)
|
||||
attack.setPaused(gameState, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
MilitaryAttackManager.prototype.unpausePlan = function(gameState, planName) {
|
||||
for (attackType in this.upcomingAttacks) {
|
||||
for (i in this.upcomingAttacks[attackType]) {
|
||||
var attack = this.upcomingAttacks[attackType][i];
|
||||
if (attack.getName() == planName)
|
||||
attack.setPaused(gameState, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
MilitaryAttackManager.prototype.pauseAllPlans = function(gameState) {
|
||||
for (attackType in this.upcomingAttacks) {
|
||||
for (i in this.upcomingAttacks[attackType]) {
|
||||
var attack = this.upcomingAttacks[attackType][i];
|
||||
attack.setPaused(gameState, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
MilitaryAttackManager.prototype.unpauseAllPlans = function(gameState) {
|
||||
for (attackType in this.upcomingAttacks) {
|
||||
for (i in this.upcomingAttacks[attackType]) {
|
||||
var attack = this.upcomingAttacks[attackType][i];
|
||||
attack.setPaused(gameState, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
MilitaryAttackManager.prototype.update = function(gameState, queues, events) {
|
||||
var self = this;
|
||||
|
||||
Engine.ProfileStart("military update");
|
||||
|
||||
this.gameState = gameState;
|
||||
|
||||
//this.registerSoldiers(gameState);
|
||||
|
||||
//this.trainMilitaryUnits(gameState, queues);
|
||||
|
||||
this.constructTrainingBuildings(gameState, queues);
|
||||
|
||||
this.buildDefences(gameState, queues);
|
||||
|
||||
for (watcher in this.enemyWatchers)
|
||||
this.enemyWatchers[watcher].detectArmies(gameState,this);
|
||||
this.defenceManager.update(gameState, events, this);
|
||||
|
||||
/*Engine.ProfileStart("Plan new attacks");
|
||||
// Look for attack plans which can be executed, only do this once every minute
|
||||
for (var i = 0; i < this.availableAttacks.length; i++){
|
||||
if (this.availableAttacks[i].canExecute(gameState, this)){
|
||||
this.availableAttacks[i].execute(gameState, this);
|
||||
this.currentAttacks.push(this.availableAttacks[i]);
|
||||
//debug("Attacking!");
|
||||
}
|
||||
this.availableAttacks.splice(i, 1, new this.attackManagers[i](gameState, this));
|
||||
}
|
||||
Engine.ProfileStop();
|
||||
|
||||
Engine.ProfileStart("Update attacks");
|
||||
// Keep current attacks updated
|
||||
for (var i in this.currentAttacks){
|
||||
this.currentAttacks[i].update(gameState, this, events);
|
||||
}
|
||||
Engine.ProfileStop();*/
|
||||
|
||||
Engine.ProfileStart("Looping through attack plans");
|
||||
// create plans if I'm at peace. I'm not starting plans if there is a sizable force in my realm (hence defcon 4+)
|
||||
|
||||
//if (gameState.defcon() >= 4 && this.canStartAttacks === true) {
|
||||
//if ((this.preparingNormal) == 0 && this.BuildingInfoManager.getNumberBuiltByRole("Barracks") > 0) {
|
||||
|
||||
// this will updats plans. Plans can be updated up to defcon 2, where they'll be paused (TODO)
|
||||
//if (0 == 1) // remove to activate attacks
|
||||
//if (gameState.defcon() >= 3) {
|
||||
if (1) {
|
||||
for (attackType in this.upcomingAttacks) {
|
||||
for (i in this.upcomingAttacks[attackType]) {
|
||||
|
||||
var attack = this.upcomingAttacks[attackType][i];
|
||||
|
||||
if (!attack.isPaused()) {
|
||||
// okay so we'll get the support plan
|
||||
if (!attack.isStarted()) {
|
||||
if (1) { //gameState.ai.status["underAttack"] == false) {
|
||||
var updateStep = attack.updatePreparation(gameState, this,events);
|
||||
|
||||
// now we're gonna check if the preparation time is over
|
||||
if (updateStep === 1) {
|
||||
// just chillin'
|
||||
} else if (updateStep === 0) {
|
||||
debug ("Military Manager: " +attack.getType() +" plan " +attack.getName() +" aborted.");
|
||||
attack.Abort(gameState, this);
|
||||
|
||||
//this.abortedAttacks.push(attack);
|
||||
|
||||
this.upcomingAttacks[attackType].splice(i,1);
|
||||
i--;
|
||||
} else if (updateStep === 2) {
|
||||
debug ("Military Manager: Starting " +attack.getType() +" plan " +attack.getName());
|
||||
attack.StartAttack(gameState,this);
|
||||
this.startedAttacks[attackType].push(attack);
|
||||
this.upcomingAttacks[attackType].splice(i,1);
|
||||
i--;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
debug ("Military Manager: Starting " +attack.getType() +" plan " +attack.getName());
|
||||
this.startedAttacks[attackType].push(attack);
|
||||
this.upcomingAttacks[attackType].splice(i,1);
|
||||
i--;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
//if (this.abortedAttacks.length !== 0)
|
||||
// this.abortedAttacks[gameState.ai.mainCounter % this.abortedAttacks.length].releaseAnyUnit(gameState);
|
||||
}
|
||||
for (attackType in this.startedAttacks) {
|
||||
for (i in this.startedAttacks[attackType]) {
|
||||
var attack = this.startedAttacks[attackType][i];
|
||||
// okay so then we'll update the raid.
|
||||
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.abortedAttacks.push(attack);
|
||||
this.startedAttacks[attackType].splice(i,1);
|
||||
i--;
|
||||
}
|
||||
}
|
||||
}
|
||||
// creating plans after updating because an aborted plan might be reused in that case.
|
||||
if (gameState.countEntitiesByType(gameState.applyCiv(this.bModerate[0])) >= 1) {
|
||||
if (this.upcomingAttacks["CityAttack"].length == 0) {
|
||||
var Lalala = new CityAttack(gameState, this,this.TotalAttackNumber, -1);
|
||||
debug ("Military Manager: Creating the plan " +this.TotalAttackNumber);
|
||||
this.TotalAttackNumber++;
|
||||
this.upcomingAttacks["CityAttack"].push(Lalala);
|
||||
}
|
||||
}
|
||||
/*
|
||||
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, queues.advancedSoldier)) {
|
||||
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.ProfileStart("Use idle military as workers");
|
||||
// Set unassigned to be workers TODO: fix this so it doesn't scan all units every time
|
||||
this.getUnassignedUnits(gameState).forEach(function(ent){
|
||||
if (self.getSoldierType(ent) === "citizenSoldier"){
|
||||
ent.setMetadata("role", "worker");
|
||||
}
|
||||
});
|
||||
Engine.ProfileStop();*/
|
||||
|
||||
Engine.ProfileStop();
|
||||
};
|
152
binaries/data/mods/public/simulation/ai/qbot-wc/plan-building.js
Normal file
152
binaries/data/mods/public/simulation/ai/qbot-wc/plan-building.js
Normal file
@ -0,0 +1,152 @@
|
||||
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
|
||||
|
||||
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){
|
||||
debug("No room to place " + this.type);
|
||||
return;
|
||||
}
|
||||
|
||||
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("obstructions.png");
|
||||
|
||||
obstructionMap.expandInfluences();
|
||||
|
||||
// Compute each tile's closeness to friendly structures:
|
||||
|
||||
var friendlyTiles = new Map(gameState);
|
||||
|
||||
// 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);
|
||||
//friendlyTiles.dumpIm("pos.png", 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, infl*2.0); // houses are close to other houses
|
||||
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 (ent.genericName() != "House") // houses have no influence on other buildings
|
||||
friendlyTiles.addInfluence(x, z, infl);
|
||||
// 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, Math.floor(infl/3.0), infl + 1);
|
||||
friendlyTiles.addInfluence(x, z, Math.floor(infl/4), -Math.floor(infl));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 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
|
||||
if (template.genericName() == "Field")
|
||||
var radius = Math.ceil(template.obstructionRadius() / cellSize) - 0.7;
|
||||
else if (template.buildCategory() === "Dock")
|
||||
var radius = 0;
|
||||
else if (template.genericName() != "House" && !template.hasClass("DropsiteWood") && !template.hasClass("DropsiteStone") && !template.hasClass("DropsiteMetal"))
|
||||
var radius = Math.ceil(template.obstructionRadius() / cellSize) + 2;
|
||||
else
|
||||
var radius = Math.ceil(template.obstructionRadius() / cellSize);
|
||||
|
||||
// Find the best non-obstructed tile
|
||||
var bestTile = friendlyTiles.findBestTile(radius, obstructionMap);
|
||||
var bestIdx = bestTile[0];
|
||||
var bestVal = bestTile[1];
|
||||
|
||||
if (bestVal === -1){
|
||||
return false;
|
||||
}
|
||||
|
||||
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
|
||||
};
|
||||
};
|
@ -0,0 +1,57 @@
|
||||
var UnitTrainingPlan = function(gameState, type, metadata, number) {
|
||||
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;
|
||||
}
|
||||
};
|
||||
|
||||
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 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) {
|
||||
return a.trainingQueueTime() - b.trainingQueueTime();
|
||||
});
|
||||
|
||||
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(){
|
||||
this.number += 1;
|
||||
};
|
184
binaries/data/mods/public/simulation/ai/qbot-wc/qbot.js
Normal file
184
binaries/data/mods/public/simulation/ai/qbot-wc/qbot.js
Normal file
@ -0,0 +1,184 @@
|
||||
|
||||
function QBotAI(settings) {
|
||||
BaseAI.call(this, settings);
|
||||
|
||||
this.turn = 0;
|
||||
|
||||
this.modules = {
|
||||
"economy": new EconomyManager(),
|
||||
"military": new MilitaryAttackManager(),
|
||||
"housing": new HousingManager()
|
||||
};
|
||||
|
||||
// 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(),
|
||||
field : new Queue(),
|
||||
advancedSoldier : new Queue(),
|
||||
siege : new Queue(),
|
||||
militaryBuilding : new Queue(),
|
||||
defenceBuilding : new Queue(),
|
||||
civilCentre: new Queue()
|
||||
};
|
||||
|
||||
this.productionQueues = [];
|
||||
|
||||
this.priorities = Config.priorities;
|
||||
|
||||
this.queueManager = new QueueManager(this.queues, this.priorities);
|
||||
|
||||
this.firstTime = true;
|
||||
|
||||
this.savedEvents = [];
|
||||
}
|
||||
|
||||
QBotAI.prototype = new BaseAI();
|
||||
|
||||
//Some modules need the gameState to fully initialise
|
||||
QBotAI.prototype.runInit = function(gameState){
|
||||
if (this.firstTime){
|
||||
for (var i in this.modules){
|
||||
if (this.modules[i].init){
|
||||
this.modules[i].init(gameState);
|
||||
}
|
||||
}
|
||||
|
||||
this.timer = new Timer();
|
||||
|
||||
this.firstTime = false;
|
||||
|
||||
var myKeyEntities = gameState.getOwnEntities().filter(function(ent) {
|
||||
return ent.hasClass("CivCentre");
|
||||
});
|
||||
|
||||
if (myKeyEntities.length == 0){
|
||||
myKeyEntities = gameState.getOwnEntities();
|
||||
}
|
||||
|
||||
|
||||
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());
|
||||
|
||||
if (enemyKeyEntities.length == 0)
|
||||
return;
|
||||
|
||||
var pathFinder = new PathFinder(gameState);
|
||||
this.pathsToMe = pathFinder.getPaths(enemyKeyEntities.toEntityArray()[0].position(), myKeyEntities.toEntityArray()[0].position(), 'entryPoints');
|
||||
|
||||
this.templateManager = new TemplateManager(gameState);
|
||||
|
||||
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
QBotAI.prototype.OnUpdate = function() {
|
||||
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
|
||||
if ((this.turn + this.player) % 10 == 0) {
|
||||
Engine.ProfileStart("qBot");
|
||||
|
||||
var gameState = new GameState(this);
|
||||
|
||||
if (gameState.getOwnEntities().length === 0){
|
||||
Engine.ProfileStop();
|
||||
return; // With no entities to control the AI cannot do anything
|
||||
}
|
||||
|
||||
this.runInit(gameState);
|
||||
|
||||
for (var i in this.modules){
|
||||
this.modules[i].update(gameState, this.queues, this.savedEvents);
|
||||
}
|
||||
|
||||
this.updateDynamicPriorities(gameState, this.queues);
|
||||
|
||||
this.queueManager.update(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.updateDynamicPriorities = function(gameState, queues){
|
||||
// Dynamically change priorities
|
||||
Engine.ProfileStart("Change Priorities");
|
||||
var females = gameState.countEntitiesByType(gameState.applyCiv("units/{civ}_support_female_citizen"));
|
||||
var femalesTarget = this.modules["economy"].targetNumWorkers;
|
||||
var enemyStrength = this.modules["military"].measureEnemyStrength(gameState);
|
||||
var availableStrength = this.modules["military"].measureAvailableStrength();
|
||||
|
||||
var additionalPriority = (enemyStrength - availableStrength) * 5;
|
||||
additionalPriority = Math.min(Math.max(additionalPriority, -50), 220);
|
||||
|
||||
var advancedProportion = (availableStrength / 40) * (females/femalesTarget);
|
||||
advancedProportion = Math.min(advancedProportion, 0.7);
|
||||
|
||||
this.priorities.advancedSoldier = advancedProportion * (150 + additionalPriority) + 1;
|
||||
|
||||
if (females/femalesTarget > 0.7){
|
||||
this.priorities.defenceBuilding = 70;
|
||||
}
|
||||
Engine.ProfileStop();
|
||||
};
|
||||
|
||||
// TODO: Remove override when the whole AI state is serialised
|
||||
QBotAI.prototype.Deserialize = function(data)
|
||||
{
|
||||
BaseAI.prototype.Deserialize.call(this, data);
|
||||
};
|
||||
|
||||
// Override the default serializer
|
||||
QBotAI.prototype.Serialize = function()
|
||||
{
|
||||
var ret = BaseAI.prototype.Serialize.call(this);
|
||||
ret._entityMetadata = {};
|
||||
return ret;
|
||||
};
|
||||
|
||||
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];
|
||||
}
|
||||
}
|
338
binaries/data/mods/public/simulation/ai/qbot-wc/queue-manager.js
Normal file
338
binaries/data/mods/public/simulation/ai/qbot-wc/queue-manager.js
Normal file
@ -0,0 +1,338 @@
|
||||
//This takes the input queues and picks which items to fund with resources until no more resources are left to distribute.
|
||||
//
|
||||
//In this manager all resources are 'flattened' into a single type=(food+wood+metal+stone+pop*50 (see resources.js))
|
||||
//the following refers to this simple as resource
|
||||
//
|
||||
// Each queue has an account which records the amount of resource it can spend. If no queue has an affordable item
|
||||
// then the amount of resource is increased to all accounts in direct proportion to the priority until an item on one
|
||||
// of the queues becomes affordable.
|
||||
//
|
||||
// A consequence of the system is that a rarely used queue will end up with a very large account. I am unsure if this
|
||||
// is good or bad or neither.
|
||||
//
|
||||
// Each queue object has two queues in it, one with items waiting for resources and the other with items which have been
|
||||
// allocated resources and are due to be executed. The secondary queues are helpful because then units can be trained
|
||||
// in groups of 5 and buildings are built once per turn to avoid placement clashes.
|
||||
|
||||
var QueueManager = function(queues, priorities) {
|
||||
this.queues = queues;
|
||||
this.priorities = priorities;
|
||||
this.account = {};
|
||||
for (var p in this.queues) {
|
||||
this.account[p] = 0;
|
||||
}
|
||||
this.curItemQueue = [];
|
||||
};
|
||||
|
||||
QueueManager.prototype.getAvailableResources = function(gameState) {
|
||||
var resources = gameState.getResources();
|
||||
for (var key in this.queues) {
|
||||
resources.subtract(this.queues[key].outQueueCost());
|
||||
}
|
||||
return resources;
|
||||
};
|
||||
|
||||
QueueManager.prototype.futureNeeds = function(gameState, onlyNeeds) {
|
||||
// Work out which plans will be executed next using priority and return the total cost of these plans
|
||||
var recurse = function(queues, qm, number, depth){
|
||||
var needs = new Resources();
|
||||
var totalPriority = 0;
|
||||
for (var i = 0; i < queues.length; i++){
|
||||
totalPriority += qm.priorities[queues[i]];
|
||||
}
|
||||
for (var i = 0; i < queues.length; i++){
|
||||
var num = Math.round(((qm.priorities[queues[i]]/totalPriority) * number));
|
||||
if (num < qm.queues[queues[i]].countQueuedUnits()){
|
||||
var cnt = 0;
|
||||
for ( var j = 0; cnt < num; j++) {
|
||||
cnt += qm.queues[queues[i]].queue[j].number;
|
||||
needs.add(qm.queues[queues[i]].queue[j].getCost());
|
||||
number -= qm.queues[queues[i]].queue[j].number;
|
||||
}
|
||||
}else{
|
||||
for ( var j = 0; j < qm.queues[queues[i]].length(); j++) {
|
||||
needs.add(qm.queues[queues[i]].queue[j].getCost());
|
||||
number -= qm.queues[queues[i]].queue[j].number;
|
||||
}
|
||||
queues.splice(i, 1);
|
||||
i--;
|
||||
}
|
||||
}
|
||||
// Check that more items were selected this call and that there are plans left to be allocated
|
||||
// Also there is a fail-safe max depth
|
||||
if (queues.length > 0 && number > 0 && depth < 20){
|
||||
needs.add(recurse(queues, qm, number, depth + 1));
|
||||
}
|
||||
return needs;
|
||||
};
|
||||
|
||||
//number of plans to look at
|
||||
var current = this.getAvailableResources(gameState);
|
||||
|
||||
var futureNum = 20;
|
||||
var queues = [];
|
||||
for (var q in this.queues){
|
||||
queues.push(q);
|
||||
}
|
||||
var needs = recurse(queues, this, futureNum, 0);
|
||||
|
||||
if (onlyNeeds) {
|
||||
return {
|
||||
"food" : Math.max(needs.food - current.food, 0),
|
||||
"wood" : Math.max(needs.wood + 15*needs.population - current.wood, 0),
|
||||
"stone" : Math.max(needs.stone - current.stone, 0),
|
||||
"metal" : Math.max(needs.metal - current.metal, 0)
|
||||
};
|
||||
} else if (gameState.getTimeElapsed() > 300*1000) {
|
||||
// Return predicted values minus the current stockpiles along with a base rater for all resources
|
||||
return {
|
||||
"food" : Math.max(needs.food - current.food, 0) + 150,
|
||||
"wood" : Math.max(needs.wood + 15*needs.population - current.wood, 0) + 150, //TODO: read the house cost in case it changes in the future
|
||||
"stone" : Math.max(needs.stone - current.stone, 0) + 50,
|
||||
"metal" : Math.max(needs.metal - current.metal, 0) + 100
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
"food" : Math.max(needs.food - current.food, 0) + 150,
|
||||
"wood" : Math.max(needs.wood + 15*needs.population - current.wood, 0) + 150, //TODO: read the house cost in case it changes in the future
|
||||
"stone" : Math.max(needs.stone - current.stone, 0),
|
||||
"metal" : Math.max(needs.metal - current.metal, 0)
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
// runs through the curItemQueue and allocates resources be sending the
|
||||
// affordable plans to the Out Queues. Returns a list of the unneeded resources
|
||||
// so they can be used by lower priority plans.
|
||||
QueueManager.prototype.affordableToOutQueue = function(gameState) {
|
||||
var availableRes = this.getAvailableResources(gameState);
|
||||
if (this.curItemQueue.length === 0) {
|
||||
return availableRes;
|
||||
}
|
||||
|
||||
var resources = this.getAvailableResources(gameState);
|
||||
|
||||
// Check everything in the curItemQueue, if it is affordable then mark it
|
||||
// for execution
|
||||
for ( var i = 0; i < this.curItemQueue.length; i++) {
|
||||
availableRes.subtract(this.queues[this.curItemQueue[i]].getNext().getCost());
|
||||
if (resources.canAfford(this.queues[this.curItemQueue[i]].getNext().getCost())) {
|
||||
this.account[this.curItemQueue[i]] -= this.queues[this.curItemQueue[i]].getNext().getCost().toInt();
|
||||
this.queues[this.curItemQueue[i]].nextToOutQueue();
|
||||
resources = this.getAvailableResources(gameState);
|
||||
this.curItemQueue[i] = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Clear the spent items
|
||||
var tmpQueue = [];
|
||||
for ( var i = 0; i < this.curItemQueue.length; i++) {
|
||||
if (this.curItemQueue[i] !== null) {
|
||||
tmpQueue.push(this.curItemQueue[i]);
|
||||
}
|
||||
}
|
||||
this.curItemQueue = tmpQueue;
|
||||
|
||||
return availableRes;
|
||||
};
|
||||
|
||||
QueueManager.prototype.onlyUsesSpareAndUpdateSpare = function(unitCost, spare){
|
||||
// This allows plans to be given resources if there are >500 spare after all the
|
||||
// higher priority plan queues have been looked at and there are still enough resources
|
||||
// We make it >0 so that even if we have no stone available we can still have non stone
|
||||
// plans being given resources.
|
||||
var spareNonNegRes = {
|
||||
food: Math.max(0, spare.food - 500),
|
||||
wood: Math.max(0, spare.wood - 500),
|
||||
stone: Math.max(0, spare.stone - 500),
|
||||
metal: Math.max(0, spare.metal - 500)
|
||||
};
|
||||
var spareNonNeg = new Resources(spareNonNegRes);
|
||||
var ret = false;
|
||||
if (spareNonNeg.canAfford(unitCost)){
|
||||
ret = true;
|
||||
}
|
||||
|
||||
// If there are no negative resources then there weren't any higher priority items so we
|
||||
// definitely want to say that this can be added to the list.
|
||||
var tmp = true;
|
||||
for (key in spare.types){
|
||||
var type = spare.types[key];
|
||||
if (spare[type] < 0){
|
||||
tmp = false;
|
||||
}
|
||||
}
|
||||
// If either to the above sections returns true then
|
||||
ret = ret || tmp;
|
||||
|
||||
spare.subtract(unitCost); // take the resources of the current unit from spare since this
|
||||
// must be higher priority than any which are looked at
|
||||
// afterwards.
|
||||
|
||||
return ret;
|
||||
};
|
||||
|
||||
String.prototype.rpad = function(padString, length) {
|
||||
var str = this;
|
||||
while (str.length < length)
|
||||
str = str + padString;
|
||||
return str;
|
||||
};
|
||||
|
||||
QueueManager.prototype.printQueues = function(gameState){
|
||||
debug("OUTQUEUES");
|
||||
for (var i in this.queues){
|
||||
var qStr = "";
|
||||
var q = this.queues[i];
|
||||
for (var j in q.outQueue){
|
||||
qStr += q.outQueue[j].type + " ";
|
||||
if (q.outQueue[j].number)
|
||||
qStr += "x" + q.outQueue[j].number;
|
||||
}
|
||||
if (qStr != ""){
|
||||
debug((i + ":").rpad(" ", 20) + qStr);
|
||||
}
|
||||
}
|
||||
|
||||
debug("INQUEUES");
|
||||
for (var i in this.queues){
|
||||
var qStr = "";
|
||||
var q = this.queues[i];
|
||||
for (var j in q.queue){
|
||||
qStr += q.queue[j].type + " ";
|
||||
if (q.queue[j].number)
|
||||
qStr += "x" + q.queue[j].number;
|
||||
qStr += " ";
|
||||
}
|
||||
if (qStr != ""){
|
||||
debug((i + ":").rpad(" ", 20) + qStr);
|
||||
}
|
||||
}
|
||||
debug("Accounts: " + uneval(this.account));
|
||||
debug("Needed Resources:" + uneval(this.futureNeeds(gameState)));
|
||||
};
|
||||
|
||||
QueueManager.prototype.update = function(gameState) {
|
||||
|
||||
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");
|
||||
//this.printQueues(gameState);
|
||||
|
||||
Engine.ProfileStart("Pick items from queues");
|
||||
// See if there is a high priority item from last time.
|
||||
this.affordableToOutQueue(gameState);
|
||||
do {
|
||||
// pick out all affordable items, and list the ratios of (needed
|
||||
// cost)/priority for unaffordable items.
|
||||
var ratio = {};
|
||||
var ratioMin = 1000000;
|
||||
var ratioMinQueue = undefined;
|
||||
for (var p in this.queues) {
|
||||
if (this.queues[p].length() > 0 && this.curItemQueue.indexOf(p) === -1) {
|
||||
var cost = this.queues[p].getNext().getCost().toInt();
|
||||
if (cost < this.account[p]) {
|
||||
this.curItemQueue.push(p);
|
||||
// break;
|
||||
} else {
|
||||
ratio[p] = (cost - this.account[p]) / this.priorities[p];
|
||||
if (ratio[p] < ratioMin) {
|
||||
ratioMin = ratio[p];
|
||||
ratioMinQueue = p;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Checks to see that there is an item in at least one queue, otherwise
|
||||
// breaks the loop.
|
||||
if (this.curItemQueue.length === 0 && ratioMinQueue === undefined) {
|
||||
break;
|
||||
}
|
||||
|
||||
var availableRes = this.affordableToOutQueue(gameState);
|
||||
|
||||
var allSpare = availableRes["food"] > 0 && availableRes["wood"] > 0 && availableRes["stone"] > 0 && availableRes["metal"] > 0;
|
||||
// if there are no affordable items use any resources which aren't
|
||||
// wanted by a higher priority item
|
||||
if ((availableRes["food"] > 0 || availableRes["wood"] > 0 || availableRes["stone"] > 0 || availableRes["metal"] > 0)
|
||||
&& ratioMinQueue !== undefined) {
|
||||
while (Object.keys(ratio).length > 0 && (availableRes["food"] > 0 || availableRes["wood"] > 0 || availableRes["stone"] > 0 || availableRes["metal"] > 0)){
|
||||
ratioMin = Math.min(); //biggest value
|
||||
for (var key in ratio){
|
||||
if (ratio[key] < ratioMin){
|
||||
ratioMin = ratio[key];
|
||||
ratioMinQueue = key;
|
||||
}
|
||||
}
|
||||
if (this.onlyUsesSpareAndUpdateSpare(this.queues[ratioMinQueue].getNext().getCost(), availableRes)){
|
||||
if (allSpare){
|
||||
for (var p in this.queues) {
|
||||
this.account[p] += ratioMin * this.priorities[p];
|
||||
}
|
||||
}
|
||||
//this.account[ratioMinQueue] -= this.queues[ratioMinQueue].getNext().getCost().toInt();
|
||||
this.curItemQueue.push(ratioMinQueue);
|
||||
allSpare = availableRes["food"] > 0 && availableRes["wood"] > 0 && availableRes["stone"] > 0 && availableRes["metal"] > 0;
|
||||
}
|
||||
delete ratio[ratioMinQueue];
|
||||
}
|
||||
|
||||
}
|
||||
this.affordableToOutQueue(gameState);
|
||||
} while (this.curItemQueue.length === 0);
|
||||
Engine.ProfileStop();
|
||||
|
||||
Engine.ProfileStart("Execute items");
|
||||
|
||||
// Handle output queues by executing items where possible
|
||||
for (var p in this.queues) {
|
||||
while (this.queues[p].outQueueLength() > 0) {
|
||||
var next = this.queues[p].outQueueNext();
|
||||
if (next.category === "building") {
|
||||
if (gameState.buildingsBuilt == 0) {
|
||||
if (this.queues[p].outQueueNext().canExecute(gameState)) {
|
||||
this.queues[p].executeNext(gameState);
|
||||
gameState.buildingsBuilt += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
if (this.queues[p].outQueueNext().canExecute(gameState)){
|
||||
this.queues[p].executeNext(gameState);
|
||||
}else{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
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];
|
||||
}
|
||||
}
|
||||
|
126
binaries/data/mods/public/simulation/ai/qbot-wc/queue.js
Normal file
126
binaries/data/mods/public/simulation/ai/qbot-wc/queue.js
Normal file
@ -0,0 +1,126 @@
|
||||
/*
|
||||
* Holds a list of wanted items to train or construct
|
||||
*/
|
||||
|
||||
var Queue = function() {
|
||||
this.queue = [];
|
||||
this.outQueue = [];
|
||||
};
|
||||
|
||||
Queue.prototype.addItem = function(plan) {
|
||||
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.nextToOutQueue = function(){
|
||||
if (this.queue.length > 0){
|
||||
if (this.outQueue.length > 0 &&
|
||||
this.getNext().category === "unit" &&
|
||||
this.outQueue[this.outQueue.length-1].type === this.getNext().type &&
|
||||
this.outQueue[this.outQueue.length-1].number < 5){
|
||||
this.queue.shift();
|
||||
this.outQueue[this.outQueue.length-1].addItem();
|
||||
}else{
|
||||
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.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;
|
||||
};
|
@ -0,0 +1,8 @@
|
||||
This is an AI for 0 A.D. (http://wildfiregames.com/0ad/) based on the testBot.
|
||||
|
||||
Install by placing the files into the data/mods/public/simulation/ai/qbot folder.
|
||||
|
||||
If you are developing you might find it helpful to change the debugOn line in qBot.js. This will make it spew random warnings depending on what I have been working on. Use the debug() function to make your own warnings.
|
||||
|
||||
Addendum for the experimental version: this is the regular qBot, with improvements here and there. It's "experimental" as it is currently in "test" phase, and if it proves to work and be more efficient than the normal qBot, will replace it in the next alpha. Please report any error to the wildfire games forum ( http://www.wildfiregames.com/forum/index.php?act=idx ), thanks for playing the bot!
|
||||
(note:debug is activated by default on this one. Deactivate it in the config file.)
|
66
binaries/data/mods/public/simulation/ai/qbot-wc/resources.js
Normal file
66
binaries/data/mods/public/simulation/ai/qbot-wc/resources.js
Normal file
@ -0,0 +1,66 @@
|
||||
function Resources(amounts, population) {
|
||||
if (amounts === undefined) {
|
||||
amounts = {
|
||||
food : 0,
|
||||
wood : 0,
|
||||
stone : 0,
|
||||
metal : 0
|
||||
};
|
||||
}
|
||||
for ( var tKey in this.types) {
|
||||
var t = this.types[tKey];
|
||||
this[t] = amounts[t] || 0;
|
||||
}
|
||||
|
||||
if (population > 0) {
|
||||
this.population = parseInt(population);
|
||||
} else {
|
||||
this.population = 0;
|
||||
}
|
||||
}
|
||||
|
||||
Resources.prototype.types = [ "food", "wood", "stone", "metal" ];
|
||||
|
||||
Resources.prototype.canAfford = function(that) {
|
||||
for ( var tKey in this.types) {
|
||||
var t = this.types[tKey];
|
||||
if (this[t] < that[t]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
Resources.prototype.add = function(that) {
|
||||
for ( var tKey in this.types) {
|
||||
var t = this.types[tKey];
|
||||
this[t] += that[t];
|
||||
}
|
||||
this.population += that.population;
|
||||
};
|
||||
|
||||
Resources.prototype.subtract = function(that) {
|
||||
for ( var tKey in this.types) {
|
||||
var t = this.types[tKey];
|
||||
this[t] -= that[t];
|
||||
}
|
||||
this.population += that.population;
|
||||
};
|
||||
|
||||
Resources.prototype.multiply = function(n) {
|
||||
for ( var tKey in this.types) {
|
||||
var t = this.types[tKey];
|
||||
this[t] *= n;
|
||||
}
|
||||
this.population *= n;
|
||||
};
|
||||
|
||||
Resources.prototype.toInt = function() {
|
||||
var sum = 0;
|
||||
for ( var tKey in this.types) {
|
||||
var t = this.types[tKey];
|
||||
sum += this[t];
|
||||
}
|
||||
sum += this.population * 50; // based on typical unit costs
|
||||
return sum;
|
||||
};
|
76
binaries/data/mods/public/simulation/ai/qbot-wc/template-manager.js
Executable file
76
binaries/data/mods/public/simulation/ai/qbot-wc/template-manager.js
Executable file
@ -0,0 +1,76 @@
|
||||
/*
|
||||
* Used to know which templates I have, which templates I know I can train, things like that.
|
||||
*/
|
||||
|
||||
var TemplateManager = function(gameState) {
|
||||
var self = this;
|
||||
|
||||
this.knownTemplatesList = [];
|
||||
this.buildingTemplates = [];
|
||||
this.unitTemplates = [];
|
||||
|
||||
// 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.
|
||||
|
||||
};
|
||||
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 (templateName in this.knownTemplatesList) {
|
||||
var template = gameState.getTemplate(templateName);
|
||||
if (template !== null) {
|
||||
var buildable = template.buildableEntities();
|
||||
if (buildable !== undefined)
|
||||
for each (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 (templateName in this.knownTemplatesList) {
|
||||
var template = gameState.getTemplate(templateName);
|
||||
if (template !== null) {
|
||||
var trainables = template.trainableEntities();
|
||||
if (trainables !== undefined)
|
||||
for each (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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,350 @@
|
||||
/*
|
||||
* TerrainAnalysis inherits from Map
|
||||
*
|
||||
* This creates a suitable passability map for pathfinding units and provides the findClosestPassablePoint() function.
|
||||
* This is intended to be a base object for the terrain analysis modules to inherit from.
|
||||
*/
|
||||
|
||||
function TerrainAnalysis(gameState){
|
||||
var passabilityMap = gameState.getMap();
|
||||
|
||||
var obstructionMask = gameState.getPassabilityClassMask("pathfinderObstruction");
|
||||
obstructionMask |= gameState.getPassabilityClassMask("default");
|
||||
|
||||
var obstructionTiles = new Uint16Array(passabilityMap.data.length);
|
||||
for (var i = 0; i < passabilityMap.data.length; ++i)
|
||||
{
|
||||
obstructionTiles[i] = (passabilityMap.data[i] & obstructionMask) ? 0 : 65535;
|
||||
}
|
||||
|
||||
this.Map(gameState, obstructionTiles);
|
||||
};
|
||||
|
||||
copyPrototype(TerrainAnalysis, Map);
|
||||
|
||||
// Returns the (approximately) closest point which is passable by searching in a spiral pattern
|
||||
TerrainAnalysis.prototype.findClosestPassablePoint = function(startPoint, quick, limitDistance){
|
||||
var w = this.width;
|
||||
var p = startPoint;
|
||||
var direction = 1;
|
||||
|
||||
if (p[0] + w*p[1] > 0 && p[0] + w*p[1] < this.length &&
|
||||
this.map[p[0] + w*p[1]] != 0){
|
||||
if (this.countConnected(p, 10) >= 10){
|
||||
return p;
|
||||
}
|
||||
}
|
||||
|
||||
var count = 0;
|
||||
// search in a spiral pattern.
|
||||
for (var i = 1; i < w; i++){
|
||||
for (var j = 0; j < 2; j++){
|
||||
for (var k = 0; k < i; k++){
|
||||
p[j] += direction;
|
||||
if (p[0] + w*p[1] > 0 && p[0] + w*p[1] < this.length &&
|
||||
this.map[p[0] + w*p[1]] != 0){
|
||||
if (quick || this.countConnected(p, 10) >= 10){
|
||||
return p;
|
||||
}
|
||||
}
|
||||
if (limitDistance && count > 40){
|
||||
return undefined;
|
||||
}
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
direction *= -1;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
};
|
||||
|
||||
// Counts how many accessible tiles there are connected to the start Point. If there are >= maxCount then it stops.
|
||||
// This is inefficient for large areas so maxCount should be kept small for efficiency.
|
||||
TerrainAnalysis.prototype.countConnected = function(startPoint, maxCount, curCount, checked){
|
||||
curCount = curCount || 0;
|
||||
checked = checked || [];
|
||||
|
||||
var w = this.width;
|
||||
|
||||
var positions = [[0,1], [0,-1], [1,0], [-1,0]];
|
||||
|
||||
curCount += 1; // add 1 for the current point
|
||||
checked.push(startPoint);
|
||||
if (curCount >= maxCount){
|
||||
return curCount;
|
||||
}
|
||||
|
||||
for (var i in positions){
|
||||
var p = [startPoint[0] + positions[i][0], startPoint[1] + positions[i][1]];
|
||||
if (p[0] + w*p[1] > 0 && p[0] + w*p[1] < this.length &&
|
||||
this.map[p[0] + w*p[1]] != 0 && !(p in checked)){
|
||||
curCount += this.countConnected(p, maxCount, curCount, checked);
|
||||
}
|
||||
}
|
||||
return curCount;
|
||||
};
|
||||
|
||||
/*
|
||||
* PathFinder inherits from TerrainAnalysis
|
||||
*
|
||||
* Used to create a list of distinct paths between two points.
|
||||
*
|
||||
* Currently it works with a basic implementation which should be improved.
|
||||
*
|
||||
* TODO: Make this use territories.
|
||||
*/
|
||||
|
||||
|
||||
function PathFinder(gameState){
|
||||
this.TerrainAnalysis(gameState);
|
||||
}
|
||||
|
||||
copyPrototype(PathFinder, TerrainAnalysis);
|
||||
|
||||
/*
|
||||
* Returns a list of distinct paths to the destination. Currently paths are distinct if they are more than
|
||||
* blockRadius apart at a distance of blockPlacementRadius from the destination. Where blockRadius and
|
||||
* blockPlacementRadius are defined in walkGradient
|
||||
*/
|
||||
PathFinder.prototype.getPaths = function(start, end, mode){
|
||||
var s = this.findClosestPassablePoint(this.gamePosToMapPos(start));
|
||||
var e = this.findClosestPassablePoint(this.gamePosToMapPos(end));
|
||||
|
||||
if (!s || !e){
|
||||
return undefined;
|
||||
}
|
||||
|
||||
var paths = [];
|
||||
while (true){
|
||||
this.makeGradient(s,e);
|
||||
var curPath = this.walkGradient(e, mode);
|
||||
|
||||
if (curPath !== undefined){
|
||||
paths.push(curPath);
|
||||
}else{
|
||||
break;
|
||||
}
|
||||
|
||||
this.wipeGradient();
|
||||
}
|
||||
|
||||
//this.dumpIm("terrainanalysis.png", 511);
|
||||
|
||||
if (paths.length > 0){
|
||||
return paths;
|
||||
}else{
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
// Creates a potential gradient with the start point having the lowest potential
|
||||
PathFinder.prototype.makeGradient = function(start, end){
|
||||
var w = this.width;
|
||||
var map = this.map;
|
||||
|
||||
// Holds the list of current points to work outwards from
|
||||
var stack = [];
|
||||
// We store the next level in its own stack
|
||||
var newStack = [];
|
||||
// Relative positions or new cells from the current one. We alternate between the adjacent 4 and 8 cells
|
||||
// so that there is an average 1.5 distance for diagonals which is close to the actual sqrt(2) ~ 1.41
|
||||
var positions = [[[0,1], [0,-1], [1,0], [-1,0]],
|
||||
[[0,1], [0,-1], [1,0], [-1,0], [1,1], [-1,-1], [1,-1], [-1,1]]];
|
||||
|
||||
//Set the distance of the start point to be 1 to distinguish it from the impassable areas
|
||||
map[start[0] + w*(start[1])] = 1;
|
||||
stack.push(start);
|
||||
|
||||
// while there are new points being added to the stack
|
||||
while (stack.length > 0){
|
||||
//run through the current stack
|
||||
while (stack.length > 0){
|
||||
var cur = stack.pop();
|
||||
// stop when we reach the end point
|
||||
if (cur[0] == end[0] && cur[1] == end[1]){
|
||||
return;
|
||||
}
|
||||
|
||||
var dist = map[cur[0] + w*(cur[1])] + 1;
|
||||
// Check the positions adjacent to the current cell
|
||||
for (var i = 0; i < positions[dist % 2].length; i++){
|
||||
var pos = positions[dist % 2][i];
|
||||
var cell = cur[0]+pos[0] + w*(cur[1]+pos[1]);
|
||||
if (cell >= 0 && cell < this.length && map[cell] > dist){
|
||||
map[cell] = dist;
|
||||
newStack.push([cur[0]+pos[0], cur[1]+pos[1]]);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Replace the old empty stack with the newly filled one.
|
||||
stack = newStack;
|
||||
newStack = [];
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
// Clears the map to just have the obstructions marked on it.
|
||||
PathFinder.prototype.wipeGradient = function(){
|
||||
for (var i = 0; i < this.length; i++){
|
||||
if (this.map[i] > 0){
|
||||
this.map[i] = 65535;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Returns the path down a gradient from the start to the bottom of the gradient, returns a point for every 20 cells in normal mode
|
||||
// in entryPoints mode this returns the point where the path enters the region near the destination, currently defined
|
||||
// by blockPlacementRadius. Note doesn't return a path when the destination is within the blockpoint radius.
|
||||
PathFinder.prototype.walkGradient = function(start, mode){
|
||||
var positions = [[0,1], [0,-1], [1,0], [-1,0], [1,1], [-1,-1], [1,-1], [-1,1]];
|
||||
|
||||
var path = [[start[0]*this.cellSize, start[1]*this.cellSize]];
|
||||
|
||||
var blockPoint = undefined;
|
||||
var blockPlacementRadius = 45;
|
||||
var blockRadius = 23;
|
||||
var count = 0;
|
||||
|
||||
var cur = start;
|
||||
var w = this.width;
|
||||
var dist = this.map[cur[0] + w*cur[1]];
|
||||
var moved = false;
|
||||
while (this.map[cur[0] + w*cur[1]] !== 0){
|
||||
for (var i = 0; i < positions.length; i++){
|
||||
var pos = positions[i];
|
||||
var cell = cur[0]+pos[0] + w*(cur[1]+pos[1]);
|
||||
if (cell >= 0 && cell < this.length && this.map[cell] > 0 && this.map[cell] < dist){
|
||||
dist = this.map[cell];
|
||||
cur = [cur[0]+pos[0], cur[1]+pos[1]];
|
||||
moved = true;
|
||||
count++;
|
||||
// Mark the point to put an obstruction at before calculating the next path
|
||||
if (count === blockPlacementRadius){
|
||||
blockPoint = cur;
|
||||
}
|
||||
// Add waypoints to the path, fairly well spaced apart.
|
||||
if (count % 40 === 0){
|
||||
path.unshift([cur[0]*this.cellSize, cur[1]*this.cellSize]);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!moved){
|
||||
break;
|
||||
}
|
||||
moved = false;
|
||||
}
|
||||
if (blockPoint === undefined){
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Add an obstruction to the map at the blockpoint so the next path will take a different route.
|
||||
this.addInfluence(blockPoint[0], blockPoint[1], blockRadius, -1000000, 'constant');
|
||||
if (mode === 'entryPoints'){
|
||||
// returns the point where the path enters the blockPlacementRadius
|
||||
return [blockPoint[0] * this.cellSize, blockPoint[1] * this.cellSize];
|
||||
}else{
|
||||
// return a path of points 20 squares apart on the route
|
||||
return path;
|
||||
}
|
||||
};
|
||||
|
||||
// Would be used to calculate the width of a chokepoint
|
||||
// NOTE: Doesn't currently work.
|
||||
PathFinder.prototype.countAttached = function(pos){
|
||||
var positions = [[0,1], [0,-1], [1,0], [-1,0]];
|
||||
var w = this.width;
|
||||
var val = this.map[pos[0] + w*pos[1]];
|
||||
|
||||
var stack = [pos];
|
||||
var used = {};
|
||||
|
||||
while (stack.length > 0){
|
||||
var cur = stack.pop();
|
||||
used[cur[0] + " " + cur[1]] = true;
|
||||
for (var i = 0; i < positions.length; i++){
|
||||
var p = positions[i];
|
||||
var cell = cur[0]+p[0] + w*(cur[1]+p[1]);
|
||||
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/*
|
||||
* Accessibility inherits from TerrainAnalysis
|
||||
*
|
||||
* Determines whether there is a path from one point to another. It is initialised with a single point (p1) and then
|
||||
* can efficiently determine if another point is reachable from p1. Initialising the object is costly so it should be
|
||||
* cached.
|
||||
*/
|
||||
|
||||
function Accessibility(gameState, location){
|
||||
this.TerrainAnalysis(gameState);
|
||||
|
||||
var start = this.findClosestPassablePoint(this.gamePosToMapPos(location));
|
||||
|
||||
// Check that the accessible region is a decent size, otherwise obstacles close to the start point can create
|
||||
// tiny accessible areas which makes the rest of the map inaceesible.
|
||||
var iterations = 0;
|
||||
while (this.floodFill(start) < 20 && iterations < 30){
|
||||
this.map[start[0] + this.width*(start[1])] = 0;
|
||||
start = this.findClosestPassablePoint(this.gamePosToMapPos(location));
|
||||
iterations += 1;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
copyPrototype(Accessibility, TerrainAnalysis);
|
||||
|
||||
// Return true if the given point is accessible from the point given when initialising the Accessibility object. #
|
||||
// If the given point is impassable the closest passable point is used.
|
||||
Accessibility.prototype.isAccessible = function(position){
|
||||
var s = this.findClosestPassablePoint(this.gamePosToMapPos(position), true, true);
|
||||
if (!s)
|
||||
return false;
|
||||
|
||||
return this.map[s[0] + this.width * s[1]] === 1;
|
||||
};
|
||||
|
||||
// fill all of the accessible areas with value 1
|
||||
Accessibility.prototype.floodFill = function(start){
|
||||
var w = this.width;
|
||||
var map = this.map;
|
||||
|
||||
// Holds the list of current points to work outwards from
|
||||
var stack = [];
|
||||
// We store new points to be added to the stack temporarily in here while we run through the current stack
|
||||
var newStack = [];
|
||||
// Relative positions or new cells from the current one.
|
||||
var positions = [[0,1], [0,-1], [1,0], [-1,0]];
|
||||
|
||||
// Set the start point to be accessible
|
||||
map[start[0] + w*(start[1])] = 1;
|
||||
stack.push(start);
|
||||
|
||||
var count = 0;
|
||||
|
||||
// while there are new points being added to the stack
|
||||
while (stack.length > 0){
|
||||
//run through the current stack
|
||||
while (stack.length > 0){
|
||||
var cur = stack.pop();
|
||||
|
||||
// Check the positions adjacent to the current cell
|
||||
for (var i = 0; i < positions.length; i++){
|
||||
var pos = positions[i];
|
||||
var cell = cur[0]+pos[0] + w*(cur[1]+pos[1]);
|
||||
if (cell >= 0 && cell < this.length && map[cell] > 1){
|
||||
map[cell] = 1;
|
||||
newStack.push([cur[0]+pos[0], cur[1]+pos[1]]);
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Replace the old empty stack with the newly filled one.
|
||||
stack = newStack;
|
||||
newStack = [];
|
||||
}
|
||||
return count;
|
||||
};
|
104
binaries/data/mods/public/simulation/ai/qbot-wc/timer.js
Normal file
104
binaries/data/mods/public/simulation/ai/qbot-wc/timer.js
Normal file
@ -0,0 +1,104 @@
|
||||
//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.
|
||||
|
||||
|
||||
//-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;
|
||||
};
|
26
binaries/data/mods/public/simulation/ai/qbot-wc/utils-extend.js
Executable file
26
binaries/data/mods/public/simulation/ai/qbot-wc/utils-extend.js
Executable file
@ -0,0 +1,26 @@
|
||||
function AssocArraytoArray(assocArray) {
|
||||
var endArray = [];
|
||||
for (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);
|
||||
}
|
85
binaries/data/mods/public/simulation/ai/qbot-wc/walkToCC.js
Normal file
85
binaries/data/mods/public/simulation/ai/qbot-wc/walkToCC.js
Normal file
@ -0,0 +1,85 @@
|
||||
var WalkToCC = function(gameState, militaryManager){
|
||||
this.minAttackSize = 20;
|
||||
this.maxAttackSize = 60;
|
||||
this.idList=[];
|
||||
};
|
||||
|
||||
// Returns true if the attack can be executed at the current time
|
||||
WalkToCC.prototype.canExecute = function(gameState, militaryManager){
|
||||
var enemyStrength = militaryManager.measureEnemyStrength(gameState);
|
||||
var enemyCount = militaryManager.measureEnemyCount(gameState);
|
||||
|
||||
// We require our army to be >= this strength
|
||||
var targetStrength = enemyStrength * 1.5;
|
||||
|
||||
var availableCount = militaryManager.countAvailableUnits();
|
||||
var availableStrength = militaryManager.measureAvailableStrength();
|
||||
|
||||
debug("Troops needed for attack: " + this.minAttackSize + " Have: " + availableCount);
|
||||
debug("Troops strength for attack: " + targetStrength + " Have: " + availableStrength);
|
||||
|
||||
return ((availableStrength >= targetStrength && availableCount >= this.minAttackSize)
|
||||
|| availableCount >= this.maxAttackSize);
|
||||
};
|
||||
|
||||
// Executes the attack plan, after this is executed the update function will be run every turn
|
||||
WalkToCC.prototype.execute = function(gameState, militaryManager){
|
||||
var availableCount = militaryManager.countAvailableUnits();
|
||||
this.idList = militaryManager.getAvailableUnits(availableCount);
|
||||
|
||||
var pending = EntityCollectionFromIds(gameState, this.idList);
|
||||
|
||||
// Find the critical enemy buildings we could attack
|
||||
var targets = militaryManager.getEnemyBuildings(gameState,"ConquestCritical");
|
||||
// If there are no critical structures, attack anything else that's critical
|
||||
if (targets.length == 0) {
|
||||
targets = gameState.entities.filter(function(ent) {
|
||||
return (gameState.isEntityEnemy(ent) && ent.hasClass("ConquestCritical") && ent.owner() !== 0);
|
||||
});
|
||||
}
|
||||
// If there's nothing, attack anything else that's less critical
|
||||
if (targets.length == 0) {
|
||||
targets = militaryManager.getEnemyBuildings(gameState,"Town");
|
||||
}
|
||||
if (targets.length == 0) {
|
||||
targets = militaryManager.getEnemyBuildings(gameState,"Village");
|
||||
}
|
||||
|
||||
// If we have a target, move to it
|
||||
if (targets.length) {
|
||||
// Remove the pending role
|
||||
pending.forEach(function(ent) {
|
||||
ent.setMetadata("role", "attack");
|
||||
});
|
||||
|
||||
var target = targets.toEntityArray()[0];
|
||||
var targetPos = target.position();
|
||||
|
||||
// TODO: this should be an attack-move command
|
||||
pending.move(targetPos[0], targetPos[1]);
|
||||
} else if (targets.length == 0 ) {
|
||||
gameState.ai.gameFinished = true;
|
||||
}
|
||||
};
|
||||
|
||||
// Runs every turn after the attack is executed
|
||||
// This removes idle units from the attack
|
||||
WalkToCC.prototype.update = function(gameState, militaryManager){
|
||||
var removeList = [];
|
||||
for (var idKey in this.idList){
|
||||
var id = this.idList[idKey];
|
||||
var ent = militaryManager.entity(id);
|
||||
if(ent)
|
||||
{
|
||||
if(ent.isIdle()) {
|
||||
militaryManager.unassignUnit(id);
|
||||
removeList.push(id);
|
||||
}
|
||||
} else {
|
||||
removeList.push(id);
|
||||
}
|
||||
}
|
||||
for (var i in removeList){
|
||||
this.idList.splice(this.idList.indexOf(removeList[i]),1);
|
||||
}
|
||||
};
|
272
binaries/data/mods/public/simulation/ai/qbot-wc/worker.js
Normal file
272
binaries/data/mods/public/simulation/ai/qbot-wc/worker.js
Normal file
@ -0,0 +1,272 @@
|
||||
/**
|
||||
* This class makes a worker do as instructed by the economy manager
|
||||
*/
|
||||
|
||||
var Worker = function(ent) {
|
||||
this.ent = ent;
|
||||
this.approachCount = 0;
|
||||
};
|
||||
|
||||
Worker.prototype.update = function(gameState) {
|
||||
var subrole = this.ent.getMetadata("subrole");
|
||||
|
||||
if (!this.ent.position()){
|
||||
// If the worker has no position then no work can be done
|
||||
return;
|
||||
}
|
||||
|
||||
if (subrole === "gatherer"){
|
||||
if (!(this.ent.unitAIState().split(".")[1] === "GATHER" && this.ent.unitAIOrderData().type
|
||||
&& this.getResourceType(this.ent.unitAIOrderData().type) === this.ent.getMetadata("gather-type"))
|
||||
&& !(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("gather-type")){
|
||||
Engine.ProfileStart("Start Gathering");
|
||||
this.startGathering(gameState);
|
||||
Engine.ProfileStop();
|
||||
} else if (this.ent.unitAIState().split(".")[1] !== "RETURNRESOURCE") {
|
||||
// Should deposit resources
|
||||
Engine.ProfileStart("Return Resources");
|
||||
this.returnResources(gameState);
|
||||
Engine.ProfileStop();
|
||||
}
|
||||
|
||||
this.startApproachingResourceTime = gameState.getTimeElapsed();
|
||||
|
||||
//Engine.PostCommand({"type": "set-shading-color", "entities": [this.ent.id()], "rgb": [10,0,0]});
|
||||
}else{
|
||||
// If we haven't reached the resource in 2 minutes twice in a row and none of the resource has been
|
||||
// gathered then mark it as inaccessible.
|
||||
if (gameState.getTimeElapsed() - this.startApproachingResourceTime > 120000){
|
||||
if (this.gatheringFrom){
|
||||
var ent = gameState.getEntityById(this.gatheringFrom);
|
||||
if (ent && ent.resourceSupplyAmount() == ent.resourceSupplyMax()){
|
||||
if (this.approachCount > 0){
|
||||
ent.setMetadata("inaccessible", true);
|
||||
this.ent.setMetadata("subrole", "idle");
|
||||
}
|
||||
this.approachCount++;
|
||||
}else{
|
||||
this.approachCount = 0;
|
||||
}
|
||||
|
||||
this.startApproachingResourceTime = gameState.getTimeElapsed();
|
||||
}
|
||||
}
|
||||
}
|
||||
}else if(subrole === "builder"){
|
||||
if (this.ent.unitAIState().split(".")[1] !== "REPAIR"){
|
||||
var target = this.ent.getMetadata("target-foundation");
|
||||
this.ent.repair(target);
|
||||
}
|
||||
|
||||
//Engine.PostCommand({"type": "set-shading-color", "entities": [this.ent.id()], "rgb": [0,10,0]});
|
||||
}
|
||||
|
||||
Engine.ProfileStart("Update Gatherer Counts");
|
||||
this.updateGathererCounts(gameState);
|
||||
Engine.ProfileStop();
|
||||
};
|
||||
|
||||
Worker.prototype.updateGathererCounts = function(gameState, dead){
|
||||
// update gatherer counts for the resources
|
||||
if (this.ent.unitAIState().split(".")[2] === "GATHERING" && !dead){
|
||||
if (this.gatheringFrom !== this.ent.unitAIOrderData().target){
|
||||
if (this.gatheringFrom){
|
||||
var ent = gameState.getEntityById(this.gatheringFrom);
|
||||
if (ent){
|
||||
ent.setMetadata("gatherer-count", ent.getMetadata("gatherer-count") - 1);
|
||||
this.markFull(ent);
|
||||
}
|
||||
}
|
||||
this.gatheringFrom = this.ent.unitAIOrderData().target;
|
||||
if (this.gatheringFrom){
|
||||
var ent = gameState.getEntityById(this.gatheringFrom);
|
||||
if (ent){
|
||||
ent.setMetadata("gatherer-count", (ent.getMetadata("gatherer-count") || 0) + 1);
|
||||
this.markFull(ent);
|
||||
}
|
||||
}
|
||||
}
|
||||
}else{
|
||||
if (this.gatheringFrom){
|
||||
var ent = gameState.getEntityById(this.gatheringFrom);
|
||||
if (ent){
|
||||
ent.setMetadata("gatherer-count", ent.getMetadata("gatherer-count") - 1);
|
||||
this.markFull(ent);
|
||||
}
|
||||
this.gatheringFrom = undefined;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Worker.prototype.markFull = function(ent){
|
||||
var maxCounts = {"food": 20, "wood": 5, "metal": 20, "stone": 20, "treasure": 1};
|
||||
if (ent.resourceSupplyType() && ent.getMetadata("gatherer-count") >= maxCounts[ent.resourceSupplyType().generic]){
|
||||
if (!ent.getMetadata("full")){
|
||||
ent.setMetadata("full", true);
|
||||
}
|
||||
}else{
|
||||
if (ent.getMetadata("full")){
|
||||
ent.setMetadata("full", false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Worker.prototype.startGathering = function(gameState){
|
||||
var resource = this.ent.getMetadata("gather-type");
|
||||
var ent = this.ent;
|
||||
|
||||
if (!ent.position()){
|
||||
// TODO: work out what to do when entity has no position
|
||||
return;
|
||||
}
|
||||
|
||||
// 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;
|
||||
|
||||
gameState.updatingCollection("active-dropsite-" + resource, Filters.byMetadata("active-dropsite-" + resource, true),
|
||||
gameState.getOwnDropsites(resource)).forEach(function (dropsite){
|
||||
if (dropsite.position()){
|
||||
var dist = SquareVectorDistance(ent.position(), dropsite.position());
|
||||
if (dist < minDropsiteDist){
|
||||
minDropsiteDist = dist;
|
||||
nearestResources = dropsite.getMetadata("nearby-resources-" + resource);
|
||||
nearestDropsite = dropsite;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (!nearestResources || nearestResources.length === 0){
|
||||
nearestResources = gameState.getResourceSupplies(resource);
|
||||
gameState.getOwnDropsites(resource).forEach(function (dropsite){
|
||||
if (dropsite.position()){
|
||||
var dist = SquareVectorDistance(ent.position(), dropsite.position());
|
||||
if (dist < minDropsiteDist){
|
||||
minDropsiteDist = dist;
|
||||
nearestDropsite = dropsite;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (nearestResources.length === 0){
|
||||
if (resource === "food" && !this.buildAnyField(gameState)) // try to go build a farm
|
||||
debug("No " + resource + " found! (1)");
|
||||
else
|
||||
debug("No " + resource + " found! (1)");
|
||||
return;
|
||||
}
|
||||
|
||||
var supplies = [];
|
||||
var nearestSupplyDist = Math.min();
|
||||
var nearestSupply = undefined;
|
||||
|
||||
nearestResources.forEach(function(supply) {
|
||||
// TODO: handle enemy territories
|
||||
|
||||
if (!supply.position()){
|
||||
return;
|
||||
}
|
||||
|
||||
// measure the distance to the resource
|
||||
var dist = VectorDistance(supply.position(), ent.position());
|
||||
// Add on a factor for the nearest dropsite if one exists
|
||||
if (nearestDropsite){
|
||||
dist += 5 * VectorDistance(supply.position(), nearestDropsite.position());
|
||||
}
|
||||
|
||||
// Go for treasure as a priority
|
||||
if (dist < 1000 && supply.resourceSupplyType().generic == "treasure"){
|
||||
dist /= 1000;
|
||||
}
|
||||
|
||||
if (dist < nearestSupplyDist){
|
||||
nearestSupplyDist = dist;
|
||||
nearestSupply = supply;
|
||||
}
|
||||
});
|
||||
|
||||
if (nearestSupply) {
|
||||
var pos = nearestSupply.position();
|
||||
|
||||
// if the resource is far away, try to build a farm instead.
|
||||
var tried = false;
|
||||
if (resource === "food" && SquareVectorDistance(pos,this.ent.position()) > 50000)
|
||||
tried = this.buildAnyField(gameState);
|
||||
if (!tried) {
|
||||
var territoryOwner = gameState.getTerritoryMap().getOwner(pos);
|
||||
if (!gameState.ai.accessibility.isAccessible(pos) ||
|
||||
(territoryOwner != gameState.getPlayerID() && territoryOwner != 0)){
|
||||
nearestSupply.setMetadata("inaccessible", true);
|
||||
}else{
|
||||
ent.gather(nearestSupply);
|
||||
}
|
||||
}
|
||||
}else{
|
||||
debug("No " + resource + " found! (2)");
|
||||
}
|
||||
};
|
||||
|
||||
// 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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
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 for " + resource);
|
||||
return;
|
||||
}
|
||||
|
||||
this.ent.returnResources(closestDropsite);
|
||||
};
|
||||
|
||||
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;
|
||||
};
|
Loading…
Reference in New Issue
Block a user