Timing the Race

Do this on pencilcode.net

fd 50
rt 90
fd 30             
await done defer()
b = new Date      
speed Infinity
tick 60, ->
  if touches blue         
    f = new Date          
    t = (f - b) / 1000    
    write "Finished in " +
      t + " seconds!"     
    tick null             
  if pressed "up" then fd 1
  if pressed "left" then lt 1

The idea of this program is to keep track of the time of the race so you can see how fast you go.

The program uses the Date object. You can say b = new Date to save the current time as b. Then if later (say, when you touch the blue line), you have a second time f = new Date, subtracting f - b will tell you the number of milliseconds between the two times.

The setup adds fd 30 to move the turtle forward 30 pixels so that it does not start on the blue line. Or else the race will end as soon as it starts.

await done defer() pauses the program until all the drawing of the track finished. (If instead we had done speed Infinity at the beginning of this program, this pause would not be needed.)

b = new Date creates a new Date object that is a snapshot of the current time at the beginning of the race. It saves this time as the variable b.

The finish line is touched when if touches blue runs the code under it.

f = new Date creates a new Date object that is a snapshot of the current time at the finish of the race. It saves it as the variable f.

t = (f - b) / 1000 takes the difference between the finish time f and the beginning time b in milliseconds, and divides by 1000 to get the time in seconds.

write shows the "Finished" message, and tick null turns off the tick timer.