Use Python turtle to make circles wtihout the circle function - python

I have this assignment for school:
Build a Snowman without turtle circle function
The snowman should be on a blue background, and should be drawn filled with white.
The outline of the snowman should be in black.
The snowman’s body should be made of 3 filled circles.
The outline of each circle should be 3 pixels wide.
The bottom circle should have a radius of 100 pixels.
The middle circle should have a radius of 70 pixels.
The top circle should have a radius of 40 pixels.
Each circle should be centered above the one below it (except the bottom circle, which can be located anywhere).
There should be no gap between the circles.
Give the snowman a mouth, eyes, and a nose (a hat is optional).
Make sure to include two stick-arms and at least two fingers on each hand.
So far I created this, but I can't seem to get the circles right before I move on.
Also, don't know how to color in circles or make dots for eyes. Help me please, first time coding.
import turtle # allows us to use turtle library
wn = turtle.Screen() # allows us to create a graphics window
wn.bgcolor("blue") # sets gtaphics windows background color to blue
import math # allows us to use math functions
quinn = turtle.Turtle() # sets up turtle quinn
quinn.setpos(0,0)
quinn.pensize(3)
quinn.up()
# drawing first circle middle
quinn.forward(70)
quinn.down()
quinn.left(90)
# calculation of cicumference of a circle
a = (math.pi*140.00/360)
#itineration for first circle
for i in range (1,361,1):
quinn.left(a)
quinn.forward (1)
# drawing second circle bottom
quinn.up()
quinn.home()
quinn.right(90)
quinn.forward(70)
quinn.left(90)
quinn.down()
b = (math.pi*200.00/360)
for i in range (1,361,1):
quinn.right(b)
quinn.forward(1)
# drawing third circle head top
quinn.up ()
quinn.goto(0,70)
quinn.right(90)
quinn.down()
c =(math.pi*80/360)
for i in range (1,361,1):
quinn.left(c)
quinn.forward(1)
wn.exitonclick()

The following is an example function to draw a circle filled in blue:
def draw_circle(radius):
turtle.up()
turtle.goto(0,radius) # go to (0, radius)
turtle.begin_fill() # start fill
turtle.down() # pen down
turtle.color('blue')
times_y_crossed = 0
x_sign = 1.0
while times_y_crossed <= 1:
turtle.forward(2*math.pi*radius/360.0) # move by 1/360
turtle.right(1.0)
x_sign_new = math.copysign(1, turtle.xcor())
if(x_sign_new != x_sign):
times_y_crossed += 1
x_sign = x_sign_new
turtle.up() # pen up
turtle.end_fill() # end fill.
return
Then you can modify the above function adding parameters for position (x,y) of the circle center:
def draw_circle(radius, x, y):
turtle.up()
turtle.goto(x,y+radius) # go to (x, y + radius)
turtle.begin_fill() # start fill
turtle.down() # pen down
turtle.color('blue')
times_y_crossed = 0
x_sign = 1.0
while times_y_crossed <= 1:
turtle.forward(2*math.pi*radius/360.0) # move by 1/360
turtle.right(1.0)
x_sign_new = math.copysign(1, turtle.xcor())
if(x_sign_new != x_sign):
times_y_crossed += 1
x_sign = x_sign_new
turtle.up() # pen up
turtle.end_fill() # end fill.
return
You can easily add dots as, for instance,:
turtle.goto(-20,10)
turtle.color('red')
turtle.dot(20)
turtle.goto(40,10)
turtle.dot(20)
Putting together:
import turtle
import math
def draw_circle(radius, x, y):
turtle.up()
turtle.goto(x,y+radius) # go to (0, radius)
turtle.begin_fill() # start fill
turtle.down() # pen down
turtle.color('blue')
times_y_crossed = 0
x_sign = 1.0
while times_y_crossed <= 1:
turtle.forward(2*math.pi*radius/360.0) # move by 1/360
turtle.right(1.0)
x_sign_new = math.copysign(1, turtle.xcor())
if(x_sign_new != x_sign):
times_y_crossed += 1
x_sign = x_sign_new
turtle.up() # pen up
turtle.end_fill() # end fill.
return
draw_circle(100, 10, 10)
turtle.goto(-20,10)
turtle.color('red')
turtle.dot(20)
turtle.goto(40,10)
turtle.dot(20)
turtle.pen(shown=False)
turtle.done()
You should attempt to do by yourself the remaining part of the assignment.. ;)

Sorry for not giving an explanation.
The first part is Ramanujan's aproximation of pi, but not a very good one because it only reaches an aproximation of pi after something like 300,000 iterations of the loop and it is only accurate to 5 decimal places. that would be this part:
r += (1 / k) * (-1)**i
pi = (4 * (1 - r))
Then I use the circumference of a circle:
t.forward(2*5*pi)
Finally I just make the turtle walk clock wise by 20.
import turtle
t = turtle.Turtle()
t.right(90)
t.penup()
t.goto(100, 0)
t.pendown()
i = 0
r = 0
k = 3
while i <= 360:
r += (1 / k) * (-1)**i
pi = (4 * (1 - r))
t.write(pi)
t.forward(2*5*pi)
t.right(20)
i += 1
k += 2
turtle.done()

From a mathematical standpoint, you can use functions sin and cos from the math to plot the circle.
Once the circle is plot, use the turtle.begin_fill() and turtle.end_fill() methods to fill in the circle (though I do agree that in programming, this method is more practical):
from turtle import Turtle
from math import sin, cos, radians
def draw_circle(radius, x, y, color="light blue", line_width=3):
c = Turtle(visible=False)
c.width(3)
c.penup()
c.goto(x + radius, y)
c.pendown()
c.color("black", color)
c.begin_fill()
# Circle drawing starts here
for i in range(1, 361):
c.goto(radius * cos(radians(i)) + x,
radius * sin(radians(i)) + y)
# Circle drawing ends here
c.end_fill()
draw_circle(100, 0, -100)
As pointed out in this answer, you can use the turtle.dot() method to draw a dot on the screen,
and the width of the pen will be the diameter of the dot.
There's another way to do that, but compared to the dot method, it is impractical.
I'll throw it out there anyway, just to show how there are many possibilities in workarounds:
from turtle import Turtle
def draw_circle(radius, x, y, color="light bue", line_width=3):
c = Turtle(visible=False)
c.penup()
c.goto(x, y)
c.pendown()
# Circle drawing starts here
c.width(radius * 2 + line_width)
c.forward(0)
c.color(color)
c.width(radius * 2 - line_width)
c.forward(0)
# Circle drawing ends here
draw_circle(100, 0, -100)
So a turtle.dot() is the equivalent of turtle.forward(0) (and turtle.backward(0), turtle.goto(turtle.pos()), turtle.setpos(turtle.pos()), etc., etc.).
Output:

Most solutions to "without turtle circle function" involve writing your own equivalent to turtle's circle function. But there are already two other ways you can draw outlined, filled circles with turtle.
One is you can use concentric dots:
turtle.color('black')
turtle.dot(200 + 3)
turtle.color('white')
turtle.dot(200 - 3)
Just remember that dot() takes a diameter whereas circle() takes a radius:
However, I prefer to use stamping to solve these sorts of problems:
''' Build a Snowman without turtle circle function '''
from turtle import Turtle, Screen
# The snowman’s body should be made of 3 filled circles.
# The bottom circle should have a radius of 100 pixels.
# The middle circle should have a radius of 70 pixels.
# The top circle should have a radius of 40 pixels.
RADII = (100, 70, 40)
STAMP_SIZE = 20
# The snowman should be on a blue background
screen = Screen()
screen.bgcolor('blue')
quinn = Turtle('circle')
quinn.setheading(90)
quinn.up()
# The outline of the snowman should be in black, and should be drawn filled with white.
quinn.color('black', 'white')
for not_first, radius in enumerate(RADII):
if not_first:
quinn.forward(radius)
# The outline of each circle should be 3 pixels wide.
quinn.shapesize((radius * 2) / STAMP_SIZE, outline=3)
quinn.stamp()
# Each circle should be centered above the one below it
# There should be no gap between the circles.
quinn.forward(radius)
# Give the snowman eyes
quinn.shapesize(15 / STAMP_SIZE)
quinn.color('black')
quinn.backward(3 * RADII[-1] / 4)
for x in (-RADII[-1] / 3, RADII[-1] / 3):
quinn.setx(x)
quinn.stamp()
# Give the snowman a mouth, and a nose (a hat is optional).
pass
# Make sure to include two stick-arms and at least two fingers on each hand.
pass
quinn.hideturtle()
screen.exitonclick()
The idea is you contort the turtle cursor itself to what you need, make a snapshot of it on the screen, and then contort it to the next thing you need to draw.

You can create a function that takes arguments fd, and left.
here is what I created.
from turtle import *
speed(100000)
for i in range(360):
fd(2)
left(1)
Here is the calculation: The iterations in range divided by the fd+left.
That is the approximation I have. SO you should be able to create a function like that.

You could try this, hope this helps!
def polygon(length, sides):
for i in range(sides):
turtle.forward(length)
turtle.left(360.0/sides)
polygon(1, 360)

Related

How to draw a circle using turtle in python?

I wanted ask how can I draw a circle using turtle module in python just using turtle.forward and turtle.left? I use the code below:
for i in range(30):
turtle.forward(i)
turtle.left(i)
turtle.done()
What I get is that the line does not stop once I get the full cirle. How can I code so that I have a circle of specific radius and that I have a full stop once the circle is drawn (without using turtle.circle).
I made this image as a reference,
Essentially you need to draw the inscribed polygon with n sides.
The initial left turn will be ϴ/2.
Then forward by a = 2rsin(ϴ/2).
Each forward is followed by a left turn of the full ϴ, except that after the last forward we want only a left turn of ϴ/2 so that the heading will be correctly updated to be tangential to the circle (or arc).
Something like this,
import turtle
import math
def circle2(radius,extent=360,steps=360):
if extent<360 and steps==360:
steps=extent
theta=extent/steps
step_size=2*radius*math.sin(math.radians(theta/2))
turtle.left(theta/2)
turtle.forward(step_size)
for i in range(1,steps):
turtle.left(theta)
turtle.forward(step_size)
turtle.left(theta/2)
turtle.hideturtle()
turtle.speed(0)
turtle.getscreen().tracer(False)
circle2(50)
circle2(100,180)
turtle.up()
turtle.home()
turtle.down()
circle2(130)
circle2(130,360,10)
turtle.update()
turtle.mainloop()
If you want to draw a circle the best thing to do is to simplyfy the problem, if we consider moving 1 space for each degree of the circle then we can simply write this as
def draw_circle1():
for _ in range(360):
turtle.forward(1)
turtle.left(1)
Now what do we know about this basic circle that we drew? well we know it took 360 steps and each step was 1. so the circle has a circumference of 360. we can use a bit of math to calculate the radius.
circumference = 2 * 3.14... * radius
360 = 2 * 3.14... * radius
360 / 2 / 3.14... = radius
radius = 57.29...
So now we can reverse this, if we want to specify a circle of a given radius, we can calculate what circumference that circle should have. divide that by the 360 degrees and we know what size step to take before each turn of 1 degree.
def draw_circle(radis):
circumfrence = 2 * math.pi * radis
step_size = circumfrence / 360
for _ in range(360):
turtle.forward(step_size)
turtle.left(1)
if we run this for 3 separate circles each increasing in size you see it gives us a consistent result
draw_circle(20)
draw_circle(40)
draw_circle(60)
turtle.hideturtle()
turtle.done()
So now we have a function which can accept a radius and draw a circle based on that radius
A spirograph code
from turtle import Turtle
import random
josh = Turtle()
josh.color('DarkRed')
def random_color()->tuple:
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
return (r,g,b)
josh.speed('fastest')
josh.pensize(2)
for i in range(72):
josh.circle(100)
josh.right(5)
colormode(255)
josh.pencolor(random_color())
screen = Screen()
screen.setup(800,800)
screen.exitonclick()
Example here,
import turtle
def circle(distance, sections):
angle = 360/sections
for i in range(1, sections+1):
turtle.forward(distance)
turtle.left(angle)
circle(20, 30)
turtle.done()
Create a SPIROGRAPH using turtle. Final output:
import random
import turtle
from turtle import Turtle, Screen
tim = Turtle()
tim.shape('arrow')
turtle.colormode(255)
def random_colour( ):
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
return (r, g, b)
tim.speed('fastest')
def draw_spirograph(size_of_gap):
for _ in range(int(360/size_of_gap)):
tim.color(random_colour())
tim.circle(100)
tim.setheading(tim.heading()+size_of_gap)
draw_spirograph(5)
screen = Screen()
screen.exitonclick()

