How to draw Circle using Turtle in Python 3 - python

This is the code that I have already, but it is saying I need to define 'polygon' which I know I need to, but not exactly sure how and different ways that I have been trying just keeps giving me errors.
import turtle
import math
apple=turtle.Turtle()
def draw_circle(t, r):
circumference = 2 * math.pi * r
n = 50
length = circumference / n
polygon(t, n, length)
draw_circle(apple, 15)
turtle.exitonclick()

use the circle method
import turtle
import math
apple=turtle.Turtle()
def draw_circle(t, r):
turtle.circle(r)
draw_circle(apple, 15)
turtle.exitonclick()

If you really need to define a polygon.
from turtle import *
import math
apple = Turtle()
def polygon(t, n, length):
for i in range(n):
left(360/n)
forward(length)
def draw_circle(t, r):
circumference = 2 * math.pi * r
n = 50
length = circumference / n
polygon(t, n, length)
exitonclick()
draw_circle(apple, 30)

here is a function for polygon:
def drawPolygon (ttl, x, y, num_side, radius):
sideLen = 2 * radius * math.sin (math.pi / num_side)
angle = 360 / num_side
ttl.penup()
ttl.goto (x, y)
ttl.pendown()
for iter in range (num_side):
ttl.forward (sideLen)
ttl.left (angle)
Here is how you use it:
def main():
# put label on top of page
turtle.title ('Figures')
# setup screen size
turtle.setup (800, 800, 0, 0)
# create a turtle object
ttl = turtle.Turtle()
# draw equilateral triangle
ttl.color ('blue')
drawPolygon (ttl, -200, 0, 3, 50)
# draw square
ttl.color ('red')
drawPolygon (ttl, -50, 0, 4, 50)
# draw pentagon
ttl.color ('forest green')
drawPolygon (ttl, 100, 0, 5, 50)
# draw octagon
ttl.color ('DarkOrchid4')
drawPolygon (ttl, 250, 0, 8, 50)
# persist drawing
turtle.done()
main()
Dont Forget to add import turtle, math

Related

How to create a tessellation with turtles in Python

