Turtle Race

Back to index

Get this sample program up and running. Execute the script several times and observe the results. If things are working normally, the race results should be different on each execution of the script.
#!/usr/bin/python import turtle import random finish_line=turtle.Pen() finish_line.pencolor("white") finish_line.pensize=5 finish_line.penup() finish_line.setpos(360,-80) finish_line.pendown() finish_line.setpos(360,30) finish_line.ht() s=turtle.Pen() s.pencolor("yellow") t=turtle.Pen() t.pencolor("orange") p=turtle.Pen() p.pencolor("cyan") t.screen.bgcolor("black") herd = [s,t,p] stp = [-40,-20,0] ct = 0 max = -200 for e in herd: e.pensize=2 e.speed(1) e.shape("turtle") e.penup() e.setpos(-200,stp[ct]) e.seth(0) e.pendown() ct+=1 while max<360: for e in herd: e.fd(int(random.random()*5)) if e.xcor()>max: max=e.xcor() turtle.mainloop()
To generate random numbers two lines are required:
  1. import random
  2. e.fd(int(random.random()*5))
The random.random() command generates a random value between zero and one. Encapsulating it in int() turns it into an integer value, which is only interesting if the value is first multiplied by an integer.

It should be understood that int(random.random()*5) returns a value between zero and five. Change the five to alter the possible range of integer values which are generated.


ASSIGNMENT:

Add two more turtles to the race and have the winning turtle spin in place five times after it hits the finish line.