Python Forum

Full Version: Create a turtle drawing from .txt file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2 3
This is what I have to actually get it to print out from the .txt file

f = open("venv/tegne_eksempel_2.txt"
color = []
angle = []
forward = []
for line in f:
splitLine = line.split(",")
color.append(splitLine[0])
angle.append(int(splitLine[1]))
forward.append(int(splitLine[2]))
print(color)
print(angle)
print(forward)
You should only have to worry about 3 lines from the file. Color, x and y.

Let's say your file is:
black
100
0

This should result in
turtle.pencolor("black")
draw_to(x=100, y=0)

When you start your program you can assume you are at x=0, y=0. To stay with convention you should make x the horizontal axis and y the vertical axis. How do you draw a horizontal line that is 100 long? Do you know how to do that?

What if the file is:
red
0, 100

Do you know how to change the pen color to red? Do you know how to draw a vertical line that is 100 long?
Maybe an easier explanation: they want me to make a program that reads the file, then I need to put it in a for loop and use except for the colors.
I looked at your initial post and at your sample code and decided the file looks something like this:
red, 15, 200
blue, 150, 200
green, 300, 200
orange, 150, 200
black, 300, 200
red, 150, 200
blue, 300, 200
green, 150, 200
Each 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.
This is sort of an introduction to state machines. But, in general, these problems are easier if you break them down into their parts and work on each one at a time. The whole project might look big and complex, but each part is fairly small.

For this, I see the following parts:
1) read from a file.
2) keep track of state as you parse the file (are we rotating this line, or moving forward?)
3) error handling (but if the file you shared is the final one, there's no errors you need to catch).

Here's an example, where I skipped the file reading part (I just copy/pasted your input to make a list... processing a list vs a file will be identical either way).
>>> rules = '''black
... 15
... 200
... lightgray
... 150
... 200
... black
... 300
... 200
... lightgray
... 150
... 200
... black
... 300
... 200
... lightgray
... 150
... 200
... black
... 300
... 200
... lightgray
... 150
... 200'''.split()
>>> rules
['black', '15', '200', 'lightgray', '150', '200', 'black', '300', '200', 'lightgray', '150', '200', 'black', '300', '200', 'lightgray', '150', '200', 'black', '300', '200', 'lightgray', '150', '200']
>>> import turtle
>>> t = turtle.Turtle()
>>> rotating = True
>>> 
>>> # loop over each line in the file/rules
>>> for line in rules:
...   # is this line a number?  (we rotate/move if it is)
...   if line.isnumeric():
...     if rotating:
...       # this line is a number, and we need to rotate right now...
...       t.right(int(line))
...     else:
...       # this line is a number, and we need to move right now...
...       t.forward(int(line))
...     # whatever we just did, do the opposite next time through the loop
...     rotating = not rotating
...   else:
...     # this line is not a number, so it's a new color
...     t.pencolor(line)
...
(Jan-25-2021, 03:46 PM)Noob101 Wrote: [ -> ]I can get my program to read/print the file out as text
Will you please post your code so far? If you can read the information for the text file then you should be able to loop through it to instruct the turtle. Someone here can help if the know what you've done up until now.
After some help from classmates, I got it to work :) Ended up being quite similar'ish to what @nilamo wrote. Thanks for the help guys!
(Jan-26-2021, 06:49 PM)Noob101 Wrote: [ -> ]After some help from classmates, I got it to work :) Ended up being quite similar'ish to what @nilamo wrote. Thanks for the help guys!

Hi @Noob101. I have a problem quite similar similar to your's, and was wondering if you could share how you ended up solving it?
@spot do you still need help or did you figure it out?
(Jan-28-2021, 07:06 PM)Noob101 Wrote: [ -> ]@spot do you still need help or did you figure it out?

Similar problem here. Could you please share?
Pages: 1 2 3