May-09-2022, 11:49 AM
(May-06-2022, 07:33 PM)menator01 Wrote: One more.
All right Menator01, I've got one for you. Since you seem to like a challenge I off you this one. It is the classic turtle race example that I have expanded to show a practical use for arrays. Can you get this one down below 25 lines?
#Turtle race - An example of using all of the topics #with an introduction to using lists from turtle import * from random import * turtlecnt = 10 #number of turtles in the race linetop = turtlecnt * 30 / 2 #location of top line linebottom = 0 - linetop - 30 #location of bottom line hideturtle() #setup the screen penup() speed("fastest") goto(-200,linetop) pendown() goto(-200,linebottom) penup() goto(200,linetop) pendown() goto(200,linebottom) racers = [] #a list to hold our turtles for i in range(0,turtlecnt): #for each position in the list newturtle = Turtle() #create the turtle racers.append(newturtle) #add it to the turtle list #a list of colors to randomly choose from colors = ["yellow", "gold", "orange", "red", "maroon", "violet", "pink", "magenta", "purple", "navy", "blue", "skyblue", "cyan", "turquoise", "lightgreen", "green", "darkgreen", "chocolate", "brown", "gray", "black"] #Setup the turtles for i in range(0,turtlecnt): #for each turtle in the list clrnum = randint(0,len(colors)-1) #choose a random color racers[i].color(colors[clrnum]) #set the turtle to the color colors.pop(clrnum) #remove the color from the list (avoid repeats) racers[i].shapesize(2) #increase the turtles size racers[i].penup() #no drawing during the race racers[i].goto(-200, (i * 30) - (turtlecnt * 30 / 2)) #goto the starting line racers[i].speed("fastest") #set the speed (same as 0) #repeat until on of the turtles reaches the finish line racing = True #the race is running i = 0 #start at the first turtle tracer(0) #do not automatically update window while racing: #while the race is running racerdist = randint(0,5) #choose a random distance to travel racers[i].forward(racerdist) #for the current turtle, move the random distance if racers[i].xcor() >= 200: #check if that move won the race racing = False #the race is over winpos = i #this turtle won i = i + 1 #setting up for the next turtle if i >= turtlecnt: #have we reached the end of the turtle list? i = 0 #yes? wrap to the beginning update() #manually update the window (needed when tracer is 0) penup() #relocate the default turtle goto(-200,racers[winpos].ycor()) #display the winner write("The winner is turtle " + str(winpos),font=("",25,""))