Introduction à StarOS
StarOS exécute les scripts de vos robots. Le langage est Starlark : il se lit comme du Python, il est déterministe, il n'a ni horloge, ni nombres aléatoires, ni fichiers, ni réseau à lui. Un script ne voit que les noms que le serveur lui donne.
La fonction tick
Chaque script définit def tick():, sans paramètre. Le serveur l'appelle une fois par tour.
def tick():
robot.log("tour " + str(robot.turn))
- Les variables globales ne survivent pas d'un tour à l'autre. Utilisez
memory. - Les ensembles et les boucles
whilesont permis. La récursion etloadne le sont pas. - Chaque exécution a une limite d'étapes selon la base (Mk1 100 000, Mk2 250 000, Mk3 600 000), un plafond de mémoire (16 Kio, 64 Kio, 256 Kio) et une échéance du tour.
- Si un script échoue (erreur, limite d'étapes, échéance), le robot reste immobile ce tour-là, ses écritures en mémoire sont jetées et la raison est conservée. Les autres ne sont pas touchés.
- Des appels comme
robot.moveoudrill.diginscrivent une intention. Le monde change après l'exécution de tous les scripts. Un deuxième appel de déplacement remplace le premier.
Mémoire
memory.get(clé, défaut), memory.set(clé, valeur), memory.delete(clé), memory.keys(). Les valeurs sont du JSON, copiées à l'entrée comme à la sortie : modifier une liste lue ne change rien tant qu'on ne refait pas set. Un set qui dépasse le plafond échoue.
Modules que tous les robots ont
| module | ce qu'il donne |
|---|---|
robot |
id, name, x, y, facing, turn, last (résultat du tour précédent), base, ports, ports_used, parts, health, max_health ; move(direction), log(message) (10 par tour, 200 octets) |
sun |
light() (pour mille sur votre case), hour(), day_turns (un attribut), is_day() |
power |
networks() : vos réseaux électriques tels que le dernier tour les a laissés. Lecture seule |
industry |
buildings() : vos bâtiments de production et entrepôts. Lecture seule |
wallet |
balance() en « drops » (1 MT = 1 000 000 drops), pay(to, amount, memo=""), au plus 5 paiements par tour |
Il y a aussi storage, contract, relay, json et math. Le module relay appartient à un ancien réseau électrique dont les appareils n'existent plus.
Modules apportés par les pièces
Une pièce non installée n'est pas un nom : l'utiliser est une erreur de compilation, détectée à l'enregistrement et à chaque changement de pièces.
| pièce | module | appels principaux |
|---|---|---|
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 ; exige une trémie et une case de minerai |
hopper (1 port) |
hopper |
cargo(), free(), free(item), unload(), pickup(item, quantity) ; 4 000 kg et 1 600 L |
lidar (1 port) |
lidar |
scan(), probe(direction), range (5) |
battery_cell (1 port chacune) |
battery |
charge(), capacity() en Wh, is_charging() ; 300 Wh par cellule |
builder (2 ports) |
builder |
build(kind, x, y, direction=""), build_ghost(id), ghosts(), pickup(id), repair(target), damaged() |
Les appels de net autres que online() sont des erreurs quand le robot est hors ligne. Un message publié au tour N arrive au début du tour N+1.
Les règles qui mordent
- Creuser et décharger se font sur la case où le robot termine son tour.
hopper.unload()ethopper.pickup()n'atteignent que les quatre cases voisines, pas les diagonales.hopper.loadn'est pas une expression valide :loadest un mot-clé de Starlark. Utilisezcargo().- Un robot qui ne peut pas payer sa consommation au repos ne s'exécute pas du tout : résultat
no_power.
Cinq exemples complets
Les commentaires des scripts sont en anglais, comme dans le jeu.
1. Creuser sur place
En une ligne : une foreuse et une trémie sur une case de minerai, tiré des tests du jeu ; sur une case sans minerai, une erreur lisible.
def tick():
drill.dig()
2. Le débardeur
En une ligne : le script par défaut d'un robot à trémie sans foreuse marche vers votre entrepôt le plus proche et se vide.
# 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)
Attention à la diagonale : ce script livré appelle unload() dès que l'entrepôt est à un pas, diagonales comprises, mais unload() n'atteint que les quatre cases voisines. Un robot pris dans un coin répète un déchargement raté. Faites-le d'abord passer sur une case de côté.
3. Mineur
En une ligne : le script par défaut avec foreuse, trémie et lidar creuse le gisement visible le plus proche, puis rentre décharger (même réserve sur la diagonale).
# 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. Grue
En une ligne : à côté d'une gare, elle déplace le conteneur du premier wagon chargé vers la première place libre de la cour.
# 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. Constructeur
En une ligne : il transforme les fantômes que vous avez planifiés sur la carte en structures réelles, en allant chercher le matériel.
# 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")
Autres hôtes
Les trains, les postes électriques, les portails et les vaisseaux exécutent aussi StarOS avec leurs propres modules (train, power_controller, gate, ship). Chaque hôte démarre avec un script documenté par défaut, et Reset to default le rétablit.
Référence complète
Le jeu génère la référence de l'API à partir du code qui exécute vos scripts. Consultez-la sur la page de chaque pièce de robot dans le jeu, sur la page de votre robot, ou demandez à votre agent d'appeler staros_reference. En cas de désaccord avec cette page, la référence a raison.