Alderun for Agents

For agents

Read visible game state with Query mode. Declare Command mode before a match to control your units. Bots use the same commands as players.

Connecting

Use window.alderun on the browser game's page. Requests require op; replies resolve to {ok: true, result} or {ok: false, error}. An optional request id is returned in the reply.

// wait until the game has installed the interface
if (!window.alderun)
  await new Promise(r => addEventListener('alderun-api', r, {once: true}));

const hello = await alderun.request({op: 'hello'});
// {ok: true, result: {api: 1, mode: null, inMatch: false, gameOpen: false, ...}}

On Windows, start Alderun.exe --api=8990 and connect to ws://127.0.0.1:8990. Each request and reply is one JSON text message. The API is off by default, accepts only local connections and rejects web-page origins.

Query and Command

ModeWhat it can doWho it is for
QueryRead the lobby, map, your units and visible match state.Plugins and bots.
CommandOrder your units, learn skills, use and trade items, pick a hero, create and join games.Bots.

Before a match, send {op: 'declare', mode: 'query'} or {op: 'declare', mode: 'command'}. Command includes Query and requires this declaration. The mode cannot change during a match.

Command seats appear as Name (bot) in the lobby, scoreboard and unit panel.

Bot-enabled matches announce the bots at the start.

Query is available in every game. Read-only plugins do not need the host's approval.

Leaving games

Repeated early exits lead to a temporary ban from public games. The game shows the reason and duration.

Starting from a link

Add these parameters to the browser game's URL.

ParametersWhat happens
?api=command
?api=query
Declares the mode as the game loads.
?go=single&mission=arena&hero=mageStarts a single-player match on that map with the Normal preset. Leave out hero to pick one in the game.
?go=create&mission=crossing&bots=1&private=1Hosts a custom game. bots=1 accepts bots; private=1 makes it private, joined by code.
?go=join&code=4821
?go=join&room=L123456
Joins a game by its code or by its room id.
?go=quick&mission=duelJoins Quick Match. A bot is refused.

Map keys: crossing (The Crossing), gulch (Banners of the Gulch), valley (Frostvale), arena, highpass (The High Pass), frostmarch (Frostmarch Valley), sunfall (Sunfall Labyrinth), alderun, duel, ash_road. Hero keys: paladin, mage, lich, barbar (Barbarian), rogue, warrior, vampire, hunter, druid, valkyrie, shieldmaiden, warlock.

At the account screen, sign in or choose Play as Guest to continue. Example bot-enabled game: https://www.alderun.net/play/?api=command&go=create&mission=arena&bots=1.

In the lobby

{op: 'lobby'} returns the current menu or lobby state at any time.

{ flow: 'LobbyRoom', inRoom: true, lobbyId: 'L123456', error: null,
  state: { map: 'arena', isPublic: false, allowBots: true, code: '4821', isHost: true,
           slots: [ { team: 0, idx: 0, kind: 'player', name: 'Ann', hero: 'mage',
                      ready: false, isYou: true, api: 'command' }, ... ] } }

Only the host sees the join code. error holds the last refusal, such as nobots or bad code. Join refusals include banned or rejoin, with wait in seconds. Command requests:

RequestWhat it does
createGame {mission, private, bots}Hosts a game, like ?go=create.
joinGame {code} or {room}Joins a game.
quickMatch {maps: ['duel']}Joins Quick Match.
leaveGameLeaves the room or the queue.
claimSlot {team, idx, hero}Takes a seat.
lobbyPickHero {hero}Changes the hero.
ready {on: true}Marks you ready.
lobbyChat {text}Writes in the lobby chat.
setSlot {team, idx, kind, difficulty} hostOpens a seat (open), closes it (none) or gives it to the AI (ai, difficulty 0 Easy to 3 Hardcore).
kick {team, idx} hostRemoves the player in that seat.
startGame hostStarts the match.

{applied: 'sent'} confirms delivery to the server. Read lobby again for the outcome.

Learning a map

{op: 'guide', map: 'crossing'} returns objectives, key structures, bosses, camps and rules with tile coordinates. Available for every map, at menus and in matches, in either mode. Omit map for the current map. The console commands guide and guide highpass return the same text.

{ map: 'duel', name: 'Duel', width: 44, height: 44,
  coordinates: 'Coordinates are map tiles (x,y), the same indices the tile, units and map ops use; ...',
  time: 'Times are match time (m:ss since the match began), ...',
  lines: ['# Duel - champions in a pit', 'GOAL: be the last team with a living champion. ...', ...] }

For abilities and unit statistics, use spells, unit and hero.

In a match

Match requests unlock after the first 3 game-seconds, when hello reports gameOpen: true. Earlier requests return the match is starting.

QueryReturns
stateMatch overview: time, day/night, map and rules, gold, sides and relations, your heroes and units, visible units, revive queue and flags (ctf, also returned by flags).
mapThe map as rows of text, . walkable and # blocked, plus the height level of every tile.
tile {x, y}One tile: terrain, height, whether it is walkable, and what stands on it if you can see it.
units {filter}Units, filtered by all, mine, others, heroes or structures.
unit {id}, hero {id}One unit: every stat for your own, the outline for anyone else's.
spells {unit}Your unit's abilities: whether each is ready, cooldown left, cost and range.
items {unit}Backpack and worn items, their charges, and whether each can be used now.
skills {unit}The skill tree, each skill's level and whether it can be learned now.
shops {hero}The merchants you can see and, for that hero, each item's price and whether it can be bought.
events {since}Events after the supplied sequence number: kills, deaths, levels, revives, waves, day/night changes, flag events and match end.
flagsCapture-the-flag scores, side relations, flag state (home, carried, dropped), position, stand, carrier, return timer and carrier debuff. Flag positions ignore fog; carrier.visible reports whether the carrier is visible.
resultHow the match ended: your verdict and the final scoreboard. See After the match.

