Skip to content

Instantly share code, notes, and snippets.

@horstjens
Created October 28, 2023 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save horstjens/01b045c8d9f0c623ab8ec07c899a970f to your computer and use it in GitHub Desktop.
Save horstjens/01b045c8d9f0c623ab8ec07c899a970f to your computer and use it in GitHub Desktop.
drunk turtle race
import turtle
import random
w,h = 1200,750
turtle.setup(w,h)
colors = ["blue","red","green","yellow"]
goals = []
stable = []
y = h//2
for i, c in enumerate(colors):
t = turtle.Turtle()
t.shape("turtle")
t.pencolor(c)
y-= h//(len(colors)+1)
goals.append((w/2,y)) # where the turtle should go
t.goto(-w//2,y)
t.clear()
stable.append(t)
winner = []
while len(winner) < len(colors):
for i, t in enumerate(stable):
# turn because drunk?
t.left(random.choice((-5,-4,-3,-2,-1,-1,0,0,0,0,0,0,0,0,1,1,2,3,4,5)))
# forward
roll = random.choice((0,1,2,3,4,5,6,7,8,9,10))
t.forward(roll)
# win?
if t.xcor() > w//2:
if t.pencolor() not in winner:
winner.append(t.pencolor())
# on way to target?
deviation = t.towards(goals[i])
# bounce on border ?
if (t.xcor() <= -w//2) or (t.ycor()<-h//2) or (t.ycor()>h//2):
t.setheading(0)
t.left(deviation)
t.forward(10) # extra boost to get away from border
# slowly correct wrong direction
relative_angle = t.heading() - deviation
if relative_angle != 0:
if relative_angle > 0:
t.left(1)
else:
t.left(-1)
text= "race is over"
for rank, color in enumerate(winner):
text+= f"\n{rank+1}.: {color}"
turtle.write(text, align="center", font=("Arial",55,"normal"))
turtle.exitonclick()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment