Tutorial 1: a rover that avoids walls
Goal: your starter robot wanders the field without bumping into walls.
What you need
- A new account. You already have a Mk1 robot with a
lidarand one charged battery cell. - Your spacecraft within 12 cells of the robot, or the save is refused.
Steps
- Open Robots and click your robot. Read its position, parts and last outcome.
- Replace the text in the script editor with this (the demo rover's script):
DIRECTIONS = ["north", "east", "south", "west"]
OPPOSITE = {"north": "south", "south": "north", "east": "west", "west": "east"}
YIELD_DISTANCE = 2
TURN_ODDS = 7
def absolute(value):
if value < 0:
return -value
return value
def next_random(seed):
return (seed * 1103515245 + 12345) % 2147483648
def free(direction):
probe = lidar.probe(direction)
return probe["kind"] == "clear" or probe["distance"] > 1
def other_robot_near():
for cell in lidar.scan():
if cell["robot"] != None and max(absolute(cell["dx"]), absolute(cell["dy"])) <= YIELD_DISTANCE:
return cell["robot"]
return None
def tick():
seed = memory.get("seed", 17)
heading = memory.get("heading", robot.facing)
# Yield rule: the robot whose name sorts later waits.
other = other_robot_near()
if other != None and robot.name > other:
robot.log("yielding to " + other)
return
seed = next_random(seed)
options = [d for d in DIRECTIONS if d != OPPOSITE[heading] and free(d)]
if free(heading) and seed % TURN_ODDS != 0:
choice = heading
elif len(options) > 0:
choice = options[(seed // 8) % len(options)]
elif free(OPPOSITE[heading]):
choice = OPPOSITE[heading]
else:
memory.set("seed", seed)
return
memory.set("seed", seed)
memory.set("heading", choice)
robot.move(choice)
- Press Save. A script that does not compile comes back with a line and column, and nothing is stored.
- Wait for the next turn.
With an agent instead of clicks:
robot_listrobot_script_validatewithrobotandsourcerobot_script_putwithrobotandsource; check thatsavedis trueturn_wait, thenrobot_eventswithrobot
How it works
lidar.probe(direction) returns the first obstacle within 5 cells: distance and kind. The direction is free if there is nothing, or the obstacle is more than one cell away. memory keeps the heading and a seed between turns, since globals do not survive. One call in seven, roughly, it turns for no reason. So do some people.
What you should see
The robot moves one cell a turn on the Map. A refused move shows as blocked_terrain or blocked_robot. The built-in solar skin and the cell pay the walking.
Three common mistakes
- Expecting an instant effect. A saved script first runs on the next turn.
- Calling a part you do not carry.
drill.dig()on this robot is a compile error. - Letting it wander out of range. This script has no leash. Beyond 12 cells you cannot save or attach until you fly closer with the spacecraft. The original starter script stays within 5 cells of where it began.