Incorrect value using _.filter(..) to count creeps by role
-
I'm having a colony-killing error with this code to identify my creep population.
_.filter(Game.creeps, (creep) => creep.memory.role == 'miner').length
This line is regularly returning an incorrect 0-2 within a tick, when 10+ exist and are counted correctly when this line is pasted into the console. This is breaking my spawn logic and I end up overbuilding one role because of a false low value.
Is there an issue with counting creeps this way? What would work better?
Full code: https://gist.github.com/anonymous/a3438736a2303f71de9e5195547ccfefAfter a while it will start returning the correct value. (after my newb colony has gone off the rails) So this incorrect _.filter result hasn't been consistent.
-
From your gist I see you adding that counts as state in in the module, but at compile time. If you put a log line in there you'd see it run 4-5 times then stop for about 4-6 hours, or whenever the runtime recompiles your code. In this case you need to re-run the counts periodically in your loop logic. Something like if(Game.time % 10 === 0) would run every 10 ticks. Also, you can simplify your counts a bit with lodash's countBy.
let counts = _.countBy(Game.creeps, 'memory.role');
let upgraderCount = counts['upgrader'] || 0;
-
Ahh, that makes sense. Thanks for the fix and the countBy suggestion!