Recursive rainbow-colored circles around each other

I'm trying to change the color and # of circles shown on the screen. So far, I've figured out how to make all of them different colors in a recursive pattern, but I need help finding out how to add more. Attached is what I have versus what I need to achieve.
my code
import turtle
import colorsys
def draw_circle(x,y,r,color):
turtle.seth(0)
turtle.up()
turtle.goto(x,y-r)
turtle.down()
turtle.fillcolor(color)
turtle.begin_fill()
turtle.circle(r)
turtle.end_fill()
def draw_recursive_circles(x,y,r,color,n):
if n == 0:
return
draw_circle(x,y,r,color)
colors = ['red','orange','yellow','green','blue','purple']
i = 0
for angle in range(30,360,60):
turtle.up()
turtle.goto(x,y)
turtle.seth(angle)
turtle.fd(r*2)
draw_recursive_circles(turtle.xcor(),turtle.ycor(),r/3,colors[i],n-1)
i += 1
turtle.tracer(0)
turtle.hideturtle()
turtle.speed(0)
draw_recursive_circles(0,0,100,'red',5)
turtle.update()
What I need to achieve
What I have so far
You import colorsys but never use it -- this is a clue that you're supposed to generate colors based on angles and not a fixed list of colors. The reason for the import is that turtle's RGB-based colors are the wrong model for our needs, so we want a more appropriate model, like HSV (where we only really care about H/hue), and have it convert those values to RGB.
The number of satellites is determined by your range call:
for angle in range(30,360,60):
Which for this drawing should be more like:
for angle in range(0, 360, 30):
As there are twelve satellites and 360 / 30 is 12. Finally, we need to do proper accounting such that whenever we change a position or heading, in order to do recursive drawing, we need to restore the original values on exit. Below is my simplified example solution to this problem:
from turtle import Screen, Turtle
from colorsys import hsv_to_rgb
def draw_circle(radius):
y = turtle.ycor() # save position & heading
heading = turtle.heading()
turtle.fillcolor(hsv_to_rgb(heading / 360, 1.0, 1.0))
turtle.sety(y - radius)
turtle.setheading(0)
turtle.begin_fill()
turtle.circle(radius)
turtle.end_fill()
turtle.sety(y) # restore position & heading
turtle.setheading(heading)
def draw_recursive_circles(radius, n):
if n == 0:
return
draw_circle(radius)
if n > 1:
heading = turtle.heading() # save heading
for angle in range(0, 360, 30):
turtle.setheading(angle)
turtle.forward(radius * 2)
draw_recursive_circles(radius / 5, n - 1)
turtle.backward(radius * 2)
turtle.setheading(heading) # restore heading
screen = Screen()
screen.tracer(False)
turtle = Turtle(visible=False)
turtle.penup()
draw_recursive_circles(150, 4)
screen.update()
screen.tracer(True)
screen.exitonclick()
I've intentionally kept the pen up to simplifiy my example so only filled portions of the circles are shown. Putting back the surrounding outlines I leave as an exercise for you.
The center circle is not the right color. Fixing this is a simple matter of setting the turtle's heading prior to the initial call to draw_recursive_circles()

How to return turtle to its origin in recursion function

