I want to draw a flower with turtle. Although I am facing problem in centering the flower (0,0) should be flower's center or where turtle initially is spawned. How can I center it?
import turtle
import math
turtle.speed(-1)
def Flower():
global radius, num_of
for i in range(num_of):
turtle.setheading(i * 360/num_of)
turtle.circle(radius*3.5/num_of,180)
radius = 50
num_of = 10
Flower()
I tried setting turtle to where it starts drawing but number of sides ruin it.
Since the turtle draws from a edge, we need to move the turtle to compensate for the radius of the entire image. To simplify this move, we align the starting point of the image with one (X) axis. We also switch from absolute coordinates (setheading()) to relative coordinates (right()) so our initial rotational offset doesn't get lost or need to be added to every position:
import turtle
import math
radius = 50
num_of = 13
def flower():
outer_radius = radius * 3.5 / math.pi
turtle.penup()
turtle.setx(-outer_radius) # assumes heading of 0
turtle.pendown()
turtle.right(180 / num_of)
for _ in range(num_of):
turtle.right(180 - 360 / num_of)
turtle.circle(radius * 3.5 / num_of, 180)
turtle.speed('fastest')
turtle.dot() # mark turtle starting location
flower()
turtle.hideturtle()
turtle.done()
To get the radius of the flower, we add up the diameters of all the petals and use the standard circumference to radius formula. There are probably simplifications, math-wise and code-wise, we could make.
Related
I am making a tic tac toe game and when the user presses 'o' a circle is printed but the circle is always on the left of the turtle. i would like the turtle to be in the center of a box and draw the circle around itself.
You have to move turtle on your own - using left,right,forward, penup, pendowm.
Example
import turtle
radius = 100
# move
turtle.penup()
turtle.right(90)
turtle.forward(radius)
turtle.left(90)
turtle.pendown()
# circle
turtle.circle(radius)
# move back
turtle.penup()
turtle.right(-90)
turtle.forward(radius)
turtle.left(-90)
turtle.pendown()
Result:
There are a couple of ways to draw a circle centered around a Python turtle without moving the turtle. The first is the dot() method. It takes a diameter, rather than a radius, and optionally allows you to specify the color at the same time:
import turtle
RADIUS = 100
turtle.dot(RADIUS * 2)
turtle.dot(RADIUS * 1.6, turtle.bgcolor()) # "unfill" the circle
turtle.done()
Another way to do it is via stamping, that is, make the turtle cursor itself a circle, size it, and then call stamp():
import turtle
RADIUS = 100
CURSOR_RADIUS = 10
turtle.hideturtle()
turtle.shape('circle')
turtle.fillcolor(turtle.bgcolor())
turtle.shapesize(RADIUS / CURSOR_RADIUS, outline=RADIUS/5)
turtle.stamp()
turtle.done()
Both of the above have the side effect of overwritting anything that the circle surrounds, which doesn't seem like a problem for tic-tac-toe. To avoid this, you can, of course, temporarily shift the turtle's position, as #furas suggests:
import turtle
RADIUS = 100
turtle.width(RADIUS/5)
turtle.penup()
turtle.sety(turtle.ycor() - RADIUS)
turtle.pendown()
turtle.circle(RADIUS)
turtle.penup()
turtle.sety(turtle.ycor() + RADIUS)
turtle.pendown()
turtle.done()
My task is to write a function, drawCircle(radius,fillColor), that asks a user for the specific radius of the circle and which color they'd like the circle to be filled.
I have the circle-drawing down, but I'm struggling with getting the circle to fill with the user-defined color. Any help would be greatly appreciated.
import turtle
def drawCircle(radius, fillColor):
x=360/300 #This gives the angle
r=radius#This is the radius of the circle.
c=fillColor
c=str("")
z=1 #Placeholder for the while loop.
win=turtle.Screen()
tom=turtle.Turtle()
fillColor=tom.color()
tom.begin_fill()
while (z<=300):
tom.forward(r)
tom.right(x)
tom.forward(r)
z=z+1
win.exitonclick()
tom.end_fill()
This is my function call: drawCircle(1,"red")
There are several problems with your code:
You call win.exitonclick before tom.end_fill, so programm exits before filling (as it happens on end_fill)
You do "fillColor=tom.color()" with gets you current color. Instead use "tom.fillcolor(fillColor)"
Unnecessary copying of variables radius->r and fillColor->c
This is python. Use for whenever possible. Instead of counting using z use:
for _ in range(300):
My final code:
import turtle
def drawCircle(radius, fillColor):
x = 360/300 # This gives the angle
win = turtle.Screen()
tom = turtle.Turtle()
tom.fillcolor(fillColor)
tom.begin_fill()
for _ in range(300):
tom.forward(radius)
tom.right(x)
tom.forward(radius)
tom.end_fill()
win.exitonclick()
drawCircle(1, "red")
I have the circle-drawing down
Before addressing your fill issue, I'd argue that your premise isn't true, you don't have circle-drawing down. As #Mysak0CZ shows, your circle of radius 1 is huge -- 1 what? You're drawing a circle but have no real control over its size.
As a professional turtle wrangler, I'd go about the problem as follows. Not only your angle needs to be divided by the number of segments you plan to draw, but you need to compute a circumference based on the requested radius and chop that up as well. I do so below and include a call to turtle's own .circle() method to show that we're in the right ballpark. And I fix your minor fill issue:
import math
from turtle import Turtle, Screen # force object-oriented turtles
SEGMENTS = 60 # how many lines make up the circle
def drawCircle(radius, fillColor):
distance = math.pi * radius * 2 / SEGMENTS # circumference / SEGMENTS
angle = 360 / SEGMENTS
turtle.fillcolor(fillColor)
turtle.begin_fill()
for _ in range(SEGMENTS):
turtle.forward(distance)
turtle.left(angle) # left for .circle() compatibility
turtle.end_fill()
screen = Screen()
turtle = Turtle()
drawCircle(100, 'red')
turtle.circle(100) # for comparison
screen.exitonclick()
Here is my code for a pink circle if you are going through the same Python learning resource. I think the original code was missing an argument.
import turtle
def drawPolygon(t, sideLength, numSides):
t.goto(0, 0)
turnAngle = 360 / numSides
for i in range(numSides):
t.forward(sideLength)
t.right(turnAngle)
def drawCircle(anyTurtle, radius):
circumference = 2 * 3.1415 * radius
sideLength = circumference / 360
drawPolygon(anyTurtle, sideLength, 360)
def drawFilledCircle(anyTurtle, radius, color):
anyTurtle.fillcolor(color)
anyTurtle.begin_fill()
drawCircle(anyTurtle, radius)
anyTurtle.end_fill()
anyTurtle.hideturtle()
wn = turtle.Screen()
wheel = turtle.Turtle()
drawFilledCircle(wheel, 80, "pink")
wn.exitonclick()
I'm being really bugged by a task:
User inputs radius r and then turtle draws the circle then proceeds to draw another circle with the same center but 10 px smaller until the radius is 0
First let us approximate a circle as a regular polygon with 36 sides/segments.
To draw this shape given a radius r we need to know;
The length of each segment
The angle to turn between each segment
To calculate the length, we first need the circumference, which is 2πr (we will approximate pi as 3.1415), giving us
circumference = 2 * 3.1415 * radius
Next we divide this by the number of segments we are approximating, giving
circumference = 2 * 3.1415 * radius
seg_lenght = circumferece/36
Now we need the angle difference between the segments, or the external angle. This is simply 360/n for a regular n-gon(polygon with n sides), so we do 360/36 = 10
We can now define a function to generate the segment length and draw the circle:
def circle_around_point(radius):
circumference = 2 * 3.1415 * radius
seg_length = circumference/36
penup()
fd(radius) #Move from the centre to the circumference
right(90) #Face ready to start drawing the circle
pendown()
for i in range(36): #Draw each segment
fd(seg_length)
right(10)
penup()
right(90) #Face towards the centre of the circle
fd(radius) #Go back to the centre of the circle
right(180) #Restore original rotation
pendown()
Now for the concentric circles:
def concentric_circles(radius):
while radius > 0:
circle_around_point(radius)
radius -= 10
It's not clear why #IbraheemRodrigues felt the need to recode turtle's circle() function based on your problem description, but we can simplify his solution by not reinventing the wheel:
def circle_around_point(turtle, radius):
is_down = turtle.isdown()
if is_down:
turtle.penup()
turtle.forward(radius) # move from the center to the circumference
turtle.left(90) # face ready to start drawing the circle
turtle.pendown()
turtle.circle(radius)
turtle.penup()
turtle.right(90) # face awary from the center of the circle
turtle.backward(radius) # go back to the center of the circle
if is_down:
turtle.pendown() # restore original pen state
def concentric_circles(turtle, radius):
for r in range(radius, 0, -10):
circle_around_point(turtle, r)
The key to circle() is that the current position is on the edge of the circle so you need to shift your position by the radius to make a specific point the center of the circle.
However, to solve this problem, I might switch from drawing to stamping and do it this way to speed it up and simplify the code:
import turtle
STAMP_SIZE = 20
radius = int(input("Please input a radius: "))
turtle.shape('circle')
turtle.fillcolor('white')
for r in range(radius, 0, -10):
turtle.shapesize(r * 2 / STAMP_SIZE)
turtle.stamp()
turtle.mainloop()
However, this draws crude circles as it's blowing up a small one:
To fix that, I might compromise between the two solutions above and do:
import turtle
radius = int(input("Please input a radius: "))
turtle.penup()
turtle.forward(radius)
turtle.left(90)
turtle.pendown()
turtle.begin_poly()
turtle.circle(radius)
turtle.penup()
turtle.end_poly()
turtle.addshape('round', turtle.get_poly()) # 'circle' is already taken
turtle.right(90)
turtle.backward(radius)
turtle.shape('round')
turtle.fillcolor('white')
for r in range(radius - 10, 0, -10):
turtle.shapesize(r / radius)
turtle.stamp()
turtle.mainloop()
This improves circle quality by shrinking a large one instead of enlarging a small one:
Where quality of the circle can be controlled using the steps= argument to the call to circle().
But, if I really wanted to minimize code while keeping quality high and speed fast, I might do:
import turtle
radius = int(input("Please input a radius: "))
for diameter in range(radius * 2, 0, -20):
turtle.dot(diameter, 'black')
turtle.dot(diameter - 2, 'white')
turtle.hideturtle()
turtle.mainloop()
The dot() method draws from the center instead of the edge, uses diameters instead of radii, draws only filled circles, and seems our best solution to this particular exercise:
import turtle
#### ##### #### Below class draws concentric circles.
class Circle:
def __init__(self, pen, cx, cy, radius):
self.pen = pen
self.cx = cx
self.cy = cy
self.radius = radius
def drawCircle(self):
self.pen.up()
self.pen.setposition( self.cx, self.cy - self.radius )
self.pen.down()
self.pen.circle(self.radius)
def drawConCircle(self, minRadius = 10, delta = 10):
if( self.radius > minRadius ) :
self.drawCircle()
self.radius -= delta # reduce radius of next circle
self.drawConCircle()
#### End class circle #######
win = turtle.Screen()
win.bgcolor("white")
s = Circle( turtle.Turtle(), 0, 0, 200 )
s.drawConCircle()
win.exitonclick()
I'm looking for best way to automatically find starting position for new turtle drawing so that it would be centered in graphics window regardless of its size and shape.
So far I've developed a function that checks with each drawn element turtle position to find extreme values for left, right, top and bottom and that way I find picture size and can use it to adjust starting position before releasing my code. This is example of simple shape drawing with my picture size detection added:
from turtle import *
Lt=0
Rt=0
Top=0
Bottom=0
def chkPosition():
global Lt
global Rt
global Top
global Bottom
pos = position()
if(Lt>pos[0]):
Lt = pos[0]
if(Rt<pos[0]):
Rt= pos[0]
if(Top<pos[1]):
Top = pos[1]
if(Bottom>pos[1]):
Bottom = pos[1]
def drawShape(len,angles):
for i in range(angles):
chkPosition()
forward(len)
left(360/angles)
drawShape(80,12)
print(Lt,Rt,Top,Bottom)
print(Rt-Lt,Top-Bottom)
This method does work however it seems very clumsy to me so I would like to ask more experiences turtle programmers is there a better way to find starting position for turtle drawings to make them centered?
Regards
There is no universal method to center every shape (before you draw it and find all your max, min points).
For your shape ("almost" circle) you can calculate start point using geometry.
alpha + alpha + 360/repeat = 180
so
alpha = (180 - 360/repeat)/2
but I need 180-alpha to move right (and later to move left)
beta = 180 - aplha = 180 - (180 - 360/repeat)/2
Now width
cos(alpha) = (lengt/2) / width
so
width = (lengt/2) / cos(alpha)
Because Python use radians in cos() so I need
width = (length/2) / math.cos(math.radians(alpha))
Now I have beta and width so I can move start point and shape will be centered.
from turtle import *
import math
# --- functions ---
def draw_shape(length, repeat):
angle = 360/repeat
# move start point
alpha = (180-angle)/2
beta = 180 - alpha
width = (length/2) / math.cos(math.radians(alpha))
#color('red')
penup()
right(beta)
forward(width)
left(beta)
pendown()
#color('black')
# draw "almost" circle
for i in range(repeat):
forward(length)
left(angle)
# --- main ---
draw_shape(80, 12)
penup()
goto(0,0)
pendown()
draw_shape(50, 36)
penup()
goto(0,0)
pendown()
draw_shape(70, 5)
penup()
goto(0,0)
pendown()
exitonclick()
I left red width on image.
I admire #furas' explanation and code, but I avoid math. To illustrate that there's always another way to go about a problem here's a math-free solution that produces the same concentric polygons:
from turtle import Turtle, Screen
def draw_shape(turtle, radius, sides):
# move start point
turtle.penup()
turtle.sety(-radius)
turtle.pendown()
# draw "almost" circle
turtle.circle(radius, steps=sides)
turtle = Turtle()
shapes = [(155, 12), (275, 36), (50, 5)]
for shape in shapes:
draw_shape(turtle, *shape)
turtle.penup()
turtle.home()
turtle.pendown()
screen = Screen()
screen.exitonclick()
Here's the exercise Lessons from a Triangle!
import turtle
def drawPolygon(t, sideLength, numSides):
turnAngle = 360 / numSides
for i in range(numSides):
t.forward(sideLength)
t.left(turnAngle)
def drawFilledCircle(anyTurtle, radius, vcolor):
anyTurtle.fillcolor(vcolor)
anyTurtle.begin_fill()
circumference = 2 * 3.1415 * radius
sideLength = circumference / 360
drawPolygon(anyTurtle, sideLength, 360)
anyTurtle.end_fill()
wn = turtle.Screen()
wheel = turtle.Turtle()
drawFilledCircle(wheel, 20, 'purple')
wn.exitonclick()
1) How come when I try to change the speed of the turtle like wheel.speed(10) it doesn't work? What's the default speed if I don't indicate the speed?
2) How do i put my turtle to the middle of the circle once it's done?
Thank You so Much!
As abarnert said, the link to your exercise is broken, but there are a few things you can do to speed up your program. FWIW, the turtle module has a .circle method, but I guess the point of your exercise is to use a polygon to approximate a circle.
wheel.speed(10) does work (although wheel.speed(0) is even faster). It doesn't appear to make much difference because the sides of your 360-sided polygon are so tiny, and so the turtle has to do several moves & turns just to traverse a single pixel.
Using a 360-sided polygon to draw a circle, no matter what the radius is, is not a great strategy. The code below determines the number of sides from the circumference so that each side is approximately 1 pixel. This will look good for a circle of any radius, and it avoids doing too much work for small circles.
Apart from using turtle.speed to speed things up you can also reduce the canvas's frame delay. Also, if you hide the turtle while drawing, it'll go even faster.
The following code was tested on Python 2.6.6; it should also work without modification on Python 3.x, but on Python 3.x you may remove the from __future__ import division, print_function line.
#!/usr/bin/env python
''' Approximate a circle using a polygon
From http://stackoverflow.com/q/30475519/4014959
Code revised by PM 2Ring 2015.05.27
'''
from __future__ import division, print_function
import turtle
def drawPolygon(t, sideLength, numSides):
turnAngle = 360 / numSides
for i in range(numSides):
t.forward(sideLength)
t.left(turnAngle)
def drawFilledCircle(anyTurtle, radius, vcolor):
anyTurtle.fillcolor(vcolor)
anyTurtle.begin_fill()
circumference = 2 * 3.14159 * radius
#Calculate number of sides so that each side is approximately 1 pixel
numSides = int(0.5 + circumference)
sideLength = circumference / numSides
print('side length = {0}, number of sides = {1}'.format(sideLength, numSides))
drawPolygon(anyTurtle, sideLength, numSides)
anyTurtle.end_fill()
wn = turtle.Screen()
#Set minimum canvas update delay
wn.delay(1)
wheel = turtle.Turtle()
#Set fastest turtle speed
wheel.speed(0)
#wheel.hideturtle()
radius = 20
#Move to the bottom of the circle, so
#that the filled circle will be centered.
wheel.up()
wheel.goto(0, -radius)
wheel.down()
drawFilledCircle(wheel, radius, 'purple')
#Move turtle to the center of the circle
wheel.up()
wheel.goto(0, 0)
#wheel.showturtle()
wn.exitonclick()