A program in a game

info(), your own log, and the loop every game program is built from.

10.1CompetingRobot club14 min

Do this lesson in the simulator

You have written programs that drive a mat on their own. A game is the same Python with three differences: other robots are on the mat, the game tells you things while it runs, and nobody stops you at the end of a task.

What changes

  • The game talks to you through info(), a dictionary of whatever this game knows: the score, the clock, where the next thing is. Every game page lists what it puts in there.
  • print() goes to your own log, which you can read after the race. Nobody else sees it, so print as much as you like.
  • There is no task to pass. There is a result, and it is worked out from what your robot did.
  • The program keeps running until the game ends. Most game programs are one big loop.
# in a task, info() is empty: there is no game telling you anything
from bugbot import *
connect()

print("this is a task, not a game")

Run this in the simulator

The shape of a game program

Almost every one looks like this:

from bugbot import *
connect()

while True:
    # 1. look: sensors, and what the game says
    gap = distance()
    # 2. decide
    if gap < 20:
        # 3. move
        turn_right(40, angle=45)
    else:
        forward(60)
    # 4. let a moment pass, so the robot keeps hearing from you
    wait(0.1)

Look, decide, move, wait. You met it in Module 5 as the behaviour loop. A game is that loop with other robots in the way.

Try one

This is Sprint and Stop: drive up the mat and stop as close to the line as you can without crossing it. Press Race and watch your robot against the built-in bots.

from bugbot import *
connect()

# position() counts from where this robot started, and the game says where the line is
while True:
    gap = info()['finish_y'] - position()[1]
    if gap > 25:
        forward(90)
    elif gap > 4:
        forward(30)
    else:
        stop()
        break
    wait(0.1)

stop()
print("stopped", round(gap, 1), "cm short")

info()['finish_y'] is that game telling you where the line is. Change the two numbers and race again: the winner is the one who dares to creep from closest.

Task: stop on the line

Same idea, on your own: drive 55 cm up the mat and stop within 5 cm of that point, without crossing into the red strip five centimetres beyond it. Remember position() counts from where the robot started.

from bugbot import *
connect()

# position() counts from the start, so the line is 55 cm up from here
forward(70)
wait(1)
stop()
print("stopped at", position())

Challenges

  1. Print the gap every time round the loop, race, then read your log to see where the braking started.
  2. Make the light amber while creeping and green once stopped.
  3. What is the fastest first speed that still stops in time?