I'm having trouble writing a recursive function that draws circles to a certain 'depth'.
For example, at depth one, the program should draw this: depth 1
At depth two the program should draw this: depth 2
At depth three the program should draw this:depth 3
And for reference, my program draws this:myTurtleDrawing
import turtle
# These are basic instructions that do not affect the drawing if changed, only the appearance of the entities within the window
turtle.mode('logo')
turtle.speed(1)
turtle.shape('classic')
turtle.title("Circle")
def recCircle(d, r):
if d == 0:
pass
if d == 1:
print("Drawing to the depth of: ", d)
turtle.down()
turtle.circle(r)
turtle.up()
else:
print("Drawing to the depth of: ", d)
turtle.circle(r)
turtle.seth(90)
turtle.down()
recCircle(d - 1, (r / 2)) # Draw the leftmost circle
turtle.seth(360)
turtle.up
turtle.seth(270)
turtle.forward(2 * r)
turtle.down()
recCircle(d - 1, - r / 2) # Draw the rightmost circle
turtle.up()
turtle.seth(360)
turtle.forward(2*r)
def main():
d = 3 #depth of recursion
r = 100 #radius of circle
recCircle(d, r)
turtle.done()
main()
I believe the problem lies around line 20
turtle.circle(r)
I can not figure out how to return the turtle to the same location and orientation.
turtle.home or turtle.goto as I'm trying not to use those
Specific issues with your code:
turtle.mode('logo')
I understand the desire to work with North == 0 but in the case of this design, it's not to your advantage and I'd stay with the default orientation. This won't work:
turtle.up
It needs to be turtle.up(). I don't see how you got your example output with this in the code as it should throw an error. This is OK:
turtle.seth(270)
as long as you're assuming a vertical orientation. But in general, if we want to draw at any angle, you can't use setheading() as it's as absolute as turtle.goto() or turtle.home(). But this, seems strange:
turtle.seth(360)
vs. simply turtle.setheading(0). A key concept when doing a drawing like this is to return the turtle to where it started, either implicitly in the drawing command, or explicitly by undoing anything you did to position the turtle. Below's my complete rework of your code:
from turtle import Screen, Turtle
def recCircle(depth, radius):
if depth == 0:
return
print("Drawing to the depth of: ", depth)
turtle.pendown()
turtle.circle(radius)
turtle.penup()
if depth > 1:
length = 11 * radius / 8 # no specific ratio provided, so eyeballed
turtle.left(45)
turtle.forward(length)
turtle.right(45)
recCircle(depth - 1, radius / 2) # Draw the leftmost circle
turtle.backward((2 * length ** 2) ** 0.5)
recCircle(depth - 1, radius / 2) # Draw the rightmost circle
turtle.right(45)
turtle.forward(length)
turtle.left(45)
screen = Screen()
screen.title("Circle")
turtle = Turtle('classic')
turtle.speed('fast')
depth = 3 # depth of recursion
radius = 100 # radius of circle
recCircle(depth, radius)
screen.exitonclick()

randomly positioned circle clicking game

