Jan-25-2021, 07:18 PM
(This post was last modified: Jan-25-2021, 07:18 PM by deanhystad.)
I looked at your initial post and at your sample code and decided the file looks something like this:
I wrote the simples program to draw the image. It draws a four pointed star.
Sorry about the cartesian/polar misdirection. That was heading off in a completely wrong direction.
red, 15, 200 blue, 150, 200 green, 300, 200 orange, 150, 200 black, 300, 200 red, 150, 200 blue, 300, 200 green, 150, 200Each line in the file resulting in a turtle drawing a line. I changed some of the colors so it was easier for me to tell which line in the file matches which line in the drawing.
I wrote the simples program to draw the image. It draws a four pointed star.
import turtle t = turtle.Turtle() with open('test.txt') as file: for line in file: color, angle, x = line.split(',') t.pencolor(color.strip()) t.right(int(angle)) t.forward(int(x))What I think you are asking for is some way to make this program a bit more robust. My program crashes if there are less that three values in a line.
Error:Traceback (most recent call last):
File "...", line 7, in <module>
color, angle, x = line.split(',')
ValueError: not enough values to unpack (expected 3, got 2)
It also crashes if the angle or distance are not integers.Error:Traceback (most recent call last):
File "...", line 10, in <module>
t.forward(int(x))
ValueError: invalid literal for int() with base 10: ' 200.1\n'
And it crashes if the file contains a color name that isn't known to Turtle.Error:Traceback (most recent call last):
File "...", line 8, in <module>
t.pencolor(color.strip())
File "C:\Program Files\Python38\lib\turtle.py", line 2252, in pencolor
color = self._colorstr(args)
File "C:\Program Files\Python38\lib\turtle.py", line 2696, in _colorstr
return self.screen._colorstr(args)
File "C:\Program Files\Python38\lib\turtle.py", line 1158, in _colorstr
raise TurtleGraphicsError("bad color string: %s" % str(color))
turtle.TurtleGraphicsError: bad color string: hubbabubble
I am beginning to understand that your job is to handle these errors and maybe do something a little more graceful. You could attack that problem by verifying the strings before using them as colors or numbers, or you could us try/except to catch the errors when they occur.Sorry about the cartesian/polar misdirection. That was heading off in a completely wrong direction.