The interface underneath
The short way is built on this interface, and a bot may use it directly: a module whose
default export has create is given the plain view and a list of orders, and keeps its
own books.
A JavaScript bot plays as a client of BWAPI 4.4.0, the library BWAPI
bots are written for. You do not need to know BWAPI to write one.
What it means for you is that unit types have BWAPI's names (Terran_Marine), and that an
order goes into the game as a player's click would, so the game checks it the same way.
The module#
/** @type {import("@scm-js/bot").BotModule} */
export default {
name: "Do nothing",
create(init) {
// called once, before the first frame
return {
onFrame(view, api) {
// called with each view; give orders through api
},
onEnd(result) {
// optional: result.result is "victory", "defeat" or "ended"
},
};
},
};
create and onFrame may be async. The module may also set frameInterval, a
version and an author. Everything a bot needs at run time arrives in init and
view, including the tables of names (init.data.UnitTypes and the rest), so a bot in
plain JavaScript imports nothing.
What a bot is told once#
init holds:
| Field | What it is |
|---|---|
api |
The interface's version, BOT_API: 1 |
self, race, name |
The bot's player number (0 to 7), its race (0 zerg, 1 terran, 2 protoss, already drawn if it was random) and the name it was seated under |
players |
Everyone seated: id, name, race, isSelf, isEnemy. There are no teams yet, so everyone else is an enemy |
frameInterval |
Frames between views unless the bot asks otherwise |
map |
The map, below |
data |
The game's tables, below |
mod |
In a mod's game, the mod's name and hash |
useMapSettings, limits |
In a game with the map's own settings: the bot starts with the map's units, and limits says what the map keeps from it (forbiddenUnits, unavailableTechs, upgradeMax) |
init.map is what a player who knows the map knows before the game starts:
width,heightin tiles (a tile is 32 pixels), and thetileset's name;walkable: one byte per 8-pixel cell,width * 4to a row, 1 where the ground can be walked on (terrain only: buildings and units are not in it);buildable: one byte per tile, 1 where the terrain takes a building;groundHeight: one byte per tile, 0 low, 2 high, 4 very high, odd where a doodad blocks the view;startLocations: each with its point (x,yin pixels), the top-left tile of a town hall built there (tileX,tileY), and theplayerseated there, or -1;resources: every mineral field and geyser with itsid,type, position and starting amount. The id can be used as agathertarget even while the field is out of sight.
init.data holds the name tables (UnitTypes, TechTypes, UpgradeTypes, Orders,
Races, each a name to a number) and the game's own numbers, indexed by number:
units[type]:name,race,mineralPrice,gasPrice,buildTime(frames),supplyRequiredandsupplyProvided(in halves: a marine is 2, a zergling 1, a depot gives 16),tileWidthandtileHeightfor buildings, the collision box (dimensionLeft,dimensionUp,dimensionRight,dimensionDown),maxHitPoints,maxShields,armor,sightRange(tiles),topSpeed,groundWeaponandairWeapon(numbers inweapons, or -1), flags such asisBuilding,isWorker,isFlyer,isResourceDepot,isRefinery,isDetector,requiresPsiandrequiresCreep, and the tech tree:whatBuilds(the type that makes it),buildsWhat, andrequiredUnits, where every entry is needed and any one type of an entry will do;techs[id]: prices,researchTime,energyCost,whatResearches;upgrades[id]: prices and time for the first level with what each further level adds,maxRepeats,whatUpgrades;weapons[id]:damageAmount,damageBonus,damageCooldown,damageFactor,minRangeandmaxRange(pixels, edge to edge),targetsAir,targetsGround,damageType, and the three splash radii.
What a bot is shown#
view, each frame:
| Field | What it is |
|---|---|
frame |
The game's frame counter. 24 frames is a second at normal speed |
self |
minerals, gas, supplyUsed and supplyTotal (in halves), techs (the numbers researched), upgrades (the level of each) |
units |
The bot's own units and buildings, in full |
enemies |
Other players' units the bot's player sees now |
neutral |
Mineral fields, geysers and critters in sight now |
events |
What changed since the last view the bot was given |
visibility |
One byte per tile: 0 never seen, 1 seen before, 2 in sight now. Copy what you want to keep; the array may be reused |
Every unit has id, type, player, x, y (pixels, its centre), hitPoints,
shields, energy, resources (what is left in a field, a geyser or a gas building),
angle (0 to 255, clockwise from up), and the flags isCompleted, isFlying,
isCloaked, isBurrowed, isMoving, isSieged, isLifted, isLockedDown,
isStasised, isEnsnared, isPlagued, isIrradiated and isDefenseMatrixed.
The bot's own units add what only their owner knows: order (a number in Orders),
orderTarget, targetX, targetY, isIdle, isGatheringMinerals, isGatheringGas,
isCarryingMinerals, isCarryingGas, isConstructing, buildType (what a worker is
about to build, or what an egg becomes), trainingQueue, isTraining,
remainingBuildTime, remainingTrainTime, tech, upgrade, remainingResearchTime,
the three cooldowns, isLoaded, loadedUnits, transport (the transport the unit is
inside, or -1), isPowered, spiderMineCount, killCount, isStimmed, isMorphing,
addon (a terran building's add-on, or -1) and rallyX, rallyY, rallyUnit (-1 when
there is no rally point). A unit in training, a building under construction and an egg are
in the list with isCompleted false.
Counting what is on its way takes care, and the short way's count does it for you:
- The unit a building is training is in
units, unfinished, and is also the first entry of that building'strainingQueue. Count one of the two, or the same marine is counted twice. - An egg has the type
Zerg_Egg, and what it becomes is itsbuildType. An egg of a type withisTwoUnitsInOneEgg(zerglings, scourge) becomes two units; the type'smineralPriceis the egg's, itssupplyRequiredeach unit's. - A worker told to build shows the building in
buildTypeuntil the building is started. A terran or protoss building then appears as a unit of its own; a zerg worker becomes the building and keeps its id.
An id belongs to one unit for the whole game. Events are unitCreate, unitComplete,
unitMorph and unitDestroy for the bot's own units, and unitShow and unitHide for
other players' units coming into sight and leaving it; an enemy or a mineral field seen to
die is a unitDestroy. They cover the time since the last view the bot was given, which
is longer than one interval when views were skipped.
What a bot sees#
A bot sees what a player in its seat would see, by the game's own sight, high ground
included. Its own units are there in full. Another player's unit is there only while it is
in sight, and a cloaked or burrowed one only while one of the bot's detectors reaches it.
Resources are there as the map places them (init.map.resources), with their amounts
while in sight. The bot sees its own money, supply, techs and upgrades, and nobody else's.
The same rule covers orders. BWAPI takes no order aimed at a unit the bot cannot see: a target must be one of its own units, a unit in sight, or a resource. A worker sent to gather from a field out of sight walks there and is told to gather once the field is in sight.
Orders#
api has a method for each order, and each takes one unit's id or a list of them:
api.move(units, x, y, queued)
api.attack(units, enemyId) // attack that unit
api.attack(units, { x, y }) // attack-move
api.rightClick(units, target)
api.patrol(units, x, y)
api.stop(units)
api.holdPosition(units)
api.gather(workers, resourceId) // a mineral field or a finished gas building
api.returnCargo(workers)
api.train(producer, unitType) // a building; or a larva, or a hatchery (one of its larvae morphs)
api.build(worker, unitType, tileX, tileY) // the tile is the building's top-left
api.buildAddon(building, unitType)
api.research(building, tech)
api.upgrade(building, upgrade) // the next level
api.useTech(caster, tech, target) // a spell, by its tech
api.cloak(units); api.decloak(units)
api.morph(units, unitType) // a hatchery into a Lair, a hydralisk into a lurker …
api.cancelConstruction(building) // three quarters of the price back
api.cancelTrain(building, slot) // slot 0 is the unit under way; without a slot, the last one queued
api.cancelResearch(building); api.cancelUpgrade(building)
api.cancelMorph(units) // an egg, a morphing building
api.cancelAddon(building)
api.siege(tanks); api.unsiege(tanks)
api.burrow(units); api.unburrow(units)
api.stim(units)
api.load(units, transport) // into a transport or a bunker
api.unload(transport, unit); api.unloadAll(transports)
api.unloadAllAt(transports, x, y) // fly there and put everything out
api.lift(buildings); api.land(building, tileX, tileY)
api.placeNydusExit(canal, tileX, tileY)
api.setRallyPoint(buildings, target) // a point { x, y } or a unit's id
api.mergeArchon(units); api.mergeDarkArchon(units)
api.repair(scvs, target)
api.heal(medics, target) // a unit's id, or a point to walk to, healing on the way
api.rechargeShields(battery, unit)
api.command({ kind: "move", units: [...], x, y }) // any order as a plain object
Orders are collected while onFrame runs and sent when it returns, or when its promise
settles. Each goes in as a BWAPI command, and BWAPI and then the game check it as they
would a player's click: a unit is trained only by the building that trains it, with its
requirements standing; a tech or an upgrade only at its own building; a spell only by a
unit that has it; a building only on a site the game takes. An order that is refused, for
want of money or supply or because the site turned out to be taken, does nothing, and the
next view shows what happened. Calling off a nuclear strike is not possible: BWAPI has no
command for it.
Two of the game's rules catch every new bot written on this interface. A building is paid for when its construction starts, once the worker has reached the site, not when the order is given: money spent on something else while the worker walks leaves it at the site with nothing built. And the game places no building on ground nobody has seen: a worker sent there is turned away.
Questions#
The game answers what a bot cannot work out from the view. Each question returns a promise:
const ok = await api.canBuildHere(tileX, tileY, unitType, builderId);
const why = await api.placement(tileX, tileY, unitType, builderId, checkCost);
// "ok", or the first rule that fails: "requirements", "cost", "bounds", "terrain", "occupied",
// "unit", "creep", "nocreep", "psi", "resources" (a hall too close to minerals), "geyser"
const site = await api.getBuildLocation(unitType, nearTileX, nearTileY, { radius });
// { tileX, tileY } or null
placement is BWAPI's canBuildHere with the reason the game's rules give. Ground nobody
has seen reads as "occupied", and with a builder named, a unit in the way can read as
"requirements": ask without the builder for the plain reason. getBuildLocation is
BWAPI's: a site the rules take within radius tiles (64 unless given) of the tile, the
nearest free geyser for a gas building, and for a town hall the best spot BWAPI knows,
which may be at another base than the one asked about. It does not check the price or the
tech tree, whether a worker can walk there, or whether the bot has just sent another
worker to the same tiles. The game does not wait for a bot waiting for an answer.
Timing#
A bot is given a view every 8 frames unless it asks otherwise: frameInterval on the
module, or api.setFrameInterval(n) at any time, from 1 to 240. On the page the game
never waits for a bot; a view that comes due while the bot is still answering the last one
is skipped and counted, and the next one is current. The command line waits for every
answer, which is why its games repeat. api.log(text) writes a line, as game.log does.