In: Computer Science
I need to write these three functions in Python using turtle module.
def line(t, coord1, coord2)
def poly(t, *coords)
def rectangle(t, coord, width, height, color)
Function 1: line
Code:-
import turtle
def line(t, coord1, coord2):
t.penup()
t.goto((coord1[0], coord1[1]))
t.pendown()
t.goto((coord2[0], coord2[1]))
line(turtle, [50, 100], [100, 50])
turtle.hideturtle()
turtle.exitonclick()
Screenshot:-
Output:-
Function 2: Polygon
Code:-
import turtle
def poly(t, *coords):
t.penup()
t.goto(coords[0])
t.pendown()
i = 0
while i < len(coords)-1:
t.goto(coords[i+1])
i += 1
t.goto(coords[0])
poly(turtle, [50, 100], [100, 50], [0, 50], [0, 200], [200, 100])
turtle.hideturtle()
turtle.exitonclick()
Screenshot:-
Output:-
Function 3: Rectangle
Code:-
import turtle
def rectangle(t, coord, width, height, color):
t.fillcolor(color)
t.pencolor(color)
t.begin_fill()
t.penup()
t.goto(coord)
t.pendown()
t.goto([coord[0]+width, coord[1]]) #Goes to the co ordinate width pixels to the right
t.goto([coord[0]+width, coord[1]+height]) #Goes to the point width pixels to the right and height pixels down
t.goto([coord[0], coord[1]+height]) #Goes to the point height pixels down
t.goto(coord)#Back to start
t.end_fill()
rectangle(turtle, [100, 50], 100, 50, "red")
turtle.hideturtle()
turtle.exitonclick()
Screenshot:-
Output:-
I hope this resolved your doubts. If you have further doubts do let me know.