How can i draw polygon by getting data from .dat file?

Viewed 53

I have a .dat file and it contains few polygons made of 2D points. And I tried to draw them with turtle library. I draw one of them Polygons as manual in sample code, but I was not able to use data and create polygon which is in a file and use turtle.

polygon = open("POLYGONS.dat", "r")
### print(polygon.read())

import turtle
### POLYGON ((111.3671875 4.130859375,114.2578125 4.130859375,114.2578125 18.447265625,111.3671875 18.447265625,111.3671875 4.130859375))
t = turtle.Turtle()
   for i in range(20):
   t.goto(111.3671875, 4.130859375)
   t.goto(114.2578125, 4.130859375)
   t.goto(114.2578125, 18.447265625)
   t.goto(111.3671875, 18.447265625)
   t.goto(111.3671875, 4.130859375)

also i wrote "for i in range(20)" for more time to observation, because after i run turtle it disappears immediatly.

1 Answers

Assuming POLYGONS.dat looks like:

111.3671875 4.130859375
114.2578125 4.130859375
114.2578125 18.447265625
111.3671875 18.447265625
111.3671875 4.130859375

Then we can use this data to drive turtle's movements:

import turtle

turtle.penup()  # only up for first position

with open("POLYGONS.dat") as data:
    for line in data:
        position = map(float, line.split(maxsplit=2))
        turtle.goto(position)
        turtle.pendown()  # down after the first position

turtle.done()
Related