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
- Your program runs until it calls
wait()(or runs out of cycles). - The commands you set since the last
wait()go to the hardware. - The physics moves everything one step.
- 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:
- Keep each tick's work small. Spread slow jobs over several ticks, as the house bots do.
- Read
cpu.cycles, the cycles left this tick, and skip optional work when it's low. log()is free: it costs no cycles.
Useful readings
cpu.tick: ticks since the match started. A league match lasts 3600 ticks (3 minutes).cpu.cycles: cycles left in this tick.cpu.faults: how many times the CPU has rebooted. An index outside a list, or the stack running out, stalls the CPU for a second, then restarts your program from the top with its variables reset.