StarOS primer

StarOS runs your robot scripts. The language is Starlark: it reads like Python, it is deterministic, it has no clock, no random numbers, no files and no network of its own. A script sees only the names the server gives it.

The tick function

Every script defines def tick():, with no parameters. The server calls it once a turn.

def tick():
    robot.log("turn " + str(robot.turn))
  • Global variables do not survive between turns. Use memory.
  • Sets and while loops are allowed. Recursion and load are not.
  • Each run has a step limit set by the base (Mk1 100 000, Mk2 250 000, Mk3 600 000), a memory cap (16 KiB, 64 KiB, 256 KiB) and a turn deadline.
  • If a script fails (error, step limit, deadline), the robot idles that turn, its memory writes of that turn are discarded, and the reason is stored. Nobody else is affected.
  • Calls such as robot.move or drill.dig record an intention. The world changes after every script has run. A second move call replaces the first.

Memory

memory.get(key, default), memory.set(key, value), memory.delete(key), memory.keys(). Values are JSON; they are copied in and out, so changing a list you read does nothing until you set it again. A set that goes over the cap fails.

Modules every robot has

module what it gives
robot id, name, x, y, facing, turn, last (outcome of the previous turn), base, ports, ports_used, parts, health, max_health; move(direction), log(message) (10 a turn, 200 bytes)
sun light() (permille on your cell), hour(), day_turns (an attribute), is_day()
power networks(): your power systems as the last turn left them. Read only
industry buildings(): your producing buildings and stores. Read only
wallet balance() in drops (1 MT = 1 000 000 drops), pay(to, amount, memo=""), at most 5 payments a turn

There are also storage, contract, relay and json, math. The relay module belongs to an older grid whose devices no longer exist.

Modules that come with parts

A part you did not attach is not a name: using it is a compile error, found when you save and again when parts change.

part module main calls
modem (1 port) net, llm, jev, market net.online(), net.publish(topic, payload, level=0, retain=False), net.subscribe(filter), net.inbox()
drill (2 ports) drill dig(), 150 W; needs a hopper and an ore cell
hopper (1 port) hopper cargo(), free(), free(item), unload(), pickup(item, quantity); 4 000 kg and 1 600 L
lidar (1 port) lidar scan(), probe(direction), range (5)
battery_cell (1 port each) battery charge(), capacity() in Wh, is_charging(); 300 Wh a cell
builder (2 ports) builder build(kind, x, y, direction=""), build_ghost(id), ghosts(), pickup(id), repair(target), damaged()

net calls other than online() are errors while the robot is offline. A message published in turn N arrives at the start of turn N+1.

Rules that bite

  • Dig and unload act on the cell where the robot ends the turn.
  • hopper.unload() and hopper.pickup() reach only the four cells that touch the robot, not the diagonals.
  • hopper.load is not a valid expression: load is a Starlark keyword. Use cargo().
  • A robot that cannot pay its idle power does not run at all: outcome no_power.

Five complete examples

1. Dig where you stand

One line of explanation: a drill and a hopper on an ore cell, taken from the game's own tests; on a cell with no ore it fails with a readable error.

def tick():
    drill.dig()

2. Hauler of last resort

One line of explanation: the default of a robot with a hopper and no drill walks to your nearest storage and empties itself.

# Default script of a hopper robot: it empties its cargo into your storage.
# While the hopper holds something, it walks to the nearest storage of its
# owner (depot, crate, warehouse, silo or tank) on its field, and unloads when
# it touches one. Load it by hand, or from a drill robot or a train container
# with hopper.pickup. With nothing to carry it waits. Edit it: it is yours.
STORES = ["depot", "storage_crate", "warehouse", "silo", "tank"]

def absolute(value):
    if value < 0:
        return -value
    return value

def nearest_store():
    best = None
    best_distance = 0
    for building in industry.buildings():
        if building["kind"] in STORES and building["field"] == robot.field:
            distance = max(absolute(building["x"] - robot.x), absolute(building["y"] - robot.y))
            if best == None or distance < best_distance:
                best = building
                best_distance = distance
    return best

def step_toward(dx, dy):
    # Longer axis first; after a blocked turn, the other axis.
    blocked = robot.last.startswith("blocked")
    along_x = absolute(dx) >= absolute(dy)
    if blocked:
        along_x = not along_x
    if along_x and dx == 0:
        along_x = False
    if not along_x and dy == 0:
        along_x = True
    if along_x:
        robot.move("east" if dx > 0 else "west")
    else:
        robot.move("south" if dy > 0 else "north")

def tick():
    cargo = hopper.cargo()
    if len(cargo) == 0:
        return
    store = nearest_store()
    if store == None:
        robot.log("no storage of yours on this field: place a depot or a crate")
        return
    dx = store["x"] - robot.x
    dy = store["y"] - robot.y
    if max(absolute(dx), absolute(dy)) <= 1:
        hopper.unload()
    else:
        step_toward(dx, dy)

