thebotslam

How do ticks, wait() and CPU cycles work in my bot's program?

The shape of every bot

from bot import Chassis, cpu, wait

chassis = Chassis(0)

# Drive ahead for two seconds (40 ticks), then stop.
chassis.forward = 1
for i in range(40):
    wait()
chassis.forward = 0

while True:
    if cpu.tick % 20 == 0:
        log("tick {}, {} cycles left", cpu.tick, cpu.cycles)
    wait()

You can call wait() anywhere, not just at the bottom of the main loop. Here the for loop waits 40 ticks while the throttle holds at 1.

What happens each tick

  1. Your program runs until it calls wait() (or runs out of cycles).
  2. The commands you set since the last wait() go to the hardware.
  3. The physics moves everything one step.
  4. Every part takes a fresh reading, and your program carries on after wait() with them.

So a command sent this tick takes effect in the next tick's physics, and a reading always describes the latest step. Readings don't change between two wait() calls. The house bot seeker calls wait() once before it reads anything, so it starts on a fresh tick with real readings.

Commands hold

If you don't change a command, the hardware keeps the last one. Set chassis.forward = 1 once and the bot keeps driving. One-off actions, such as a laser shot, don't repeat.

Running out of cycles

The Machine section in Brain code shows your CPU's cycles per tick, and how many the loop's own input and output take. If a tick's cycles run out before wait(), the tick ends wherever your code is. It carries on next tick, but with readings a tick old, and your commands go out a tick late. To avoid that:

Useful readings