I'm trying to create a rhombus tessellation pattern with the turtle graphics on python that looks like this image:
http://www.supercoloring.com/sites/default/files/styles/coloring_medium/public/cif/2015/01/tessellation-with-rhombus-coloring-pages.png
I thought about creating a hexagon pattern first and then dividing the hexagons into thirds. I'm not sure how I can create the hexagon pattern recursively. So far, I'm only alternating the angles of the turtles as I run the program and I don't have a definite strategy. Any advice on how to approach this?
So far, I created 3 hexagons in the center with 3 turtles and used for loops to draw the hexagons around the 3 hexagons. However, when I loop the program, the turtles trace back the same path as before and it takes a while for it to draw the others.
Here is my code so far:
import turtle
t = turtle.Turtle()
t1 = turtle.Turtle()
t2 = turtle.Turtle()
t1.left(120)
t2.left(240)
for i in (t, t1, t2):
i.speed(0)
def hex():
for b in (t, t1, t2):
for i in range(6):
b.forward(100)
b.right(60)
for i in range(3):
t.left(120)
hex()
def rep():
for i in range(3):
for a in (t, t1, t2):
a.forward(100)
a.right(60)
for i in range(6):
a.forward(100)
a.left(60)
rep()
def rep2():
for a in (t, t1, t2):
for i in range(3):
a.left(120)
a.forward(100)
a.right(60)
rep()
a.right(120)
a.forward(100)
a.right(60)
rep()
rep2()
There are many of drawing this. I would draw based the rhombus shape because it will allow you to fill them with different colors. To be able to fill each rhombus, it needs to be drawn individually. The figure contains three different rhombus shapes (they are the same rhombus in different orientation).
I will draw first row and second row. After that it is repetition of the first and second row. Here is code:
def draw_rhombus(x,y,degree,size,tilt,color):
turtle.up()
turtle.goto(x,y)
turtle.seth(tilt)
turtle.down()
turtle.pencolor('dark gray')
turtle.fillcolor(color)
turtle.begin_fill()
turtle.fd(size)
turtle.left(degree)
turtle.fd(size)
turtle.left(180-degree)
turtle.fd(size)
turtle.left(degree)
turtle.fd(size)
turtle.left(180-degree)
turtle.end_fill()
def draw_rhombus_1(x,y,size):
draw_rhombus(x,y,120,size,0,'red')
def draw_rhombus_2(x,y,size):
draw_rhombus(x,y,60,size,0,'green')
def draw_rhombus_3(x,y,size):
draw_rhombus(x,y,60,size,60,'blue')
def rt_row_1(startx,starty,size,n):
x = startx
y = starty
for i in range(n):
draw_rhombus_1(x,y,size)
x += size
draw_rhombus_3(x,y,size)
draw_rhombus_2(x,y,size)
x += 2*size
def rt_row_2(startx,starty,size,n):
x = startx
y = starty
for i in range(n):
draw_rhombus_2(x,y,size)
x += 2*size
draw_rhombus_1(x,y,size)
x += size
draw_rhombus_3(x,y,size)
size = 80
x = -400
y = -400
for i in range(800//int(round(size*math.sqrt(3)))):
rt_row_1(x,y,size,800//(size*3))
rt_row_2(x-size/2,y+size*math.sqrt(3)/2,size,800//(size*3))
y += size*math.sqrt(3)
First, let's simplify your three turtle, three function hexagonal tessellation to a single turtle, single recursive function solution:
from turtle import Screen, Turtle
OUTER_RADIUS = 100
INNER_RADIUS = 3**0.5 * OUTER_RADIUS / 2
SIDES = 6
EXTENT = 360 / SIDES
def tessellation(depth):
turtle.right(EXTENT/2)
for _ in range(SIDES):
turtle.circle(OUTER_RADIUS, EXTENT, 1)
if depth:
heading = turtle.heading()
turtle.right(90)
tessellation(depth - 1)
turtle.setheading(heading)
screen = Screen()
turtle = Turtle(visible=False)
screen.tracer(False) # because I have no patience
turtle.penup()
turtle.goto(-OUTER_RADIUS / 2, -INNER_RADIUS)
turtle.pendown()
tessellation(2)
screen.tracer(True)
screen.exitonclick()
(Increase the depth argument to fill the window.) The tessellation you really want is four (not thirds) of these patterns overlaid atop each other. Keeping our initial code the same:
screen = Screen()
turtle = Turtle(visible=False)
screen.tracer(False) # because I have no patience
turtle.penup()
turtle.color('blue')
turtle.goto(OUTER_RADIUS / 4, -1 * INNER_RADIUS / 2)
turtle.pendown()
turtle.setheading(0)
tessellation(2)
turtle.penup()
turtle.color('red')
turtle.goto(-OUTER_RADIUS / 2, -2 * INNER_RADIUS / 2)
turtle.pendown()
turtle.setheading(0)
tessellation(2)
turtle.penup()
turtle.color('yellow')
turtle.goto(OUTER_RADIUS / 4, -3 * INNER_RADIUS / 2)
turtle.pendown()
turtle.setheading(0)
tessellation(2)
turtle.penup()
turtle.color('green')
turtle.goto(-OUTER_RADIUS / 2, -4 * INNER_RADIUS / 2)
turtle.pendown()
turtle.setheading(0)
tessellation(2)
screen.tracer(True)
screen.exitonclick()

Section 4.3 Exercise #5 - "Think Python" by Allen Downey

Link to the Exercises can be accessed here - Case Study: Interface Design, Exercise Section 4.3
Quoting the question, it seems I have to implement an arc() function:
Make a more general version of circle called arc that takes an additional parameter angle, which determines what fraction of a circle to draw. angle is in units of degrees, so when angle=360, arc should draw a complete circle.
The code I've written so far:
import turtle
import math
bob = turtle.Turtle()
def polygon(t, n, length):
for i in range(n):
t.fd(length)
t.lt(360/n)
def circle(t, r):
circumference = 2 * math.pi * r
n = int(circumference/3) + 1
length = circumference/n
polygon(t, n, length)
def arc(t, r, angle):
arc_length = 2 * math.pi * r * (angle/360)
n = (arc_length/4) + 1
arc(bob, 1000, 45)
turtle.mainloop()
I'm intending to call the circle() function within arc() just as polygon() was called within circle(), but I'm confused on how I should do that. Apart from that, the arc() function does not draw anything, rather just shows me a stationary Turtle.
I believe that the Turtle object bob isn't receiving any of the movement instructions assigned within polygon(). Thus all that it's doing is displaying the Turtle object!
I could be wrong, and this where I need clarification. Should I call circle() within arc() as well as make the Turtle object move? Are there easier alternatives? Calling functions within a function is still confusing for me, so more resources to learn about them would be great as well!
import turtle
bob=turtle.Turtle()
import math
def arc(t,radius,angle):
circumference = 2.0*math.pi*radius
frac = angle/360.0
arclength = circumference*frac
n = 50 # pick a number
len = arclength/n;
turnang = angle/n
for i in range(n):
t.fd(len)
t.lt(turnang)
arc(bob, 130,360)
turtle.done()
I'm trying to ... call the circle() function
within arc() just as polygon() was called within circle()
You've got this backward. The problem states:
Make a more general version of circle called arc
Just as you could draw a circle with the more general function polygon(), you should be able to draw a circle with the more general function arc(). Here's a skeletal program for thinking about this:
from turtle import Screen, Turtle
from math import pi
def polygon(turtle, sides, length):
outside_angle = 360 / sides
for _ in range(sides):
turtle.forward(length)
turtle.left(outside_angle)
def circle_using_polygon(turtle, radius):
circumference = 2 * pi * radius
sides = min(60, int(circumference / 3))
length = circumference / sides
polygon(turtle, sides, length)
def arc(turtle, radius, angle):
# implement arc not by calling *circle() nor by
# calling polygon() but rather by borrowing code
# from both and adding one more step to reduce
# the number of sides based on the arc angle
def circle_using_arc(turtle, radius):
arc(turtle, radius, 360)
bob = Turtle(visible=False)
# Draw overlapping circles three different ways:
bob.color("green")
circle_using_polygon(bob, 100)
for color in ['cyan', 'magenta', 'yellow', 'black']:
bob.color(color)
arc(bob, 100, 90)
bob.color("blue")
circle_using_arc(bob, 100)
screen = Screen()
screen.mainloop()
import tkinter
import swampy
from swampy.TurtleWorld import *
def polygon(n, t, length, angle):
print(t)
k= angle/360
for i in range(0,int(n*k)):
fd(t, length)
p= 360
lt(t,p/n)
t.delay
world = TurtleWorld()
bob = Turtle()
#def circle(r):
#l1= 2*3.14*r
#l= l1/60
#polygon(30, bob, l)
polygon(60, bob, 10, 180)

Write a function called circle that takes a turtle, t, and radius, r, as param

import turtle
bob = turtle.Turtle()
def polygon(t,length,n):
for i in range(n):
t.fd(length)
t.lt(360/n)
print(t)
polygon(bob,30,15)
turtle.mainloop()
How can I make a circle by calling polygon function?
You already have written the correct code to produce a circle. In the view of turtle's own circle() method, a circle is just a polygon with 60 sides (fewer if the circle is small.) I.e. it's about perception and how many sides do you need before you can't tell the difference.
import turtle
def polygon(t, length, n):
for _ in range(n):
t.fd(length)
t.lt(360 / n)
bob = turtle.Turtle()
bob.penup()
bob.sety(-270)
bob.pendown()
polygon(bob, 30, 60)
turtle.mainloop()
Your problem now is to control the drawing of the polygon/circle to produce it with a specific radius. Your length parameter doesn't map to a radius as the circle is coming out way too large. Here length represents 1/60 (1/n) of the circumference and we know that:
circumference = 2 * math.pi * radius
We can calculate, in our circle(t, radius) function, what length needs to be given radius (i.e. circumference/n), and call polygon(t, length, n) with these parameters. Here's a visual comparison drawing a radius 100 circle with turtle's circle() method (red) and drawing it with the solution I just described (blue):
import turtle
bob=turtle.Turtle()
bob.color('green', 'cyan')
bob.begin_fill()
def polygon(t,length, n):
for i in range(n):
bob.forward(length)
bob.left(360/n)
import math
def circle(t, r):
circum= 2*math.pi*r
n= int(circum/10)+1
length= circum/n
polygon(t,length, n)
circle(bob, 100)
bob.end_fill()
turtle.done()

Having trouble with turtles

I am having an issue with turtles.
This is the code so far:
'''
Levi Davis
This program demonstrates my knowledge on turtles based on problem one in the
third set of homework questions
'''
import turtle
import math
def draw_arc(t, angle, num_segments, length):
'''
draws an arc with turtle 't' that has a number of segments equal to 'num_segments'
and a length equal to 'length' with a turn angle of 'angle' divided by 'num_segments'
'''
#this is my calculations on the actual turning of the turtle
turn_angle = angle // num_segments
init_turn = ((num_segments - 1) * turn_angle) // 2
#the initial turn of the turtle and the loop to make the arc
t.right(init_turn)
for count in range(num_segments):
t.forward(length/num_segments)
t.left(turn_angle)
#undoing the final turn and the initial turn
t.right(turn_angle + init_turn)
def draw_squiggle(t, angle, num_segments, length, num_squiggles):
'''
This function utilizes draw_arc() to create a squiggly line
'''
for x in range(num_squiggles):
draw_arc(t, angle, num_segments, length)
draw_arc(t, -(angle), num_segments, length)
def draw_petal(t, angle, num_segments, length):
'''
draws a filled in petal shape using 2 arcs and a 180 degree turn
'''
t.begin_fill()
draw_arc(t, angle, num_segments, length)
t.left(180)
draw_arc(t, angle, num_segments, length)
t.left(180)
t.end_fill()
def draw_leaf(t, angle, num_segments, length):
draw_petal(t, angle, num_segments, length)
t.fillcolor(t.pencolor())
draw_petal(t, angle, num_segments, (length / 2))
wn = turtle.Screen()
bob = turtle.Turtle()
bob.pencolor("tomato2")
bob.pensize(5)
bob.fillcolor("black")
#Because clare told me to I made her into a turtle
clare = turtle.Turtle()
clarepen = "green"
clarefill = "purple"
clare.pencolor(clarepen)
clare.pensize(3)
clare.fillcolor(clarefill)
#testing of functions
#draw_arc(bob, 100, 10, 10)
#draw_arc(bob, -100, 10, 10)
#draw_squiggle(bob, -100, 10, 10, 2)
#draw_petal(clare, 100, 10, 40)
#draw_leaf(clare, 100, 10, 40)
#that one shape that is kind of trippy to look at... I think?...
size = 80
def draw_weird_shape(t1, t2):
startx = -size / 2
starty = -size / 2 * math.tan(math.radians(144 /2))
t1.up()
t1.goto(startx, starty)
t1.down()
t2.up()
t2.goto(startx, starty)
t2.down()
t1_fill = "purple"
t1_pen = "green"
for count in range(10):
t1.forward(size/2)
t1.right(90)
draw_squiggle(t1, 50, 10, 20, 2)
draw_leaf(t1, 50, 10, 50)
t1.pencolor(t1_pen)
t1.fillcolor(t1_fill)
t1.right(180)
draw_squiggle(t1, 50, 10, 20, 2)
t1.right(90)
t1.forward(size/2)
t1.left(36)
t2.up()
t2.forward(size)
t2.left(18)
t2.right(90)
t2.down()
draw_petal(t2, 50, 5, 25)
t2.up()
t2.left(108)
draw_weird_shape(clare, bob)
'''
clare.forward(20)
clare.left(18)
clare.right(90)
clare.forward(20)
clare.left(180)
clare.forward(20)
clare.right(90)
clare.forward(20)
'''
wn.exitonclick()
The problem appears to be around line 100.
When the squiggle starts to go back it does not go back in the 180 degree turn like it should.
When the squiggle starts to go back it does not go back in the 180
degree turn like it should.
Your problem is this code:
#this is my calculations on the actual turning of the turtle
turn_angle = angle // num_segments
init_turn = ((num_segments - 1) * turn_angle) // 2
By using integer division, //, you introduce just enough error that the arc code underlying the squiggle doesn't retrace the same path. Instead use floating point division, /, to keep it slightly more accurate:
# this is my calculations on the actual turning of the turtle
turn_angle = angle / num_segments
init_turn = ((num_segments - 1) * turn_angle) / 2

Spirograph Turtle Python

How can I play with a turtle and how can I use a turtle?
I have trouble getting the thing to work as in the picture shown below (ignore the colors).
from turtle import *
from math import *
def formulaX(R, r, p, t):
x = (R-r)*cos(t) - (r + p)*cos((R-r)/r*t)
def formulaY(R, r, p, t):
y = (R-r)*sin(t) - (r + p)*sin((R-r)/r*t)
def t_iterating(R, r, p):
t = 2*pi
up()
goto(formulaX, formulaY)
down()
while (True):
t = t + 0.01
formulaX(R, r, p, t)
formulaY(R, r, p, t)
def main():
R = int(input("The radius of the fixed circle: "))
r = int(input("The radius of the moving circle: "))
p = int(input("The offset of the pen point, between <10 - 100>: "))
if p < 10 or p > 100:
input("Incorrect value for p!")
t_iterating(R, r, p)
input("Hit enter to close...")
main()'
I am trying to make that kind of shape. Here is the coding I have done so far.
Try changing your t_iterating function to this:
def t_iterating(R, r, p):
t = 2*pi # It seems odd to me to start from 2*pi rather than 0.
down()
while t < 20*pi: # This loops while t goes from 2*pi to 20*pi.
t = t+0.01
goto(formulaX(R, r, p, t), formulaY(R, r, p, t))
up()
No! You're missing the point of the turtle! You should try to do it all with relative movements of the turtle. Think about how you would draw the shape if you were the turtle, crawling on a large floor, dragging a paintbrush from your butt.
At each small fragment of time, the turtle will perform one small iteration of a differential equation which governs the whole behavior. It is not generally wise to precompute the x y coordinates and use the turtle's GOTO function.
The turtle itself should have only relative knowledge of its surroundings. It has a direction, and a position. And these two pieces of state are modified by turning and moving.
So, think about how you would draw the spiral. Particularly, think about drawing the very first circle. As the circle appears to close, something interesting happens: it misses. It misses by a tiny little amount, which turns out to be a fraction of a circle. It is this missing curvature that closes the large pattern of circles in a circle, as they add up to one complete turn.
When the whole figure is drawn, the turtle is back to its original position and orientation.
This is my code. The color may not be exact, but here it is:
from turtle import *
from random import randint
speed(10000)
for i in range(20):
col = randint(1, 5)
if col == 1:
pencolor("orange")
elif col == 2:
pencolor("blue")
elif col == 3:
pencolor("green")
elif col == 4:
pencolor("purple")
elif col == 5:
pencolor("dark blue")
circle(50)
left(20)
This is the output:
My code is here and the function was built for automatically choosing the random colour.
from turtle import Turtle, Screen
import random
timmy = Turtle()
screen = Screen()
screen.colormode(255)
timmy.shape("turtle")
timmy.speed("fastest")
angle = [0, 90, 180, 270]
def random_color():
red = random.randint(0, 255)
green = random.randint(0, 255)
blue = random.randint(0, 255)
colour = (red, green, blue)
return colour
def draw_circles(num_of_gap):
for _ in range(int(360 / num_of_gap)):
timmy.color(random_color())
timmy.circle(100)
timmy.right(num_of_gap)
draw_circles(20)
screen.exitonclick()
Spirograph using Python Turtle with random colours
Code:
import random
from turtle import Turtle, Screen
tim = Turtle()
tim.shape("classic")
def turtle_color():
R = random.random()
G = random.random()
B = random.random()
return tim.pencolor(R, G, B)
tim.speed("fastest")
for _ in range(72):
turtle_color()
tim.circle(100)
tim.left(5)
screen = Screen()
screen.exitonclick()
Output:
You basically get the turtle to loop through the 360 degrees and you can choose two pen colours.
from turtle import Turtle, Screen
tim = Turtle()
tim.shape("turtle")
tim.color("green")
### total degrees in circle = 360
### turn left must be a divisor of 360 (1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 18, 20, 24, 30, 36, 40, 45, 60, 72, 90) NOTE: some divisors do not work as well
degrees = 360
turn_left = 12
total_circles = int(degrees / turn_left)
tim.pensize(3)
tim.speed(0)
def circle_colour1():
### choose your colour here:
tim.pencolor("pink")
tim.circle(-100)
tim.left(turn_left)
def circle_colour2():
### choose your colour here:
tim.pencolor("grey")
tim.circle(-100)
tim.left(turn_left)
for _ in range(0, int(total_circles / 2)):
circle_colour1()
circle_colour2()
screen = Screen()
screen.exitonclick()
Real basic (360°/10) is:
from turtle import Turtle as d
draw = d()
draw.speed(0)
draw.pensize(3)
for _ in range(0, 36):
draw.circle(-100)
draw.left(10)

Categories

Resources