Fix eslint rule 'prefer-const' in petra

eslint --no-config-lookup --fix --rule '"prefer-const": 1' \
    binaries/data/mods/public/simulation/ai/petra

Ref: #7812
Signed-off-by: Ralph Sennhauser <ralph.sennhauser@gmail.com>
This commit is contained in:
Ralph Sennhauser 2025-05-09 11:16:53 +02:00
parent 6a16b18795
commit 5221b81bff
10 changed files with 317 additions and 317 deletions

View file

@ -32,15 +32,15 @@ PETRA.PetraBot.prototype.CustomInit = function(gameState)
this.playedTurn = this.data.playedTurn;
this.elapsedTime = this.data.elapsedTime;
this.savedEvents = this.data.savedEvents;
for (let key in this.savedEvents)
for (const key in this.savedEvents)
{
for (let i in this.savedEvents[key])
for (const i in this.savedEvents[key])
{
if (!this.savedEvents[key][i].entityObj)
continue;
let evt = this.savedEvents[key][i];
let evtmod = {};
for (let keyevt in evt)
const evt = this.savedEvents[key][i];
const evtmod = {};
for (const keyevt in evt)
{
evtmod[keyevt] = evt[keyevt];
evtmod.entityObj = new API3.Entity(gameState.sharedScript, evt.entityObj);
@ -72,7 +72,7 @@ PETRA.PetraBot.prototype.CustomInit = function(gameState)
// this.queues can only be modified by the queue manager or things will go awry.
this.queues = {};
for (let i in this.Config.priorities)
for (const i in this.Config.priorities)
this.queues[i] = new PETRA.Queue();
this.queueManager = new PETRA.QueueManager(this.Config, this.queues);
@ -91,7 +91,7 @@ PETRA.PetraBot.prototype.OnUpdate = function(sharedScript)
if (this.gameFinished || this.gameState.playerData.state == "defeated")
return;
for (let i in this.events)
for (const i in this.events)
{
if (i == "AIMetadata") // not used inside petra
continue;
@ -119,7 +119,7 @@ PETRA.PetraBot.prototype.OnUpdate = function(sharedScript)
this.queueManager.update(this.gameState);
for (let i in this.savedEvents)
for (const i in this.savedEvents)
this.savedEvents[i] = [];
Engine.ProfileStop();
@ -130,17 +130,17 @@ PETRA.PetraBot.prototype.OnUpdate = function(sharedScript)
PETRA.PetraBot.prototype.Serialize = function()
{
let savedEvents = {};
for (let key in this.savedEvents)
const savedEvents = {};
for (const key in this.savedEvents)
{
savedEvents[key] = this.savedEvents[key].slice();
for (let i in savedEvents[key])
for (const i in savedEvents[key])
{
if (!savedEvents[key][i] || !savedEvents[key][i].entityObj)
continue;
let evt = savedEvents[key][i];
let evtmod = {};
for (let keyevt in evt)
const evt = savedEvents[key][i];
const evtmod = {};
for (const keyevt in evt)
evtmod[keyevt] = evt[keyevt];
evtmod.entityObj = evt.entityObj._entity;
savedEvents[key][i] = evtmod;

View file

@ -16,18 +16,18 @@ PETRA.BuildManager = function()
/** Initialization at start of game */
PETRA.BuildManager.prototype.init = function(gameState)
{
let civ = gameState.getPlayerCiv();
for (let ent of gameState.getOwnUnits().values())
const civ = gameState.getPlayerCiv();
for (const ent of gameState.getOwnUnits().values())
this.incrementBuilderCounters(civ, ent, 1);
};
PETRA.BuildManager.prototype.incrementBuilderCounters = function(civ, ent, increment)
{
for (let buildable of ent.buildableEntities(civ))
for (const buildable of ent.buildableEntities(civ))
{
if (this.builderCounters.has(buildable))
{
let count = this.builderCounters.get(buildable) + increment;
const count = this.builderCounters.get(buildable) + increment;
if (count < 0)
{
API3.warn(" Petra error in incrementBuilderCounters for " + buildable + " with count < 0");
@ -46,27 +46,27 @@ PETRA.BuildManager.prototype.incrementBuilderCounters = function(civ, ent, incre
PETRA.BuildManager.prototype.checkEvents = function(gameState, events)
{
this.elapsedTime = gameState.ai.elapsedTime;
let civ = gameState.getPlayerCiv();
const civ = gameState.getPlayerCiv();
for (let evt of events.Create)
for (const evt of events.Create)
{
if (events.Destroy.some(e => e.entity == evt.entity))
continue;
let ent = gameState.getEntityById(evt.entity);
const ent = gameState.getEntityById(evt.entity);
if (ent && ent.isOwn(PlayerID) && ent.hasClass("Unit"))
this.incrementBuilderCounters(civ, ent, 1);
}
for (let evt of events.Destroy)
for (const evt of events.Destroy)
{
if (events.Create.some(e => e.entity == evt.entity) || !evt.entityObj)
continue;
let ent = evt.entityObj;
const ent = evt.entityObj;
if (ent && ent.isOwn(PlayerID) && ent.hasClass("Unit"))
this.incrementBuilderCounters(civ, ent, -1);
}
for (let evt of events.OwnershipChanged) // capture events
for (const evt of events.OwnershipChanged) // capture events
{
let increment;
if (evt.from == PlayerID)
@ -75,12 +75,12 @@ PETRA.BuildManager.prototype.checkEvents = function(gameState, events)
increment = 1;
else
continue;
let ent = gameState.getEntityById(evt.entity);
const ent = gameState.getEntityById(evt.entity);
if (ent && ent.hasClass("Unit"))
this.incrementBuilderCounters(civ, ent, increment);
}
for (let evt of events.ValueModification)
for (const evt of events.ValueModification)
{
if (evt.component != "Builder" ||
!evt.valueNames.some(val => val.startsWith("Builder/Entities/")))
@ -90,8 +90,8 @@ PETRA.BuildManager.prototype.checkEvents = function(gameState, events)
// at this stage, so we simply have to dump the cache.
this.builderCounters = new Map();
let civ = gameState.getPlayerCiv();
for (let ent of gameState.getOwnUnits().values())
const civ = gameState.getPlayerCiv();
for (const ent of gameState.getOwnUnits().values())
this.incrementBuilderCounters(civ, ent, 1);
}
};
@ -103,11 +103,11 @@ PETRA.BuildManager.prototype.checkEvents = function(gameState, events)
PETRA.BuildManager.prototype.findStructuresByFilter = function(gameState, filter)
{
const result = [];
for (let [templateName, count] of this.builderCounters)
for (const [templateName, count] of this.builderCounters)
{
if (!count || gameState.isTemplateDisabled(templateName))
continue;
let template = gameState.getTemplate(templateName);
const template = gameState.getTemplate(templateName);
if (!template || !template.available(gameState))
continue;
if (filter.func(template))
@ -127,7 +127,7 @@ PETRA.BuildManager.prototype.findStructureWithClass = function(gameState, classe
PETRA.BuildManager.prototype.hasBuilder = function(template)
{
let numBuilders = this.builderCounters.get(template);
const numBuilders = this.builderCounters.get(template);
return numBuilders && numBuilders > 0;
};
@ -149,7 +149,7 @@ PETRA.BuildManager.prototype.setUnbuildable = function(gameState, template, time
this.unbuildables.set(template, { "reason": reason, "time": gameState.ai.elapsedTime + time });
else
{
let unbuildable = this.unbuildables.get(template);
const unbuildable = this.unbuildables.get(template);
if (unbuildable.time < gameState.ai.elapsedTime + time)
{
unbuildable.reason = reason;
@ -162,7 +162,7 @@ PETRA.BuildManager.prototype.setUnbuildable = function(gameState, template, time
PETRA.BuildManager.prototype.numberMissingRoom = function(gameState)
{
let num = 0;
for (let unbuildable of this.unbuildables.values())
for (const unbuildable of this.unbuildables.values())
if (unbuildable.reason == "room" && unbuildable.time > gameState.ai.elapsedTime)
++num;
return num;
@ -171,7 +171,7 @@ PETRA.BuildManager.prototype.numberMissingRoom = function(gameState)
/** Reset the unbuildables due to missing room */
PETRA.BuildManager.prototype.resetMissingRoom = function(gameState)
{
for (let [key, unbuildable] of this.unbuildables)
for (const [key, unbuildable] of this.unbuildables)
if (unbuildable.reason == "room")
this.unbuildables.delete(key);
};
@ -186,6 +186,6 @@ PETRA.BuildManager.prototype.Serialize = function()
PETRA.BuildManager.prototype.Deserialize = function(data)
{
for (let key in data)
for (const key in data)
this[key] = data[key];
};

View file

@ -212,19 +212,19 @@ PETRA.Config.prototype.setConfig = function(gameState)
// The parameter used to define the personality is basically the aggressivity or (1-defensiveness)
// as they are anticorrelated, although some small smearing to decorelate them will be added.
// And for each user choice, this parameter can vary between min and max
let personalityList = {
const personalityList = {
"random": { "min": 0, "max": 1 },
"defensive": { "min": 0, "max": 0.27 },
"balanced": { "min": 0.37, "max": 0.63 },
"aggressive": { "min": 0.73, "max": 1 }
};
let behavior = randFloat(-0.5, 0.5);
const behavior = randFloat(-0.5, 0.5);
// make agressive and defensive quite anticorrelated (aggressive ~ 1 - defensive) but not completelety
let variation = 0.15 * randFloat(-1, 1) * Math.sqrt(Math.square(0.5) - Math.square(behavior));
let aggressive = Math.max(Math.min(behavior + variation, 0.5), -0.5) + 0.5;
let defensive = Math.max(Math.min(-behavior + variation, 0.5), -0.5) + 0.5;
let min = personalityList[this.behavior].min;
let max = personalityList[this.behavior].max;
const variation = 0.15 * randFloat(-1, 1) * Math.sqrt(Math.square(0.5) - Math.square(behavior));
const aggressive = Math.max(Math.min(behavior + variation, 0.5), -0.5) + 0.5;
const defensive = Math.max(Math.min(-behavior + variation, 0.5), -0.5) + 0.5;
const min = personalityList[this.behavior].min;
const max = personalityList[this.behavior].max;
this.personality = {
"aggressive": min + aggressive * (max - min),
"defensive": 1 - max + defensive * (max - min),
@ -282,7 +282,7 @@ PETRA.Config.prototype.setConfig = function(gameState)
}
}
let maxPop = gameState.getPopulationMax();
const maxPop = gameState.getPopulationMax();
if (this.difficulty < PETRA.DIFFICULTY_EASY)
this.Economy.targetNumWorkers = Math.max(1, Math.min(40, maxPop));
else if (this.difficulty < PETRA.DIFFICULTY_MEDIUM)
@ -345,7 +345,7 @@ PETRA.Config.prototype.Cheat = function(gameState)
PETRA.Config.prototype.Serialize = function()
{
var data = {};
for (let key in this)
for (const key in this)
if (this.hasOwnProperty(key) && key != "debug")
data[key] = this[key];
return data;
@ -353,6 +353,6 @@ PETRA.Config.prototype.Serialize = function()
PETRA.Config.prototype.Deserialize = function(data)
{
for (let key in data)
for (const key in data)
this[key] = data[key];
};

View file

@ -63,22 +63,22 @@ PETRA.DiplomacyManager.prototype.init = function(gameState)
PETRA.DiplomacyManager.prototype.tributes = function(gameState)
{
this.nextTributeUpdate = gameState.ai.elapsedTime + 30;
let resTribCodes = Resources.GetTributableCodes();
const resTribCodes = Resources.GetTributableCodes();
if (!resTribCodes.length)
return;
let totalResources = gameState.getResources();
let availableResources = gameState.ai.queueManager.getAvailableResources(gameState);
const totalResources = gameState.getResources();
const availableResources = gameState.ai.queueManager.getAvailableResources(gameState);
let mostNeeded;
for (let i = 1; i < gameState.sharedScript.playersData.length; ++i)
{
if (i === PlayerID || !gameState.isPlayerAlly(i) || gameState.ai.HQ.attackManager.defeated[i])
continue;
let donor = gameState.getAlliedVictory() || gameState.getEntities(i).length < gameState.getOwnEntities().length;
let allyResources = gameState.sharedScript.playersData[i].resourceCounts;
let allyPop = gameState.sharedScript.playersData[i].popCount;
let tribute = {};
const donor = gameState.getAlliedVictory() || gameState.getEntities(i).length < gameState.getOwnEntities().length;
const allyResources = gameState.sharedScript.playersData[i].resourceCounts;
const allyPop = gameState.sharedScript.playersData[i].popCount;
const tribute = {};
let toSend = false;
for (let res of resTribCodes)
for (const res of resTribCodes)
{
if (donor && availableResources[res] > 200 && allyResources[res] < 0.2 * availableResources[res])
{
@ -126,11 +126,11 @@ PETRA.DiplomacyManager.prototype.checkEvents = function(gameState, events)
{
// Increase slowly the cooperative personality trait either when we receive tribute from our allies
// or if our allies attack enemies inside our territory
for (let evt of events.TributeExchanged)
for (const evt of events.TributeExchanged)
{
if (evt.to === PlayerID && !gameState.isPlayerAlly(evt.from) && this.receivedDiplomacyRequests.has(evt.from))
{
let request = this.receivedDiplomacyRequests.get(evt.from);
const request = this.receivedDiplomacyRequests.get(evt.from);
if (request.status === "waitingForTribute" && request.type in evt.amounts)
{
request.wanted -= evt.amounts[request.type];
@ -155,7 +155,7 @@ PETRA.DiplomacyManager.prototype.checkEvents = function(gameState, events)
if (evt.to !== PlayerID || !gameState.isPlayerAlly(evt.from))
continue;
let tributes = 0;
for (let key in evt.amounts)
for (const key in evt.amounts)
{
if (key === "food")
tributes += evt.amounts[key];
@ -165,14 +165,14 @@ PETRA.DiplomacyManager.prototype.checkEvents = function(gameState, events)
this.Config.personality.cooperative = Math.min(1, this.Config.personality.cooperative + 0.0001 * tributes);
}
for (let evt of events.Attacked)
for (const evt of events.Attacked)
{
let target = gameState.getEntityById(evt.target);
const target = gameState.getEntityById(evt.target);
if (!target || !target.position() ||
gameState.ai.HQ.territoryMap.getOwner(target.position()) !== PlayerID ||
!gameState.isPlayerEnemy(target.owner()))
continue;
let attacker = gameState.getEntityById(evt.attacker);
const attacker = gameState.getEntityById(evt.attacker);
if (!attacker || attacker.owner() === PlayerID || !gameState.isPlayerAlly(attacker.owner()))
continue;
this.Config.personality.cooperative = Math.min(1, this.Config.personality.cooperative + 0.003);
@ -181,20 +181,20 @@ PETRA.DiplomacyManager.prototype.checkEvents = function(gameState, events)
if (events.DiplomacyChanged.length || events.PlayerDefeated.length || events.CeasefireEnded.length)
this.lastManStandingCheck(gameState);
for (let evt of events.PlayerDefeated)
for (const evt of events.PlayerDefeated)
{
this.receivedDiplomacyRequests.delete(evt.playerId);
this.sentDiplomacyRequests.delete(evt.playerId);
}
for (let evt of events.DiplomacyChanged)
for (const evt of events.DiplomacyChanged)
{
if (evt.otherPlayer !== PlayerID)
continue;
if (this.sentDiplomacyRequests.has(evt.player)) // If another player has accepted a diplomacy request we sent
{
let sentRequest = this.sentDiplomacyRequests.get(evt.player);
const sentRequest = this.sentDiplomacyRequests.get(evt.player);
if (gameState.sharedScript.playersData[evt.player].isAlly[PlayerID] && sentRequest.requestType === "ally" ||
gameState.sharedScript.playersData[evt.player].isNeutral[PlayerID] && sentRequest.requestType === "neutral")
this.changePlayerDiplomacy(gameState, evt.player, sentRequest.requestType);
@ -205,7 +205,7 @@ PETRA.DiplomacyManager.prototype.checkEvents = function(gameState, events)
continue;
}
let request = this.receivedDiplomacyRequests.get(evt.player);
const request = this.receivedDiplomacyRequests.get(evt.player);
if (request !== undefined &&
(!gameState.sharedScript.playersData[evt.player].isAlly[PlayerID] && request.requestType === "ally" ||
gameState.sharedScript.playersData[evt.player].isEnemy[PlayerID] && request.requestType === "neutral"))
@ -218,7 +218,7 @@ PETRA.DiplomacyManager.prototype.checkEvents = function(gameState, events)
}
else if (gameState.sharedScript.playersData[evt.player].isAlly[PlayerID] && gameState.isPlayerEnemy(evt.player))
{
let response = request !== undefined && (request.status === "declinedRequest" || request.status === "allianceBroken") ?
const response = request !== undefined && (request.status === "declinedRequest" || request.status === "allianceBroken") ?
"decline" : "declineSuggestNeutral";
PETRA.chatAnswerRequestDiplomacy(gameState, evt.player, "ally", response);
}
@ -229,13 +229,13 @@ PETRA.DiplomacyManager.prototype.checkEvents = function(gameState, events)
}
// These events will only be sent by other AI players
for (let evt of events.DiplomacyRequest)
for (const evt of events.DiplomacyRequest)
{
if (evt.player !== PlayerID)
continue;
this.handleDiplomacyRequest(gameState, evt.source, evt.to);
let request = this.receivedDiplomacyRequests.get(evt.source);
const request = this.receivedDiplomacyRequests.get(evt.source);
if (this.Config.debug > 0)
API3.warn("Responding to diplomacy request from AI player " + evt.source + " with " + uneval(request));
@ -253,16 +253,16 @@ PETRA.DiplomacyManager.prototype.checkEvents = function(gameState, events)
}
// An AI player we sent a diplomacy request to demanded we send them a tribute
for (let evt of events.TributeRequest)
for (const evt of events.TributeRequest)
{
if (evt.player !== PlayerID)
continue;
let availableResources = gameState.ai.queueManager.getAvailableResources(gameState);
const availableResources = gameState.ai.queueManager.getAvailableResources(gameState);
// TODO: Save this event and wait until we get more resources if we don't have enough
if (evt.resourceWanted < availableResources[evt.resourceType])
{
let responseTribute = {};
const responseTribute = {};
responseTribute[evt.resourceType] = evt.resourceWanted;
if (this.Config.debug > 0)
API3.warn("Responding to tribute request from AI player " + evt.source + " with " + uneval(responseTribute));
@ -323,10 +323,10 @@ PETRA.DiplomacyManager.prototype.lastManStandingCheck = function(gameState)
if (gameState.getVictoryConditions().has("wonder"))
{
let wonder = gameState.getEnemyStructures(i).filter(API3.Filters.byClass("Wonder"))[0];
const wonder = gameState.getEnemyStructures(i).filter(API3.Filters.byClass("Wonder"))[0];
if (wonder)
{
let wonderProgess = wonder.foundationProgress();
const wonderProgess = wonder.foundationProgress();
if (wonderProgess === undefined)
{
playerToTurnAgainst = i;
@ -338,7 +338,7 @@ PETRA.DiplomacyManager.prototype.lastManStandingCheck = function(gameState)
if (gameState.getVictoryConditions().has("capture_the_relic"))
{
let relicsCount = gameState.updatingGlobalCollection("allRelics", API3.Filters.byClass("Relic"))
const relicsCount = gameState.updatingGlobalCollection("allRelics", API3.Filters.byClass("Relic"))
.filter(relic => relic.owner() === i).length;
turnFactor += relicsCount * this.betrayWeighting;
}
@ -353,7 +353,7 @@ PETRA.DiplomacyManager.prototype.lastManStandingCheck = function(gameState)
if (playerToTurnAgainst)
{
this.changePlayerDiplomacy(gameState, playerToTurnAgainst, "enemy");
let request = this.receivedDiplomacyRequests.get(playerToTurnAgainst);
const request = this.receivedDiplomacyRequests.get(playerToTurnAgainst);
if (request && request.status !== "allianceBroken")
{
if (request.status === "waitingForTribute")
@ -377,8 +377,8 @@ PETRA.DiplomacyManager.prototype.handleDiplomacyRequest = function(gameState, pl
return;
let response;
let requiredTribute;
let request = this.receivedDiplomacyRequests.get(player);
let moreEnemiesThanAllies = gameState.getEnemies().length > gameState.getMutualAllies().length;
const request = this.receivedDiplomacyRequests.get(player);
const moreEnemiesThanAllies = gameState.getEnemies().length > gameState.getMutualAllies().length;
// For any given diplomacy request be likely to permanently decline
if (!request && gameState.getPlayerCiv() !== gameState.getPlayerCiv(player) && randBool(0.6) ||
@ -411,7 +411,7 @@ PETRA.DiplomacyManager.prototype.handleDiplomacyRequest = function(gameState, pl
// Try to request a tribute.
// If a resource is not tributable, do not request it.
// If no resources are tributable, decline.
let resTribCodes = Resources.GetTributableCodes();
const resTribCodes = Resources.GetTributableCodes();
if (resTribCodes.length)
{
requiredTribute = gameState.ai.HQ.pickMostNeededResources(gameState, resTribCodes)[0];
@ -448,7 +448,7 @@ PETRA.DiplomacyManager.prototype.changePlayerDiplomacy = function(gameState, pla
PETRA.DiplomacyManager.prototype.checkRequestedTributes = function(gameState)
{
for (let [player, data] of this.receivedDiplomacyRequests)
for (const [player, data] of this.receivedDiplomacyRequests)
if (data.status === "waitingForTribute" && gameState.ai.elapsedTime > data.warnTime)
{
if (data.sentWarning)
@ -479,7 +479,7 @@ PETRA.DiplomacyManager.prototype.sendDiplomacyRequest = function(gameState)
for (let i = 1; i < gameState.sharedScript.playersData.length; ++i)
{
let mutualEnemies = 0;
let request = this.receivedDiplomacyRequests.get(i); // Do not send to players we have already rejected before
const request = this.receivedDiplomacyRequests.get(i); // Do not send to players we have already rejected before
if (i === PlayerID || gameState.isPlayerMutualAlly(i) || gameState.ai.HQ.attackManager.defeated[i] ||
gameState.ai.HQ.attackManager.currentEnemyPlayer === i ||
this.sentDiplomacyRequests.get(i) !== undefined || request && request.status === "declinedRequest")
@ -501,7 +501,7 @@ PETRA.DiplomacyManager.prototype.sendDiplomacyRequest = function(gameState)
if (!player)
return;
let requestType = gameState.isPlayerNeutral(player) ? "ally" : "neutral";
const requestType = gameState.isPlayerNeutral(player) ? "ally" : "neutral";
this.sentDiplomacyRequests.set(player, {
"requestType": requestType,
@ -516,7 +516,7 @@ PETRA.DiplomacyManager.prototype.sendDiplomacyRequest = function(gameState)
PETRA.DiplomacyManager.prototype.checkSentDiplomacyRequests = function(gameState)
{
for (let [player, data] of this.sentDiplomacyRequests)
for (const [player, data] of this.sentDiplomacyRequests)
if (gameState.ai.elapsedTime > data.timeSent + 60 && !gameState.ai.HQ.saveResources &&
gameState.getPopulation() > 70)
{
@ -544,7 +544,7 @@ PETRA.DiplomacyManager.prototype.update = function(gameState, events)
if (gameState.ai.elapsedTime > this.sentDiplomacyRequestLapseTime)
{
this.sentDiplomacyRequestLapseTime = gameState.ai.elapsedTime + 300 + randFloat(10, 100);
let numEnemies = gameState.getEnemies().length;
const numEnemies = gameState.getEnemies().length;
// Don't consider gaia
if (numEnemies > 2 && gameState.getMutualAllies().length < numEnemies - 1 && randBool(0.1))
this.sendDiplomacyRequest(gameState);
@ -569,6 +569,6 @@ PETRA.DiplomacyManager.prototype.Serialize = function()
PETRA.DiplomacyManager.prototype.Deserialize = function(data)
{
for (let key in data)
for (const key in data)
this[key] = data[key];
};

View file

@ -15,18 +15,18 @@ PETRA.isFastMoving = function(ent)
PETRA.getMaxStrength = function(ent, debugLevel, DamageTypeImportance, againstClass)
{
let strength = 0;
let attackTypes = ent.attackTypes();
let damageTypes = Object.keys(DamageTypeImportance);
const attackTypes = ent.attackTypes();
const damageTypes = Object.keys(DamageTypeImportance);
if (!attackTypes)
return strength;
for (let type of attackTypes)
for (const type of attackTypes)
{
if (type == "Slaughter")
continue;
let attackStrength = ent.attackStrengths(type);
for (let str in attackStrength)
const attackStrength = ent.attackStrengths(type);
for (const str in attackStrength)
{
let val = parseFloat(attackStrength[str]);
if (againstClass)
@ -37,14 +37,14 @@ PETRA.getMaxStrength = function(ent, debugLevel, DamageTypeImportance, againstCl
API3.warn("Petra: " + str + " unknown attackStrength in getMaxStrength (please add " + str + " to config.js).");
}
let attackRange = ent.attackRange(type);
const attackRange = ent.attackRange(type);
if (attackRange)
strength += attackRange.max * 0.0125;
let attackTimes = ent.attackTimes(type);
for (let str in attackTimes)
const attackTimes = ent.attackTimes(type);
for (const str in attackTimes)
{
let val = parseFloat(attackTimes[str]);
const val = parseFloat(attackTimes[str]);
switch (str)
{
case "repeat":
@ -59,12 +59,12 @@ PETRA.getMaxStrength = function(ent, debugLevel, DamageTypeImportance, againstCl
}
}
let resistanceStrength = ent.resistanceStrengths();
const resistanceStrength = ent.resistanceStrengths();
if (resistanceStrength.Damage)
for (let str in resistanceStrength.Damage)
for (const str in resistanceStrength.Damage)
{
let val = +resistanceStrength.Damage[str];
const val = +resistanceStrength.Damage[str];
if (DamageTypeImportance[str])
strength += DamageTypeImportance[str] * val / damageTypes.length;
else if (debugLevel > 0)
@ -81,10 +81,10 @@ PETRA.getLandAccess = function(gameState, ent)
{
if (ent.hasClass("Unit"))
{
let pos = ent.position();
const pos = ent.position();
if (!pos)
{
let holder = PETRA.getHolder(gameState, ent);
const holder = PETRA.getHolder(gameState, ent);
if (holder)
return PETRA.getLandAccess(gameState, holder);
@ -107,12 +107,12 @@ PETRA.getLandAccess = function(gameState, ent)
halfDepth = +ent.get("Footprint/Square/@depth") / 2;
else if (ent.get("Footprint/Circle"))
halfDepth = +ent.get("Footprint/Circle/@radius");
let entPos = ent.position();
let cosa = Math.cos(ent.angle());
let sina = Math.sin(ent.angle());
const entPos = ent.position();
const cosa = Math.cos(ent.angle());
const sina = Math.sin(ent.angle());
for (let d = 3; d < halfDepth; d += 3)
{
let pos = [ entPos[0] - d * sina,
const pos = [ entPos[0] - d * sina,
entPos[1] - d * cosa];
access = gameState.ai.accessibility.getAccessValue(pos);
if (access > 1)
@ -134,12 +134,12 @@ PETRA.getSeaAccess = function(gameState, ent)
// Docks are sometimes not as expected
if (sea < 2 && ent.buildPlacementType() == "shore")
{
let entPos = ent.position();
let cosa = Math.cos(ent.angle());
let sina = Math.sin(ent.angle());
const entPos = ent.position();
const cosa = Math.cos(ent.angle());
const sina = Math.sin(ent.angle());
for (let d = 3; d < 15; d += 3)
{
let pos = [ entPos[0] + d * sina,
const pos = [ entPos[0] + d * sina,
entPos[1] + d * cosa];
sea = gameState.ai.accessibility.getAccessValue(pos, true);
if (sea > 1)
@ -179,7 +179,7 @@ PETRA.allowCapture = function(gameState, ent, target)
antiCapture -= target.territoryDecayRate();
let capture;
let capturableTargets = gameState.ai.HQ.capturableTargets;
const capturableTargets = gameState.ai.HQ.capturableTargets;
if (!capturableTargets.has(target.id()))
{
capture = ent.captureStrength() * PETRA.getAttackBonus(ent, target, "Capture");
@ -187,7 +187,7 @@ PETRA.allowCapture = function(gameState, ent, target)
}
else
{
let capturable = capturableTargets.get(target.id());
const capturable = capturableTargets.get(target.id());
if (!capturable.ents.has(ent.id()))
{
capturable.strength += ent.captureStrength() * PETRA.getAttackBonus(ent, target, "Capture");
@ -196,7 +196,7 @@ PETRA.allowCapture = function(gameState, ent, target)
capture = capturable.strength;
}
capture *= 1 / (0.1 + 0.9*target.healthLevel());
let sumCapturePoints = target.capturePoints().reduce((a, b) => a + b);
const sumCapturePoints = target.capturePoints().reduce((a, b) => a + b);
if (target.hasDefensiveFire() && target.isGarrisonHolder() && target.garrisoned())
return capture > antiCapture + sumCapturePoints/50;
return capture > antiCapture + sumCapturePoints/80;
@ -207,10 +207,10 @@ PETRA.getAttackBonus = function(ent, target, type)
let attackBonus = 1;
if (!ent.get("Attack/" + type) || !ent.get("Attack/" + type + "/Bonuses"))
return attackBonus;
let bonuses = ent.get("Attack/" + type + "/Bonuses");
for (let key in bonuses)
const bonuses = ent.get("Attack/" + type + "/Bonuses");
for (const key in bonuses)
{
let bonus = bonuses[key];
const bonus = bonuses[key];
if (bonus.Civ && bonus.Civ !== target.civ())
continue;
if (!bonus.Classes || target.hasClasses(bonus.Classes))
@ -225,24 +225,24 @@ PETRA.returnResources = function(gameState, ent)
if (!ent.resourceCarrying() || !ent.resourceCarrying().length || !ent.position())
return false;
let resource = ent.resourceCarrying()[0].type;
const resource = ent.resourceCarrying()[0].type;
let closestDropsite;
let distmin = Math.min();
let access = PETRA.getLandAccess(gameState, ent);
let dropsiteCollection = gameState.playerData.hasSharedDropsites ?
const access = PETRA.getLandAccess(gameState, ent);
const dropsiteCollection = gameState.playerData.hasSharedDropsites ?
gameState.getAnyDropsites(resource) : gameState.getOwnDropsites(resource);
for (let dropsite of dropsiteCollection.values())
for (const dropsite of dropsiteCollection.values())
{
if (!dropsite.position())
continue;
let owner = dropsite.owner();
const owner = dropsite.owner();
// owner !== PlayerID can only happen when hasSharedDropsites === true, so no need to test it again
if (owner !== PlayerID && (!dropsite.isSharedDropsite() || !gameState.isPlayerMutualAlly(owner)))
continue;
if (PETRA.getLandAccess(gameState, dropsite) != access)
continue;
let dist = API3.SquareVectorDistance(ent.position(), dropsite.position());
const dist = API3.SquareVectorDistance(ent.position(), dropsite.position());
if (dist > distmin)
continue;
distmin = dist;
@ -274,7 +274,7 @@ PETRA.getBestBase = function(gameState, ent, onlyConstructedBase = false, exclud
let accessIndex;
if (!pos)
{
let holder = PETRA.getHolder(gameState, ent);
const holder = PETRA.getHolder(gameState, ent);
if (!holder || !holder.position())
{
API3.warn("Petra error: entity without position, but not garrisoned");
@ -303,7 +303,7 @@ PETRA.getBestBase = function(gameState, ent, onlyConstructedBase = false, exclud
else
{
let found = false;
for (let structure of base.buildings.values())
for (const structure of base.buildings.values())
{
if (!structure.position())
continue;
@ -330,7 +330,7 @@ PETRA.getBestBase = function(gameState, ent, onlyConstructedBase = false, exclud
PETRA.getHolder = function(gameState, ent)
{
for (let holder of gameState.getEntities().values())
for (const holder of gameState.getEntities().values())
{
if (holder.isGarrisonHolder() && holder.garrisoned().indexOf(ent.id()) !== -1)
return holder;
@ -355,7 +355,7 @@ PETRA.isNotWorthBuilding = function(gameState, ent)
{
if (gameState.ai.HQ.territoryMap.getOwner(ent.position()) !== PlayerID)
{
let buildTerritories = ent.buildTerritories();
const buildTerritories = ent.buildTerritories();
if (buildTerritories && (!buildTerritories.length || buildTerritories.length === 1 && buildTerritories[0] === "own"))
return true;
}
@ -367,13 +367,13 @@ PETRA.isNotWorthBuilding = function(gameState, ent)
*/
PETRA.isLineInsideEnemyTerritory = function(gameState, pos1, pos2, step=70)
{
let n = Math.floor(Math.sqrt(API3.SquareVectorDistance(pos1, pos2))/step) + 1;
let stepx = (pos2[0] - pos1[0]) / n;
let stepy = (pos2[1] - pos1[1]) / n;
const n = Math.floor(Math.sqrt(API3.SquareVectorDistance(pos1, pos2))/step) + 1;
const stepx = (pos2[0] - pos1[0]) / n;
const stepy = (pos2[1] - pos1[1]) / n;
for (let i = 1; i < n; ++i)
{
let pos = [pos1[0]+i*stepx, pos1[1]+i*stepy];
let owner = gameState.ai.HQ.territoryMap.getOwner(pos);
const pos = [pos1[0]+i*stepx, pos1[1]+i*stepy];
const owner = gameState.ai.HQ.territoryMap.getOwner(pos);
if (owner && gameState.isPlayerEnemy(owner))
return true;
}
@ -390,21 +390,21 @@ PETRA.gatherTreasure = function(gameState, ent, water = false)
return false;
let treasureFound;
let distmin = Math.min();
let access = water ? PETRA.getSeaAccess(gameState, ent) : PETRA.getLandAccess(gameState, ent);
for (let treasure of gameState.ai.HQ.treasures.values())
const access = water ? PETRA.getSeaAccess(gameState, ent) : PETRA.getLandAccess(gameState, ent);
for (const treasure of gameState.ai.HQ.treasures.values())
{
// let some time for the previous gatherer to reach the treasure before trying again
let lastGathered = treasure.getMetadata(PlayerID, "lastGathered");
const lastGathered = treasure.getMetadata(PlayerID, "lastGathered");
if (lastGathered && gameState.ai.elapsedTime - lastGathered < 20)
continue;
if (!water && access != PETRA.getLandAccess(gameState, treasure))
continue;
if (water && access != PETRA.getSeaAccess(gameState, treasure))
continue;
let territoryOwner = gameState.ai.HQ.territoryMap.getOwner(treasure.position());
const territoryOwner = gameState.ai.HQ.territoryMap.getOwner(treasure.position());
if (territoryOwner != 0 && !gameState.isPlayerAlly(territoryOwner))
continue;
let dist = API3.SquareVectorDistance(ent.position(), treasure.position());
const dist = API3.SquareVectorDistance(ent.position(), treasure.position());
if (dist > 120000 || territoryOwner != PlayerID && dist > 14000) // AI has no LOS, so restrict it a bit
continue;
if (dist > distmin)

View file

@ -22,14 +22,14 @@ PETRA.GarrisonManager.TYPE_EMERGENCY = "emergency";
PETRA.GarrisonManager.prototype.update = function(gameState, events)
{
// First check for possible upgrade of a structure
for (let evt of events.EntityRenamed)
for (const evt of events.EntityRenamed)
{
for (let id of this.holders.keys())
for (const id of this.holders.keys())
{
if (id != evt.entity)
continue;
let data = this.holders.get(id);
let newHolder = gameState.getEntityById(evt.newentity);
const data = this.holders.get(id);
const newHolder = gameState.getEntityById(evt.newentity);
if (newHolder && newHolder.isGarrisonHolder())
{
this.holders.delete(id);
@ -37,9 +37,9 @@ PETRA.GarrisonManager.prototype.update = function(gameState, events)
}
else
{
for (let entId of data.list)
for (const entId of data.list)
{
let ent = gameState.getEntityById(entId);
const ent = gameState.getEntityById(entId);
if (!ent || ent.getMetadata(PlayerID, "garrisonHolder") != id)
continue;
this.leaveGarrison(ent);
@ -49,31 +49,31 @@ PETRA.GarrisonManager.prototype.update = function(gameState, events)
}
}
for (let id of this.decayingStructures.keys())
for (const id of this.decayingStructures.keys())
{
if (id !== evt.entity)
continue;
this.decayingStructures.delete(id);
if (this.decayingStructures.has(evt.newentity))
continue;
let ent = gameState.getEntityById(evt.newentity);
const ent = gameState.getEntityById(evt.newentity);
if (!ent || !ent.territoryDecayRate() || !ent.garrisonRegenRate())
continue;
let gmin = Math.ceil((ent.territoryDecayRate() - ent.defaultRegenRate()) / ent.garrisonRegenRate());
const gmin = Math.ceil((ent.territoryDecayRate() - ent.defaultRegenRate()) / ent.garrisonRegenRate());
this.decayingStructures.set(evt.newentity, gmin);
}
}
for (let [id, data] of this.holders.entries())
for (const [id, data] of this.holders.entries())
{
let list = data.list;
let holder = gameState.getEntityById(id);
const list = data.list;
const holder = gameState.getEntityById(id);
if (!holder || !gameState.isPlayerAlly(holder.owner()))
{
// this holder was certainly destroyed or captured. Let's remove it
for (let entId of list)
for (const entId of list)
{
let ent = gameState.getEntityById(entId);
const ent = gameState.getEntityById(entId);
if (!ent || ent.getMetadata(PlayerID, "garrisonHolder") != id)
continue;
this.leaveGarrison(ent);
@ -86,11 +86,11 @@ PETRA.GarrisonManager.prototype.update = function(gameState, events)
// Update the list of garrisoned units
for (let j = 0; j < list.length; ++j)
{
for (let evt of events.EntityRenamed)
for (const evt of events.EntityRenamed)
if (evt.entity === list[j])
list[j] = evt.newentity;
let ent = gameState.getEntityById(list[j]);
const ent = gameState.getEntityById(list[j]);
if (!ent) // unit must have been killed while garrisoning
list.splice(j--, 1);
else if (holder.garrisoned().indexOf(list[j]) !== -1) // unit is garrisoned
@ -128,9 +128,9 @@ PETRA.GarrisonManager.prototype.update = function(gameState, events)
if (gameState.ai.elapsedTime - holder.getMetadata(PlayerID, "holderTimeUpdate") > 3)
{
let range = holder.attackRange("Ranged") ? holder.attackRange("Ranged").max : 80;
let around = { "defenseStructure": false, "meleeSiege": false, "rangeSiege": false, "unit": false };
for (let ent of gameState.getEnemyEntities().values())
const range = holder.attackRange("Ranged") ? holder.attackRange("Ranged").max : 80;
const around = { "defenseStructure": false, "meleeSiege": false, "rangeSiege": false, "unit": false };
for (const ent of gameState.getEnemyEntities().values())
{
if (ent.hasClass("Structure"))
{
@ -146,7 +146,7 @@ PETRA.GarrisonManager.prototype.update = function(gameState, events)
continue;
if (!ent.position())
continue;
let dist = API3.SquareVectorDistance(ent.position(), holder.position());
const dist = API3.SquareVectorDistance(ent.position(), holder.position());
if (dist > range*range)
continue;
if (ent.hasClass("Structure"))
@ -167,15 +167,15 @@ PETRA.GarrisonManager.prototype.update = function(gameState, events)
// Keep defenseManager.garrisonUnitsInside in sync to avoid garrisoning-ungarrisoning some units
data.allowMelee = around.defenseStructure || around.unit;
for (let entId of holder.garrisoned())
for (const entId of holder.garrisoned())
{
let ent = gameState.getEntityById(entId);
const ent = gameState.getEntityById(entId);
if (ent.owner() === PlayerID && !this.keepGarrisoned(ent, holder, around))
holder.unload(entId);
}
for (let j = 0; j < list.length; ++j)
{
let ent = gameState.getEntityById(list[j]);
const ent = gameState.getEntityById(list[j]);
if (this.keepGarrisoned(ent, holder, around))
continue;
if (ent.getMetadata(PlayerID, "garrisonHolder") == id)
@ -194,9 +194,9 @@ PETRA.GarrisonManager.prototype.update = function(gameState, events)
// Warning new garrison orders (as in the following lines) should be done after having updated the holders
// (or TODO we should add a test that the garrison order is from a previous turn when updating)
for (let [id, gmin] of this.decayingStructures.entries())
for (const [id, gmin] of this.decayingStructures.entries())
{
let ent = gameState.getEntityById(id);
const ent = gameState.getEntityById(id);
if (!ent || ent.owner() !== PlayerID)
this.decayingStructures.delete(id);
else if (this.numberOfGarrisonedSlots(ent) < gmin)
@ -277,11 +277,11 @@ PETRA.GarrisonManager.prototype.cancelGarrison = function(ent)
{
ent.stopMoving();
this.leaveGarrison(ent);
let holderId = ent.getMetadata(PlayerID, "garrisonHolder");
const holderId = ent.getMetadata(PlayerID, "garrisonHolder");
if (!holderId || !this.holders.has(holderId))
return;
let list = this.holders.get(holderId).list;
let index = list.indexOf(ent.id());
const list = this.holders.get(holderId).list;
const index = list.indexOf(ent.id());
if (index !== -1)
list.splice(index, 1);
};
@ -297,7 +297,7 @@ PETRA.GarrisonManager.prototype.keepGarrisoned = function(ent, holder, around)
case PETRA.GarrisonManager.TYPE_PROTECTION: // hurt unit for healing or infantry for defense
if (holder.buffHeal() && ent.isHealable() && ent.healthLevel() < this.Config.garrisonHealthLevel.high)
return true;
let capture = ent.capturePoints();
const capture = ent.capturePoints();
if (capture && capture[PlayerID] / capture.reduce((a, b) => a + b) < 0.8)
return true;
if (ent.hasClasses(holder.getGarrisonArrowClasses()))
@ -353,12 +353,12 @@ PETRA.GarrisonManager.prototype.addDecayingStructure = function(gameState, entId
{
if (this.decayingStructures.has(entId))
return true;
let ent = gameState.getEntityById(entId);
const ent = gameState.getEntityById(entId);
if (!ent || !(ent.hasClass("Barracks") && justCaptured) && !ent.hasDefensiveFire())
return false;
if (!ent.territoryDecayRate() || !ent.garrisonRegenRate())
return false;
let gmin = Math.ceil((ent.territoryDecayRate() - ent.defaultRegenRate()) / ent.garrisonRegenRate());
const gmin = Math.ceil((ent.territoryDecayRate() - ent.defaultRegenRate()) / ent.garrisonRegenRate());
this.decayingStructures.set(entId, gmin);
return true;
};
@ -377,6 +377,6 @@ PETRA.GarrisonManager.prototype.Serialize = function()
PETRA.GarrisonManager.prototype.Deserialize = function(data)
{
for (let key in data)
for (const key in data)
this[key] = data[key];
};

View file

@ -5,9 +5,9 @@ PETRA.TERRITORY_BLINKING_MASK = 0x40;
PETRA.createObstructionMap = function(gameState, accessIndex, template)
{
let passabilityMap = gameState.getPassabilityMap();
let territoryMap = gameState.ai.territoryMap;
let ratio = territoryMap.cellSize / passabilityMap.cellSize;
const passabilityMap = gameState.getPassabilityMap();
const territoryMap = gameState.ai.territoryMap;
const ratio = territoryMap.cellSize / passabilityMap.cellSize;
// default values
let placementType = "land";
@ -24,7 +24,7 @@ PETRA.createObstructionMap = function(gameState, accessIndex, template)
buildNeutral = template.hasBuildTerritory("neutral");
buildEnemy = template.hasBuildTerritory("enemy");
}
let obstructionTiles = new Uint8Array(passabilityMap.data.length);
const obstructionTiles = new Uint8Array(passabilityMap.data.length);
let passMap;
let obstructionMask;
@ -41,8 +41,8 @@ PETRA.createObstructionMap = function(gameState, accessIndex, template)
for (let k = 0; k < territoryMap.data.length; ++k)
{
let tilePlayer = territoryMap.data[k] & PETRA.TERRITORY_PLAYER_MASK;
let isConnected = (territoryMap.data[k] & PETRA.TERRITORY_BLINKING_MASK) == 0;
const tilePlayer = territoryMap.data[k] & PETRA.TERRITORY_PLAYER_MASK;
const isConnected = (territoryMap.data[k] & PETRA.TERRITORY_BLINKING_MASK) == 0;
if (tilePlayer === PlayerID)
{
if (!buildOwn || !buildNeutral && !isConnected)
@ -64,13 +64,13 @@ PETRA.createObstructionMap = function(gameState, accessIndex, template)
continue;
}
let x = ratio * (k % territoryMap.width);
let y = ratio * Math.floor(k / territoryMap.width);
const x = ratio * (k % territoryMap.width);
const y = ratio * Math.floor(k / territoryMap.width);
for (let ix = 0; ix < ratio; ++ix)
{
for (let iy = 0; iy < ratio; ++iy)
{
let i = x + ix + (y + iy)*passabilityMap.width;
const i = x + ix + (y + iy)*passabilityMap.width;
if (placementType != "shore" && accessIndex && accessIndex !== passMap[i])
continue;
if (!(passabilityMap.data[i] & obstructionMask))
@ -79,29 +79,29 @@ PETRA.createObstructionMap = function(gameState, accessIndex, template)
}
}
let map = new API3.Map(gameState.sharedScript, "passability", obstructionTiles);
const map = new API3.Map(gameState.sharedScript, "passability", obstructionTiles);
map.setMaxVal(255);
if (template && template.buildDistance())
{
let distance = template.buildDistance();
const distance = template.buildDistance();
let minDist = distance.MinDistance ? +distance.MinDistance : 0;
if (minDist)
{
let obstructionRadius = template.obstructionRadius();
const obstructionRadius = template.obstructionRadius();
if (obstructionRadius)
minDist -= obstructionRadius.min;
let fromClass = distance.FromClass;
let cellSize = passabilityMap.cellSize;
let cellDist = 1 + minDist / cellSize;
let structures = gameState.getOwnStructures().filter(API3.Filters.byClass(fromClass));
for (let ent of structures.values())
const fromClass = distance.FromClass;
const cellSize = passabilityMap.cellSize;
const cellDist = 1 + minDist / cellSize;
const structures = gameState.getOwnStructures().filter(API3.Filters.byClass(fromClass));
for (const ent of structures.values())
{
if (!ent.position())
continue;
let pos = ent.position();
let x = Math.round(pos[0] / cellSize);
let z = Math.round(pos[1] / cellSize);
const pos = ent.position();
const x = Math.round(pos[0] / cellSize);
const z = Math.round(pos[1] / cellSize);
map.addInfluence(x, z, cellDist, -255, "constant");
}
}
@ -113,9 +113,9 @@ PETRA.createObstructionMap = function(gameState, accessIndex, template)
PETRA.createTerritoryMap = function(gameState)
{
let map = gameState.ai.territoryMap;
const map = gameState.ai.territoryMap;
let ret = new API3.Map(gameState.sharedScript, "territory", map.data);
const ret = new API3.Map(gameState.sharedScript, "territory", map.data);
ret.getOwner = function(p) { return this.point(p) & PETRA.TERRITORY_PLAYER_MASK; };
ret.getOwnerIndex = function(p) { return this.map[p] & PETRA.TERRITORY_PLAYER_MASK; };
ret.isBlinking = function(p) { return (this.point(p) & PETRA.TERRITORY_BLINKING_MASK) != 0; };
@ -141,25 +141,25 @@ PETRA.fullFrontier_Mask = PETRA.narrowFrontier_Mask | PETRA.largeFrontier_Mask;
PETRA.createBorderMap = function(gameState)
{
let map = new API3.Map(gameState.sharedScript, "territory");
let width = map.width;
let border = Math.round(80 / map.cellSize);
let passabilityMap = gameState.getPassabilityMap();
let obstructionMask = gameState.getPassabilityClassMask("unrestricted");
const map = new API3.Map(gameState.sharedScript, "territory");
const width = map.width;
const border = Math.round(80 / map.cellSize);
const passabilityMap = gameState.getPassabilityMap();
const obstructionMask = gameState.getPassabilityClassMask("unrestricted");
if (gameState.circularMap)
{
let ic = (width - 1) / 2;
let radcut = (ic - border) * (ic - border);
const ic = (width - 1) / 2;
const radcut = (ic - border) * (ic - border);
for (let j = 0; j < map.length; ++j)
{
let dx = j%width - ic;
let dy = Math.floor(j/width) - ic;
let radius = dx*dx + dy*dy;
const dx = j%width - ic;
const dy = Math.floor(j/width) - ic;
const radius = dx*dx + dy*dy;
if (radius < radcut)
continue;
map.map[j] = PETRA.outside_Mask;
let ind = API3.getMapIndices(j, map, passabilityMap);
for (let k of ind)
const ind = API3.getMapIndices(j, map, passabilityMap);
for (const k of ind)
{
if (passabilityMap.data[k] & obstructionMask)
continue;
@ -170,16 +170,16 @@ PETRA.createBorderMap = function(gameState)
}
else
{
let borderCut = width - border;
const borderCut = width - border;
for (let j = 0; j < map.length; ++j)
{
let ix = j%width;
let iy = Math.floor(j/width);
const ix = j%width;
const iy = Math.floor(j/width);
if (ix < border || ix >= borderCut || iy < border || iy >= borderCut)
{
map.map[j] = PETRA.outside_Mask;
let ind = API3.getMapIndices(j, map, passabilityMap);
for (let k of ind)
const ind = API3.getMapIndices(j, map, passabilityMap);
for (const k of ind)
{
if (passabilityMap.data[k] & obstructionMask)
continue;
@ -196,15 +196,15 @@ PETRA.createBorderMap = function(gameState)
PETRA.debugMap = function(gameState, map)
{
let width = map.width;
let cell = map.cellSize;
const width = map.width;
const cell = map.cellSize;
gameState.getEntities().forEach(ent => {
let pos = ent.position();
const pos = ent.position();
if (!pos)
return;
let x = Math.round(pos[0] / cell);
let z = Math.round(pos[1] / cell);
let id = x + width*z;
const x = Math.round(pos[0] / cell);
const z = Math.round(pos[1] / cell);
const id = x + width*z;
if (map.map[id] == 1)
Engine.PostCommand(PlayerID, { "type": "set-shading-color", "entities": [ent.id()], "rgb": [2, 0, 0] });
else if (map.map[id] == 2)

View file

@ -17,7 +17,7 @@ PETRA.Queue.prototype.addPlan = function(newPlan)
{
if (!newPlan)
return;
for (let plan of this.plans)
for (const plan of this.plans)
{
if (newPlan.category === "unit" && plan.type == newPlan.type && plan.number + newPlan.number <= plan.maxMerge)
{
@ -36,7 +36,7 @@ PETRA.Queue.prototype.check= function(gameState)
{
if (!this.plans[0].isInvalid(gameState))
return;
let plan = this.plans.shift();
const plan = this.plans.shift();
if (plan.queueToReset)
gameState.ai.queueManager.changePriority(plan.queueToReset, gameState.ai.Config.priorities[plan.queueToReset]);
}
@ -65,12 +65,12 @@ PETRA.Queue.prototype.startNext = function(gameState)
*/
PETRA.Queue.prototype.maxAccountWanted = function(gameState, fraction)
{
let cost = new API3.Resources();
const cost = new API3.Resources();
if (this.plans.length > 0 && this.plans[0].isGo(gameState))
cost.add(this.plans[0].getCost());
if (this.plans.length > 1 && this.plans[1].isGo(gameState) && fraction > 0)
{
let costs = this.plans[1].getCost();
const costs = this.plans[1].getCost();
costs.multiply(fraction);
cost.add(costs);
}
@ -79,8 +79,8 @@ PETRA.Queue.prototype.maxAccountWanted = function(gameState, fraction)
PETRA.Queue.prototype.queueCost = function()
{
let cost = new API3.Resources();
for (let plan of this.plans)
const cost = new API3.Resources();
for (const plan of this.plans)
cost.add(plan.getCost());
return cost;
};
@ -98,7 +98,7 @@ PETRA.Queue.prototype.hasQueuedUnits = function()
PETRA.Queue.prototype.countQueuedUnits = function()
{
let count = 0;
for (let plan of this.plans)
for (const plan of this.plans)
count += plan.number;
return count;
};
@ -111,7 +111,7 @@ PETRA.Queue.prototype.hasQueuedUnitsWithClass = function(classe)
PETRA.Queue.prototype.countQueuedUnitsWithClass = function(classe)
{
let count = 0;
for (let plan of this.plans)
for (const plan of this.plans)
if (plan.template && plan.template.hasClass(classe))
count += plan.number;
return count;
@ -120,7 +120,7 @@ PETRA.Queue.prototype.countQueuedUnitsWithClass = function(classe)
PETRA.Queue.prototype.countQueuedUnitsWithMetadata = function(data, value)
{
let count = 0;
for (let plan of this.plans)
for (const plan of this.plans)
if (plan.metadata[data] && plan.metadata[data] == value)
count += plan.number;
return count;
@ -128,8 +128,8 @@ PETRA.Queue.prototype.countQueuedUnitsWithMetadata = function(data, value)
PETRA.Queue.prototype.Serialize = function()
{
let plans = [];
for (let plan of this.plans)
const plans = [];
for (const plan of this.plans)
plans.push(plan.Serialize());
return { "plans": plans, "paused": this.paused, "switched": this.switched };
@ -140,7 +140,7 @@ PETRA.Queue.prototype.Deserialize = function(gameState, data)
this.paused = data.paused;
this.switched = data.switched;
this.plans = [];
for (let dataPlan of data.plans)
for (const dataPlan of data.plans)
{
let plan;
if (dataPlan.category == "unit")

View file

@ -24,52 +24,52 @@ PETRA.QueueManager = function(Config, queues)
this.Config = Config;
this.queues = queues;
this.priorities = {};
for (let i in Config.priorities)
for (const i in Config.priorities)
this.priorities[i] = Config.priorities[i];
this.accounts = {};
// the sorting is updated on priority change.
this.queueArrays = [];
for (let q in this.queues)
for (const q in this.queues)
{
this.accounts[q] = new API3.Resources();
this.queueArrays.push([q, this.queues[q]]);
}
let priorities = this.priorities;
const priorities = this.priorities;
this.queueArrays.sort((a, b) => priorities[b[0]] - priorities[a[0]]);
};
PETRA.QueueManager.prototype.getAvailableResources = function(gameState)
{
let resources = gameState.getResources();
for (let key in this.queues)
const resources = gameState.getResources();
for (const key in this.queues)
resources.subtract(this.accounts[key]);
return resources;
};
PETRA.QueueManager.prototype.getTotalAccountedResources = function()
{
let resources = new API3.Resources();
for (let key in this.queues)
const resources = new API3.Resources();
for (const key in this.queues)
resources.add(this.accounts[key]);
return resources;
};
PETRA.QueueManager.prototype.currentNeeds = function(gameState)
{
let needed = new API3.Resources();
const needed = new API3.Resources();
// queueArrays because it's faster.
for (let q of this.queueArrays)
for (const q of this.queueArrays)
{
let queue = q[1];
const queue = q[1];
if (!queue.hasQueuedUnits() || !queue.plans[0].isGo(gameState))
continue;
let costs = queue.plans[0].getCost();
const costs = queue.plans[0].getCost();
needed.add(costs);
}
// get out current resources, not removing accounts.
let current = gameState.getResources();
for (let res of Resources.GetCodes())
const current = gameState.getResources();
for (const res of Resources.GetCodes())
needed[res] = Math.max(0, needed[res] - current[res]);
return needed;
@ -82,21 +82,21 @@ PETRA.QueueManager.prototype.wantedGatherRates = function(gameState)
// default values for first turn when we have not yet set our queues.
if (gameState.ai.playedTurn === 0)
{
let ret = {};
for (let res of Resources.GetCodes())
const ret = {};
for (const res of Resources.GetCodes())
ret[res] = this.Config.queues.firstTurn[res] || this.Config.queues.firstTurn.default;
return ret;
}
// get out current resources, not removing accounts.
let current = gameState.getResources();
const current = gameState.getResources();
// short queue is the first item of a queue, assumed to be ready in 30s
// medium queue is the second item of a queue, assumed to be ready in 60s
// long queue contains the isGo=false items, assumed to be ready in 300s
let totalShort = {};
let totalMedium = {};
let totalLong = {};
for (let res of Resources.GetCodes())
const totalShort = {};
const totalMedium = {};
const totalLong = {};
for (const res of Resources.GetCodes())
{
totalShort[res] = this.Config.queues.short[res] || this.Config.queues.short.default;
totalMedium[res] = this.Config.queues.medium[res] || this.Config.queues.medium.default;
@ -104,16 +104,16 @@ PETRA.QueueManager.prototype.wantedGatherRates = function(gameState)
}
let total;
// queueArrays because it's faster.
for (let q of this.queueArrays)
for (const q of this.queueArrays)
{
let queue = q[1];
const queue = q[1];
if (queue.paused)
continue;
for (let j = 0; j < queue.length(); ++j)
{
if (j > 1)
break;
let cost = queue.plans[j].getCost();
const cost = queue.plans[j].getCost();
if (queue.plans[j].isGo(gameState))
{
if (j === 0)
@ -123,16 +123,16 @@ PETRA.QueueManager.prototype.wantedGatherRates = function(gameState)
}
else
total = totalLong;
for (let type in total)
for (const type in total)
total[type] += cost[type];
if (!queue.plans[j].isGo(gameState))
break;
}
}
// global rates
let rates = {};
const rates = {};
let diff;
for (let res of Resources.GetCodes())
for (const res of Resources.GetCodes())
{
if (current[res] > 0)
{
@ -162,15 +162,15 @@ PETRA.QueueManager.prototype.printQueues = function(gameState)
numWorkers++;
});
API3.warn("---------- QUEUES ------------ with pop " + gameState.getPopulation() + " and workers " + numWorkers);
for (let i in this.queues)
for (const i in this.queues)
{
let q = this.queues[i];
const q = this.queues[i];
if (q.hasQueuedUnits())
{
API3.warn(i + ": ( with priority " + this.priorities[i] +" and accounts " + uneval(this.accounts[i]) +")");
API3.warn(" while maxAccountWanted(0.6) is " + uneval(q.maxAccountWanted(gameState, 0.6)));
}
for (let plan of q.plans)
for (const plan of q.plans)
{
let qStr = " " + plan.type + " ";
if (plan.number)
@ -180,7 +180,7 @@ PETRA.QueueManager.prototype.printQueues = function(gameState)
}
}
API3.warn("Accounts");
for (let p in this.accounts)
for (const p in this.accounts)
API3.warn(p + ": " + uneval(this.accounts[p]));
API3.warn("Current Resources: " + uneval(gameState.getResources()));
API3.warn("Available Resources: " + uneval(this.getAvailableResources(gameState)));
@ -192,7 +192,7 @@ PETRA.QueueManager.prototype.printQueues = function(gameState)
PETRA.QueueManager.prototype.clear = function()
{
for (let i in this.queues)
for (const i in this.queues)
this.queues[i].empty();
};
@ -201,8 +201,8 @@ PETRA.QueueManager.prototype.clear = function()
*/
PETRA.QueueManager.prototype.setAccounts = function(gameState, cost, i)
{
let available = this.getAvailableResources(gameState);
for (let res of Resources.GetCodes())
const available = this.getAvailableResources(gameState);
for (const res of Resources.GetCodes())
{
if (this.accounts[i][res] >= cost[res])
continue;
@ -215,11 +215,11 @@ PETRA.QueueManager.prototype.setAccounts = function(gameState, cost, i)
*/
PETRA.QueueManager.prototype.transferAccounts = function(cost, i, j)
{
for (let res of Resources.GetCodes())
for (const res of Resources.GetCodes())
{
if (this.accounts[j][res] >= cost[res])
continue;
let diff = Math.min(this.accounts[i][res], cost[res] - this.accounts[j][res]);
const diff = Math.min(this.accounts[i][res], cost[res] - this.accounts[j][res]);
this.accounts[i][res] -= diff;
this.accounts[j][res] += diff;
}
@ -230,15 +230,15 @@ PETRA.QueueManager.prototype.transferAccounts = function(cost, i, j)
*/
PETRA.QueueManager.prototype.distributeResources = function(gameState)
{
let availableRes = this.getAvailableResources(gameState);
for (let res of Resources.GetCodes())
const availableRes = this.getAvailableResources(gameState);
for (const res of Resources.GetCodes())
{
if (availableRes[res] < 0) // rescale the accounts if we've spent resources already accounted (e.g. by bartering)
{
let total = gameState.getResources()[res];
let scale = total / (total - availableRes[res]);
const total = gameState.getResources()[res];
const scale = total / (total - availableRes[res]);
availableRes[res] = total;
for (let j in this.queues)
for (const j in this.queues)
{
this.accounts[j][res] = Math.floor(scale * this.accounts[j][res]);
availableRes[res] -= this.accounts[j][res];
@ -252,8 +252,8 @@ PETRA.QueueManager.prototype.distributeResources = function(gameState)
}
let totalPriority = 0;
let tempPrio = {};
let maxNeed = {};
const tempPrio = {};
const maxNeed = {};
// Okay so this is where it gets complicated.
// If a queue requires "res" for the next elements (in the queue)
// And the account is not high enough for it.
@ -263,10 +263,10 @@ PETRA.QueueManager.prototype.distributeResources = function(gameState)
// -queues accounts are capped at "resources for the first + 60% of the next"
// This avoids getting a high priority queue with many elements hogging all of one resource
// uselessly while it awaits for other resources.
for (let j in this.queues)
for (const j in this.queues)
{
// returns exactly the correct amount, ie 0 if we're not go.
let queueCost = this.queues[j].maxAccountWanted(gameState, 0.6);
const queueCost = this.queues[j].maxAccountWanted(gameState, 0.6);
if (this.queues[j].hasQueuedUnits() && this.accounts[j][res] < queueCost[res] && !this.queues[j].paused)
{
// adding us to the list of queues that need an update.
@ -289,7 +289,7 @@ PETRA.QueueManager.prototype.distributeResources = function(gameState)
// But we'll sometimes allow less if that would overflow.
let available = availableRes[res];
let missing = false;
for (let j in tempPrio)
for (const j in tempPrio)
{
// we'll add at much what can be allowed to this queue.
let toAdd = Math.floor(availableRes[res] * tempPrio[j]/totalPriority);
@ -303,9 +303,9 @@ PETRA.QueueManager.prototype.distributeResources = function(gameState)
}
if (missing && available > 0) // distribute the rest (due to floor) in any queue
{
for (let j in tempPrio)
for (const j in tempPrio)
{
let toAdd = Math.min(maxNeed[j], available);
const toAdd = Math.min(maxNeed[j], available);
this.accounts[j][res] += toAdd;
available -= toAdd;
if (available <= 0)
@ -322,27 +322,27 @@ PETRA.QueueManager.prototype.switchResource = function(gameState, res)
// We have no available resources, see if we can't "compact" them in one queue.
// compare queues 2 by 2, and if one with a higher priority could be completed by our amount, give it.
// TODO: this isn't perfect compression.
for (let j in this.queues)
for (const j in this.queues)
{
if (!this.queues[j].hasQueuedUnits() || this.queues[j].paused)
continue;
let queue = this.queues[j];
let queueCost = queue.maxAccountWanted(gameState, 0);
const queue = this.queues[j];
const queueCost = queue.maxAccountWanted(gameState, 0);
if (this.accounts[j][res] >= queueCost[res])
continue;
for (let i in this.queues)
for (const i in this.queues)
{
if (i === j)
continue;
let otherQueue = this.queues[i];
const otherQueue = this.queues[i];
if (this.priorities[i] >= this.priorities[j] || otherQueue.switched !== 0)
continue;
if (this.accounts[j][res] + this.accounts[i][res] < queueCost[res])
continue;
let diff = queueCost[res] - this.accounts[j][res];
const diff = queueCost[res] - this.accounts[j][res];
this.accounts[j][res] += diff;
this.accounts[i][res] -= diff;
++otherQueue.switched;
@ -356,13 +356,13 @@ PETRA.QueueManager.prototype.switchResource = function(gameState, res)
// Start the next item in the queue if we can afford it.
PETRA.QueueManager.prototype.startNextItems = function(gameState)
{
for (let q of this.queueArrays)
for (const q of this.queueArrays)
{
let name = q[0];
let queue = q[1];
const name = q[0];
const queue = q[1];
if (queue.hasQueuedUnits() && !queue.paused)
{
let item = queue.getNext();
const item = queue.getNext();
if (this.accounts[name].canAfford(item.getCost()) && item.canStart(gameState))
{
// canStart may update the cost because of the costMultiplier so we must check it again
@ -387,7 +387,7 @@ PETRA.QueueManager.prototype.update = function(gameState)
{
Engine.ProfileStart("Queue Manager");
for (let i in this.queues)
for (const i in this.queues)
{
this.queues[i].check(gameState); // do basic sanity checks on the queue
if (this.priorities[i] > 0)
@ -415,8 +415,8 @@ PETRA.QueueManager.prototype.update = function(gameState)
PETRA.QueueManager.prototype.checkPausedQueues = function(gameState)
{
const numWorkers = gameState.countOwnEntitiesAndQueuedWithRole(PETRA.Worker.ROLE_WORKER);
let workersMin = Math.min(Math.max(12, 24 * this.Config.popScaling), this.Config.Economy.popPhase2);
for (let q in this.queues)
const workersMin = Math.min(Math.max(12, 24 * this.Config.popScaling), this.Config.Economy.popPhase2);
for (const q in this.queues)
{
let toBePaused = false;
if (!gameState.ai.HQ.hasPotentialBase())
@ -447,7 +447,7 @@ PETRA.QueueManager.prototype.checkPausedQueues = function(gameState)
toBePaused = false;
}
let queue = this.queues[q];
const queue = this.queues[q];
if (!queue.paused && toBePaused)
{
queue.paused = true;
@ -490,7 +490,7 @@ PETRA.QueueManager.prototype.unpauseQueue = function(queue)
PETRA.QueueManager.prototype.pauseAll = function(scrapAccounts, but)
{
for (let q in this.queues)
for (const q in this.queues)
{
if (q == but)
continue;
@ -502,7 +502,7 @@ PETRA.QueueManager.prototype.pauseAll = function(scrapAccounts, but)
PETRA.QueueManager.prototype.unpauseAll = function(but)
{
for (let q in this.queues)
for (const q in this.queues)
if (q != but)
this.queues[q].paused = false;
};
@ -518,9 +518,9 @@ PETRA.QueueManager.prototype.addQueue = function(queueName, priority)
this.accounts[queueName] = new API3.Resources();
this.queueArrays = [];
for (let q in this.queues)
for (const q in this.queues)
this.queueArrays.push([q, this.queues[q]]);
let priorities = this.priorities;
const priorities = this.priorities;
this.queueArrays.sort((a, b) => priorities[b[0]] - priorities[a[0]]);
};
@ -534,9 +534,9 @@ PETRA.QueueManager.prototype.removeQueue = function(queueName)
delete this.accounts[queueName];
this.queueArrays = [];
for (let q in this.queues)
for (const q in this.queues)
this.queueArrays.push([q, this.queues[q]]);
let priorities = this.priorities;
const priorities = this.priorities;
this.queueArrays.sort((a, b) => priorities[b[0]] - priorities[a[0]]);
};
@ -551,15 +551,15 @@ PETRA.QueueManager.prototype.changePriority = function(queueName, newPriority)
API3.warn(">>> Priority of queue " + queueName + " changed from " + this.priorities[queueName] + " to " + newPriority);
if (this.queues[queueName] !== undefined)
this.priorities[queueName] = newPriority;
let priorities = this.priorities;
const priorities = this.priorities;
this.queueArrays.sort((a, b) => priorities[b[0]] - priorities[a[0]]);
};
PETRA.QueueManager.prototype.Serialize = function()
{
let accounts = {};
let queues = {};
for (let q in this.queues)
const accounts = {};
const queues = {};
for (const q in this.queues)
{
queues[q] = this.queues[q].Serialize();
accounts[q] = this.accounts[q].Serialize();
@ -583,7 +583,7 @@ PETRA.QueueManager.prototype.Deserialize = function(gameState, data)
// the sorting is updated on priority change.
this.queueArrays = [];
for (let q in data.queues)
for (const q in data.queues)
{
this.queues[q] = new PETRA.Queue();
this.queues[q].Deserialize(gameState, data.queues[q]);

View file

@ -17,12 +17,12 @@ PETRA.ResearchManager.prototype.checkPhase = function(gameState, queues)
if (queues.civilCentre.hasQueuedUnits() || queues.wonder.hasQueuedUnits())
return;
let currentPhaseIndex = gameState.currentPhase();
let nextPhaseName = gameState.getPhaseName(currentPhaseIndex+1);
const currentPhaseIndex = gameState.currentPhase();
const nextPhaseName = gameState.getPhaseName(currentPhaseIndex+1);
if (!nextPhaseName)
return;
let petraRequirements =
const petraRequirements =
currentPhaseIndex == 1 && gameState.ai.HQ.getAccountedPopulation(gameState) >= this.Config.Economy.popPhase2 ||
currentPhaseIndex == 2 && gameState.ai.HQ.getAccountedWorkers(gameState) > this.Config.Economy.workPhase3 ||
currentPhaseIndex >= 3 && gameState.ai.HQ.getAccountedWorkers(gameState) > this.Config.Economy.workPhase4;
@ -40,8 +40,8 @@ PETRA.ResearchManager.prototype.researchPopulationBonus = function(gameState, qu
if (queues.minorTech.hasQueuedUnits())
return;
let techs = gameState.findAvailableTech();
for (let tech of techs)
const techs = gameState.findAvailableTech();
for (const tech of techs)
{
if (!tech[1]._template.modifications)
continue;
@ -58,8 +58,8 @@ PETRA.ResearchManager.prototype.researchTradeBonus = function(gameState, queues)
if (queues.minorTech.hasQueuedUnits())
return;
let techs = gameState.findAvailableTech();
for (let tech of techs)
const techs = gameState.findAvailableTech();
for (const tech of techs)
{
if (!tech[1]._template.modifications || !tech[1]._template.affects)
continue;
@ -77,10 +77,10 @@ PETRA.ResearchManager.prototype.researchTradeBonus = function(gameState, queues)
/** Techs to be searched for as soon as they are available */
PETRA.ResearchManager.prototype.researchWantedTechs = function(gameState, techs)
{
let phase1 = gameState.currentPhase() === 1;
let available = phase1 ? gameState.ai.queueManager.getAvailableResources(gameState) : null;
const phase1 = gameState.currentPhase() === 1;
const available = phase1 ? gameState.ai.queueManager.getAvailableResources(gameState) : null;
const numWorkers = phase1 ? gameState.getOwnEntitiesByRole(PETRA.Worker.ROLE_WORKER, true).length : 0;
for (let tech of techs)
for (const tech of techs)
{
if (tech[0].indexOf("unlock_champion") == 0)
return { "name": tech[0], "increasePriority": true };
@ -89,17 +89,17 @@ PETRA.ResearchManager.prototype.researchWantedTechs = function(gameState, techs)
if (!tech[1]._template.modifications)
continue;
let template = tech[1]._template;
const template = tech[1]._template;
if (phase1)
{
let cost = template.cost;
const cost = template.cost;
let costMax = 0;
for (let res in cost)
for (const res in cost)
costMax = Math.max(costMax, Math.max(cost[res]-available[res], 0));
if (10*numWorkers < costMax)
continue;
}
for (let i in template.modifications)
for (const i in template.modifications)
{
if (gameState.ai.HQ.navalMap && template.modifications[i].value === "ResourceGatherer/Rates/food.fish")
return { "name": tech[0], "increasePriority": this.CostSum(template.cost) < 400 };
@ -121,24 +121,24 @@ PETRA.ResearchManager.prototype.researchWantedTechs = function(gameState, techs)
/** Techs to be searched for as soon as they are available, but only after phase 2 */
PETRA.ResearchManager.prototype.researchPreferredTechs = function(gameState, techs)
{
let phase2 = gameState.currentPhase() === 2;
let available = phase2 ? gameState.ai.queueManager.getAvailableResources(gameState) : null;
const phase2 = gameState.currentPhase() === 2;
const available = phase2 ? gameState.ai.queueManager.getAvailableResources(gameState) : null;
const numWorkers = phase2 ? gameState.getOwnEntitiesByRole(PETRA.Worker.ROLE_WORKER, true).length : 0;
for (let tech of techs)
for (const tech of techs)
{
if (!tech[1]._template.modifications)
continue;
let template = tech[1]._template;
const template = tech[1]._template;
if (phase2)
{
let cost = template.cost;
const cost = template.cost;
let costMax = 0;
for (let res in cost)
for (const res in cost)
costMax = Math.max(costMax, Math.max(cost[res]-available[res], 0));
if (10*numWorkers < costMax)
continue;
}
for (let i in template.modifications)
for (const i in template.modifications)
{
if (template.modifications[i].value === "ResourceGatherer/Rates/stone.rock")
return { "name": tech[0], "increasePriority": this.CostSum(template.cost) < 400 };
@ -160,7 +160,7 @@ PETRA.ResearchManager.prototype.update = function(gameState, queues)
if (queues.minorTech.hasQueuedUnits() || queues.majorTech.hasQueuedUnits())
return;
let techs = gameState.findAvailableTech();
const techs = gameState.findAvailableTech();
let techName = this.researchWantedTechs(gameState, techs);
if (techName)
@ -168,7 +168,7 @@ PETRA.ResearchManager.prototype.update = function(gameState, queues)
if (techName.increasePriority)
{
gameState.ai.queueManager.changePriority("minorTech", 2*this.Config.priorities.minorTech);
let plan = new PETRA.ResearchPlan(gameState, techName.name);
const plan = new PETRA.ResearchPlan(gameState, techName.name);
plan.queueToReset = "minorTech";
queues.minorTech.addPlan(plan);
}
@ -186,7 +186,7 @@ PETRA.ResearchManager.prototype.update = function(gameState, queues)
if (techName.increasePriority)
{
gameState.ai.queueManager.changePriority("minorTech", 2*this.Config.priorities.minorTech);
let plan = new PETRA.ResearchPlan(gameState, techName.name);
const plan = new PETRA.ResearchPlan(gameState, techName.name);
plan.queueToReset = "minorTech";
queues.minorTech.addPlan(plan);
}
@ -202,7 +202,7 @@ PETRA.ResearchManager.prototype.update = function(gameState, queues)
// remove also sharedLos if we have no ally
for (let i = 0; i < techs.length; ++i)
{
let template = techs[i][1]._template;
const template = techs[i][1]._template;
if (template.affects && template.affects.length === 1 &&
(template.affects[0] === "Healer" || template.affects[0] === "Outpost" || template.affects[0] === "Wall"))
{
@ -227,7 +227,7 @@ PETRA.ResearchManager.prototype.update = function(gameState, queues)
PETRA.ResearchManager.prototype.CostSum = function(cost)
{
let costSum = 0;
for (let res in cost)
for (const res in cost)
costSum += cost[res];
return costSum;
};