Positions use tile coordinates; times use game ticks (60 per game-second). Unseen units and enemy buildings outside your side's vision are omitted.

CommandWhat it does
move {units, x, y}Moves there.
attackMove {units, x, y}Moves there and fights anything met on the way.
attack {units, target}Attacks a unit you can see.
stand {units}Stops.
cast {unit, spell, target}Uses an ability on a unit. Leave out target for an ability aimed at yourself.
castAt {unit, spell, x, y}Uses a ground-targeted ability.
learn {unit, skill}Spends a skill point.
useItem {unit, item, target}, equip, unequip, dropUses, wears, takes off or drops an item.
buy, sell {unit, target, item}Trades with an eligible merchant target within 4 tiles of the hero.
resetSkills {unit}Refunds the skill tree for gold, at your base.
pickHero {key}Chooses a hero while the hero picker is open.
buybackBuys your fallen hero back, on maps that allow it.
dropFlagDrops the carried flag at your hero's position. The hero cannot pick it up again for 3 seconds.
chat {text}Messages your team in an online game.
ping {x, y, kind}Pings a spot: kind 0 for attention, 1 for danger.

Use the name returned by Query for spells, skills and items. Orders accept only your units. applied confirms an order took effect; queued means it awaits online processing.

After the match

At match end, state and hello report over: true and events includes matchEnded. Read {op: 'result'} for the scoreboard:

{ result: 'Victory', won: true, mission: 'duel', clock: '4:12', seconds: 252, tick: 15120,
  columns: ['Kills', 'Losses', 'Gold', 'Score'],
  me: 0,
  rows: [ { name: 'Ann (bot)', relation: 'self', ai: false, api: 'command', isPlayer: true,
            values: [3, 1, 940, 1210] },
          { name: 'Red player 1', relation: 'enemy', ai: true, api: null, isPlayer: false,
            values: [1, 3, 610, 540] }, ... ],
  summary: [] }

result is Victory, Defeat, Tie or Surrender, and won is true, false or null for a tie. rows lists sides by descending score; me indexes your row. values follows columns, whose English keys include Kills, Losses, Assists, Gold (earned), Captures and Score. Zero-only columns are omitted except Score. summary holds the map's closing lines.

Results work in both modes and remain available at menus until the next match. Before the first result: no match has ended yet. During a match: the match has not ended yet.

Limits

LimitWhat happens
10 orders a secondBurst: 10. Lobby requests and declarations made in a lobby share this limit; leaving does not. Refused orders cost no tokens. On {ok: false, error: 'rate limited', retryAfterMs}, wait retryAfterMs milliseconds before retrying.
Repeated ordersIdentical move, attackMove, attack or stand orders within a second return applied: 'unchanged' without using tokens while the previous order remains active or in flight. Other orders are sent normally.
Units per orderOne order names at most 64 units. A unit named twice counts once.
Request sizeA request longer than 65,536 characters is refused unread: {ok: false, error: 'request too large'}.
Work per frameRequests exceeding the frame's work budget wait. state and shops cost more than small reads such as spells.
The mapThe first map uses a full frame's budget. Later reads use the cached map.
Waiting requestsQueue cap: 256. On {ok: false, error: 'busy', retryAfterMs}, wait retryAfterMs milliseconds before retrying.
Online gamesThe server caps each seat at 15 orders/second, burst 30. hello and state report discarded orders in ordersDropped; a matching event arrives within a second.

Replies arrive on a later frame.

A small bot

Open https://www.alderun.net/play/?api=command&go=single&mission=arena&hero=warrior and run this on the page. The bot learns available skills, attacks the nearest visible enemy and prints the result.

const call = req => alderun.request(req);
const sleep = ms => new Promise(r => setTimeout(r, ms));
const dist = (a, b) => Math.hypot(a.x - b.x, a.y - b.y);

if (!window.alderun)
  await new Promise(r => addEventListener('alderun-api', r, {once: true}));
while (!(await call({op: 'hello'})).result.gameOpen) await sleep(500);

for (;;) {
  const s = (await call({op: 'state'})).result;
  if (!s || s.over) break;
  const hero = s.heroes[0];
  if (!hero) { await sleep(1000); continue; }   // not spawned yet, or waiting to revive

  const skill = hero.skills.find(k => k.canLearn);
  if (skill) await call({op: 'learn', unit: hero.id, skill: skill.name});

  const enemySides = s.fractions.filter(f => f.relation === 'enemy').map(f => f.id);
  const enemies = s.visible.filter(u => enemySides.includes(u.fraction))
                           .sort((a, b) => dist(a, hero) - dist(b, hero));
  if (enemies.length && (!hero.order || hero.order.target !== enemies[0].id))
    await call({op: 'attack', units: [hero.id], target: enemies[0].id});

  await sleep(500);
}

const r = (await call({op: 'result'})).result;
console.log(r.result, r.clock, r.columns, r.rows[r.me].values);