Reputation: 1
I need help to simplify/shorten code for turtle using functions/loops.
I'm writing a program for a character using Python turtle. I've managed to draw the character properly, but I can't find ways to make the code shorter/efficient as it looks too long. I really need help with this as I'm a newbie:
import turtle
win = turtle.Screen()
ninja = turtle.Turtle()
ninja.pensize(10)
ninja.forward(85)
ninja.penup()
ninja.goto(36,0)
ninja.pendown()
ninja.right(135)
ninja.forward(40)
ninja.left(135)
ninja.forward(67)
ninja.penup()
ninja.goto(58,-12)
ninja.pendown()
ninja.right(38)
ninja.forward(34)
ninja.penup()
ninja.goto(44,-32)
ninja.pendown()
ninja.right(52)
ninja.forward(38)
ninja.penup()
ninja.goto(5,-48)
ninja.pendown()
ninja.left(90)
ninja.forward(75)
ninja.penup()
ninja.goto(-4,-70)
ninja.pendown()
ninja.forward(92)
win.mainloop()
Upvotes: 0
Views: 238
Reputation: 41872
I reviewed your code and came up with my own improvement logic: first, write it so the pen is never lifted off the paper; second, make it shorter if possible. The following is about four turtle commands shorter, never lifts the pen and produces nearly identical output:
from turtle import Screen, Turtle
turtle = Turtle()
turtle.pensize(9)
turtle.forward(85)
turtle.backward(49)
turtle.left(45)
turtle.backward(40)
turtle.right(45)
turtle.forward(70)
turtle.right(38)
turtle.forward(7)
turtle.backward(33)
turtle.forward(24)
turtle.left(39)
turtle.backward(32)
turtle.right(90)
turtle.forward(43)
turtle.left(90)
turtle.forward(44)
turtle.backward(93)
turtle.forward(49)
turtle.left(90)
turtle.forward(23)
turtle.right(90)
turtle.forward(36)
turtle.backward(78)
turtle.hideturtle()
Screen().mainloop()
For the final stroke, not lifting the pen cost me an extra turtle command, so it is possible to make this code slightly shorter. However, having designed a non-lifting solution, we can monitor where the pen stops and turn this into simply connecting the dots:
from turtle import Screen, Turtle
points = [ \
(85, 0), (36, 0), (8, -28), (78, -28), (83, -33), \
(57, -12), (76, -27), (44, -28), (45, -71), (89, -70), \
(-4, -71), (45, -71), (44, -48), (80, -47), (2, -48), \
]
turtle = Turtle()
turtle.pensize(9)
for point in points:
turtle.goto(point)
turtle.hideturtle()
Screen().mainloop()
Upvotes: 2