Watch the diagonal: this shipped script calls unload() as soon as the storage is within one step, diagonals included, but unload() only reaches the four touching cells. A robot stuck on a corner repeats a failed unload. Step to a side cell first.

3. Miner

One line of explanation: the default of a drill, hopper and lidar digs the nearest deposit in sight, then walks home to unload (same diagonal caveat as above).

# Default script of a miner: a robot with a drill, a hopper and a lidar. It digs
# the nearest deposit it sees, one dig a turn, until the hopper is full, then
# walks to the nearest storage of its owner (depot, crate, warehouse, silo or
# tank), unloads next to it, and goes back to mining. With no deposit in sight
# it explores. A deposit that gave nothing is left alone for good. Edit it: it
# is yours.
DIRECTIONS = ["north", "east", "south", "west"]
ORE_TERRAINS = [
    "copper_ore", "iron_ore", "ice", "bornite_ore", "hematite_ore", "nickel_iron_ore", "cobalt_sulphide_ore", "pgm_ore_ore",
    "olivine_ore", "pyroxene_ore", "chondrite_ore", "clay_ore", "ilmenite_ore", "anorthite_ore", "helium3_regolith_ore",
    "kreep_ore", "ammonia_ice", "methane_clathrate", "bauxite_ore", "spodumene_ore", "lithium_brine_ore", "uraninite_ore",
    "cassiterite_ore", "wolframite_ore", "sphalerite_ore", "galena_ore", "native_gold_ore", "silver_ore", "monazite_ore",
    "bastnasite_ore", "xenotime_ore", "columbite_tantalite_ore", "molybdenite_ore",
]
MIN_ROOM = 400  # kilograms of room under which the hopper counts as full (hopper.free() answers kilograms)
STORES = ["depot", "storage_crate", "warehouse", "silo", "tank"]

def absolute(value):
    if value < 0:
        return -value
    return value

def free(direction):
    probe = lidar.probe(direction)
    return probe["kind"] == "clear" or probe["distance"] > 1

def step_toward(dx, dy):
    # One step along the longer axis, the other axis when that one is blocked.
    horizontal = "east" if dx > 0 else "west"
    vertical = "south" if dy > 0 else "north"
    order = []
    if absolute(dx) >= absolute(dy):
        order = [horizontal, vertical]
    else:
        order = [vertical, horizontal]
    for direction in order:
        along_x = direction in ["east", "west"]
        if ((along_x and dx != 0) or (not along_x and dy != 0)) and free(direction):
            robot.move(direction)
            return True
    return False

def nearest_store():
    best = None
    best_distance = 0
    for building in industry.buildings():
        if building["kind"] in STORES and building["field"] == robot.field:
            distance = max(absolute(building["x"] - robot.x), absolute(building["y"] - robot.y))
            if best == None or distance < best_distance:
                best = building
                best_distance = distance
    return best

def nearest_ore(spent):
    best = None
    best_distance = 0
    for cell in lidar.scan():
        if cell["terrain"] in ORE_TERRAINS and cell["robot"] == None and cell["structure"] == None and [cell["x"], cell["y"]] not in spent:
            distance = max(absolute(cell["dx"]), absolute(cell["dy"]))
            if best == None or distance < best_distance:
                best = cell
                best_distance = distance
    return best

def explore():
    heading = memory.get("heading", "east")
    for turn in range(4):
        if free(heading):
            robot.move(heading)
            memory.set("heading", heading)
            return
        heading = DIRECTIONS[(DIRECTIONS.index(heading) + 1) % 4]

def unload():
    store = nearest_store()
    if store == None:
        robot.log("no storage of yours on this field: place a depot or a crate")
        return
    dx = store["x"] - robot.x
    dy = store["y"] - robot.y
    if max(absolute(dx), absolute(dy)) <= 1:
        hopper.unload()
    elif not step_toward(dx, dy):
        explore()

def total(cargo):
    count = 0
    for item in cargo:
        count += cargo[item]
    return count

def tick():
    carried = total(hopper.cargo())
    if hopper.free() < MIN_ROOM:
        memory.set("returning", True)
    elif carried == 0:
        memory.set("returning", False)
    if memory.get("returning", False):
        unload()
        return
    spent = memory.get("spent", [])
    here = [robot.x, robot.y]
    last = memory.get("dug", None)
    if last != None and last[0] == here and carried <= last[1]:
        spent = spent + [here]
        memory.set("spent", spent[-50:])
        memory.set("dug", None)
        last = None
    target = memory.get("target", None)
    if target == here and here not in spent:
        memory.set("dug", [here, carried])
        drill.dig()
        return
    ore = nearest_ore(spent)
    if ore == None:
        memory.set("target", None)
        explore()
        return
    memory.set("target", [ore["x"], ore["y"]])
    if not step_toward(ore["dx"], ore["dy"]):
        explore()

4. Crane

One line of explanation: beside a train stop, it moves the first loaded wagon's container into the first free yard slot.

# Default script of a crane robot. Park it so that it touches a train stop of
# its owner. Each turn it does one of two things: with an empty grip it lifts the
# container of the first wagon that carries one (wagon:1 to wagon:10, the
# train whose locomotive is at the stop); with a container in the grip it sets
# it down in the first free slot of the stop's yard (yard:1 to yard:4). One
# turn can do both: the lift comes before the placing. A full yard leaves the
# container in the grip. Edit it: it is yours.
WAGONS = 10
SLOTS = 4

def free_slot():
    for slot in range(1, SLOTS + 1):
        if crane.look("yard:" + str(slot)) == None:
            return "yard:" + str(slot)
    return None

def loaded_wagon():
    for wagon in range(1, WAGONS + 1):
        if crane.look("wagon:" + str(wagon)) != None:
            return "wagon:" + str(wagon)
    return None

def tick():
    slot = free_slot()
    if crane.grip() == None:
        wagon = loaded_wagon()
        if wagon != None and slot != None:
            crane.lift(wagon)
            crane.place(slot)
    elif slot != None:
        crane.place(slot)
    else:
        robot.log("the yard is full")

5. Builder

One line of explanation: it turns the ghosts you planned on the map into real structures, fetching stock as needed.

# Default script of a builder: a robot with a builder, a hopper and a lidar. It
# builds the ghosts its owner planned on the map (a ghost is a translucent plan
# that costs nothing; the real structure needs one unit of its item). Each turn
# it takes the nearest ghost whose item it carries, walks to a cell next to it
# and builds it. With no stock for any ghost it walks to the nearest storage of
# its owner that holds an item a ghost needs, stands next to it and picks one
# unit up into the hopper (the unit must fit the hopper). With nothing to build
# it waits. Edit it: it is yours.
DIRECTIONS = ["north", "east", "south", "west"]
STORES = ["depot", "storage_crate", "warehouse", "silo", "tank"]

def absolute(value):
    if value < 0:
        return -value
    return value

def free(direction):
    probe = lidar.probe(direction)
    return probe["kind"] == "clear" or probe["distance"] > 1

def step_toward(dx, dy):
    # One step along the longer axis, the other axis when that one is blocked.
    horizontal = "east" if dx > 0 else "west"
    vertical = "south" if dy > 0 else "north"
    order = []
    if absolute(dx) >= absolute(dy):
        order = [horizontal, vertical]
    else:
        order = [vertical, horizontal]
    for direction in order:
        along_x = direction in ["east", "west"]
        if ((along_x and dx != 0) or (not along_x and dy != 0)) and free(direction):
            robot.move(direction)
            return True
    return False

def explore():
    heading = memory.get("heading", "east")
    for turn in range(4):
        if free(heading):
            robot.move(heading)
            memory.set("heading", heading)
            return
        heading = DIRECTIONS[(DIRECTIONS.index(heading) + 1) % 4]

def steps_to(x, y):
    return absolute(x - robot.x) + absolute(y - robot.y)

def stocked_store(kind):
    best = None
    best_steps = 0
    for building in industry.buildings():
        if building["kind"] in STORES and building["field"] == robot.field and building["input"].get(kind, 0) > 0:
            steps = steps_to(building["x"], building["y"])
            if best == None or steps < best_steps:
                best = building
                best_steps = steps
    return best

def build(ghost):
    steps = steps_to(ghost["x"], ghost["y"])
    if steps == 1:
        builder.build_ghost(ghost["id"])
    elif steps == 0:
        # A robot cannot build on its own cell: step off the ghost.
        explore()
    elif not step_toward(ghost["x"] - robot.x, ghost["y"] - robot.y):
        explore()

def fetch(store, kind):
    steps = steps_to(store["x"], store["y"])
    if steps == 1:
        hopper.pickup(kind, 1)
    elif not step_toward(store["x"] - robot.x, store["y"] - robot.y):
        explore()

def tick():
    ghosts = builder.ghosts()
    if len(ghosts) == 0:
        return
    cargo = hopper.cargo()
    for ghost in ghosts:
        if cargo.get(ghost["kind"], 0) > 0:
            build(ghost)
            return
    for ghost in ghosts:
        store = stocked_store(ghost["kind"])
        if store != None:
            fetch(store, ghost["kind"])
            return
    robot.log("no stock for any ghost: fill a depot or the hopper")

Other hosts

Trains, power stations, wormhole gates and spacecraft also run StarOS with their own modules (train, power_controller, gate, ship). Every host starts with a documented default script, and Reset to default brings it back.

Full reference

The game generates the API reference from the same code that runs your scripts. See it on each part's page under Robot parts in the game, on your robot's page, or ask your agent to call staros_reference. The reference wins any argument with this page.