So I'm still very new to python and trying to learn through making small projects.
The game I'm making is meant to test your mouse accuracy by creating a bunch of random circles which the player is meant to click in a given amount of time. At the end of the game, it should tell the player their score, and how many misclicks they had.
I've been using turtle to try and do this, but I'm stuck:
import turtle
import random
t = turtle.Pen()
win = turtle.Screen()
win.bgcolor("lightgreen")
win.title("clicky")
def mycircle(red, green, blue):
t.color(red, green, blue)
t.begin_fill()
x = random.randint(10,50)
t.circle(x)
t.end_fill()
t.up()
y = random.randint(0,360)
t.seth(y)
if t.xcor() < -300 or t.xcor() > 300:
t.goto(0, 0)
elif t.ycor() < -300 or t.ycor() > 300:
t.goto(0, 0)
z = random.randint(0,100)
t.forward(z)
t.down()
for i in range(0, 20):
a = random.randint(0,100)/100.0
b = random.randint(0,100)/100.0
c = random.randint(0,100)/100.0
mycircle(a, b, c)
The main issues I've been trying to figure out are:
How can I make the circles spawn further from each other? They overlap
quite often and I want that to be avoided.
How can I make the circles spawn instantly rather than having to be
drawn?
How can I make the circles spawn further from each other?
We can keep track of circles already created and make sure their centers are at least a diameter away from each other. Your current circle placement logic is too complicated along with being faulty. Let's try to simplify it and make sure circles are drawn completely within the window.
How can I make the circles spawn instantly rather than having to be
drawn?
We could stamp them rather than draw them. However, since you are drawing so few circles, we can make every circle a turtle. This makes determining if you clicked on a circle, and removing that circle, simpler. I've added code, for you to expand on, that removes any circle that you click on:
from turtle import Turtle, Screen
from random import random, randint
CURSOR_SIZE = 20
def my_circle(color):
radius = randint(10, 50)
circle = Turtle('circle', visible=False)
circle.shapesize(radius / CURSOR_SIZE)
circle.color(color)
circle.penup()
while True:
nx = randint(2 * radius - width // 2, width // 2 - radius * 2)
ny = randint(2 * radius - height // 2, height // 2 - radius * 2)
circle.goto(nx, ny)
for other_radius, other_circle in circles:
if circle.distance(other_circle) < 2 * max(radius, other_radius):
break # too close, try again
else: # no break
break
circle.showturtle()
circle.onclick(lambda x, y, t=circle: t.hideturtle()) # expand this into a complete function
return radius, circle
screen = Screen()
screen.bgcolor("lightgreen")
screen.title("clicky")
width, height = screen.window_width(), screen.window_height()
circles = []
for _ in range(0, 20):
rgb = (random(), random(), random())
circles.append(my_circle(rgb))
screen.mainloop()
One issue you need to work out is making sure your circle color isn't too similar to (or the same as) your background color, otherwise you'll be hunting an invisible circle. Also, we might be able to speed up the circle drawing process even more, if needed.

How to create a color wheel using turtle graphics?

I am trying to create somewhat of a color wheel using the turtle module in Python. Let's say I have a list of colors:
colors = ["#880000","#884400","#888800","#008800","#008888","#000088",
"#440088","#880088"]
I am aiming to go around a circle with a radius of 250px plotting in the colors:
def drawColors():
for color in colors:
turtle.color(dark)
for i in range(len(colors)):
turtle.begin_fill
turtle.circle(150)
turtle.end_fill()
turtle.done()
You can do it by dividing the circle up into multiple circular sectors (aka pie slices) and drawing each one in a different color. The tricky part doing it with turtle graphics is setting the initial position and heading (or direction) of the turtle to be at the start of the arc of each one. Also, unlike with the case with a full circle, you need to manually close the figure before filling it by drawing the final line segment from the end of the arc back to the center of the circle.
While this could be calculated mathematically, doing that is avoided in the following code by remembering, for all but the first sector, where the previous one left off and using that as the starting position and heading for the next. Fortunately for the initial one, these values are relatively simple to compute: the position is set to the (circle_center x value + radius, circle_center y value) with a due North heading of 90°.
import turtle
colors = ['#880000','#884400','#888800','#008800',
'#008888','#000088','#440088','#880088']
def draw_color_wheel(colors, radius, center=(0, 0)):
slice_angle = 360 / len(colors)
heading, position = 90, (center[0] + radius, center[1])
for color in colors:
turtle.color(color, color)
turtle.penup()
turtle.goto(position)
turtle.setheading(heading)
turtle.pendown()
turtle.begin_fill()
turtle.circle(radius, extent=slice_angle)
heading, position = turtle.heading(), turtle.position()
turtle.penup()
turtle.goto(center)
turtle.end_fill()
draw_color_wheel(colors, 150, center=(25, 50))
turtle.hideturtle()
print('done - press any key to exit')
turtle.onkeypress(exit)
turtle.listen()
turtle.done()
Result
Since this question has become active again, let's solve it using stamping rather than drawing:
from turtle import Turtle, Screen
colors = ['#880000', '#884400', '#888800', '#008800',
'#008888', '#000088', '#440088', '#880088']
def draw_color_wheel(colors, radius, center=(0, 0)):
slice_angle = 360 / len(colors)
yertle = Turtle(visible=False)
yertle.penup()
yertle.begin_poly()
yertle.sety(radius)
yertle.circle(-radius, extent=slice_angle)
yertle.home()
yertle.end_poly()
screen.register_shape('slice', yertle.get_poly())
yertle.shape('slice')
yertle.setposition(center)
for color in colors:
yertle.color(color)
yertle.stamp()
yertle.left(slice_angle)
screen = Screen()
draw_color_wheel(colors, 250, center=(25, 50))
screen.exitonclick()
OUTPUT
This approach takes slightly less code and produces noticeably faster output.

Categories