Spirograph Turtle Python - 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)

Related

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)

How to do animation using Zelle graphics module?

I need help to design my graphics, without turtle nor tkinter, but with Zelle graphics.py. The problem is that I need to run 4 circles moving at the same time. Here's the code I have so far:
from graphics import *
import time #import time module
from random import randrange
def rand_color():#generates a random color and returns that color
return(color_rgb(randrange(256),randrange(256),randrange(256)))
def main():
win = GraphWin("My Circle",500,500)
c = Circle(Point(20,20),20)
c.setFill(rand_color())
c.draw(win)
for i in range(1,461):
c.move(1,1)
time.sleep(.005)
c = Circle(Point(20,20),20)
c.setFill(rand_color())
c.draw(win)
for i in range(1,461):
c.move(-1,1)
time.sleep(.005)
c = Circle(Point(20,20),20)
c.setFill(rand_color())
c.draw(win)
for i in range(1,461):
c.move(1,-1)
time.sleep(.005)
c = Circle(Point(20,20),20)
c.setFill(rand_color())
c.draw(win)
for i in range(1,461):
c.move(1,1)
time.sleep(.005)
main()
I don't know how to move multiple objects at once. How would one go about this?
Rather move each circle completely in turn, chop up the movements and alternate them so each circle moves a little at a time in round robin. I'm guessing this is close to what you're trying to do:
from random import randrange
from graphics import *
def rand_color():
""" Generate a random color and return it. """
return color_rgb(randrange(256), randrange(256), randrange(256))
win = GraphWin("My Circle", 500, 500)
circles = []
for x in [-1, 1]:
for y in [-1, 1]:
circle = Circle(Point(250, 250), 20)
circle.setFill(rand_color())
circle.draw(win)
circles.append((circle, (x, y)))
for _ in range(250):
for circle, (x, y) in circles:
circle.move(x, y)
win.getMouse() # Pause to view result
win.close() # Close window when done

Turning simple polygons about a point in Python Turtle

I need help turning polygon shapes (triangle and square) in Python turtle to match a picture.
Below I am trying to copy the image.
I specifically need help on what to add to my code given the triangle and square to have them repeat outwards like the picture. Because as of now the triangles and squares look like this (pentagon code is correct and works) All help is appreciated. Thank you.
import turtle
def polygon(turtle, side, length):
turtle.color("Blue")
for i in range(4):
turtle.backward(length)
turtle.left(side)
def polygon1(turtle, side1, length):
turtle.color("Green")
for i in range(3):
turtle.left(side1)
turtle.forward(length)
def polygon2(turtle, side2, length):
turtle.color("Red")
for i in range(5):
turtle.forward(length)
turtle.left(side2)
def main():
my_turtle = turtle.Turtle()
wn = turtle.Screen()
Bill = turtle.Turtle()
length = 100
side = 90
side1 = 120
side2 = 72
Bill.pensize(5)
Bill.speed(0)
#Pentagons
Bill.pu()
Bill.right(180)
y = -45
for i in range(5):
Bill.pu()
Bill.goto(60, y)
Bill.pd()
polygon2(Bill, side2, length)
y -= 20
#Triangle
Bill.pu()
Bill.left(240)
x = 45
for j in range(5):
Bill.pu()
Bill.goto(10, x)
Bill.pd()
polygon1(Bill, side1, length)
x += 20
#Square
Bill.pu()
Bill.left(240)
b = 6
for b in range(5):
Bill.pu()
Bill.goto(148, b)
Bill.pd()
polygon(Bill, side, length)
b -= 20
wn.exitonclick()
if __name__ == '__main__':
main()
pentagon code is correct and works
I don't believe the pentagon code is correct nor that you're approaching this in the correct way. The inner three shapes should form an equilateral triangle -- yours don't as you're eyeballing instead of calculating. Instead of trying to get the turtle to be in the right spot, why not have the turtle move forward in the direction of the sides of this central triangle, drawing polygons as it goes.
That is, embrace the drawing as a whole rather than trying to divide and conquer.
We'd need to make sure the polygon drawing code restores the turtle's state when it's done, so it can simply move forward to the next polygon. We'll need to make explicit which numbers are arbitrary, and which are calculable. Although the original diagram appears to use at least three turtles to achieve it's result, we'll do it with one as you attempted:
from turtle import Turtle, Screen
SHAPES = [(5, "Red"), (3, "Green"), (4, "Blue")]
LENGTH = 100
DELTA = 20
REPLICATIONS = 5
THICKNESS = 5
HEIGHT = (3 ** 0.5 / 2) * LENGTH # assumes 3 shapes, should fix!
DIVISIONS = 360 / len(SHAPES)
def polygon(turtle, sides, color):
turtle.color(color)
turtle.left(90)
turtle.forward(LENGTH / 2)
for _ in range(sides):
turtle.right(360 / sides)
turtle.forward(LENGTH)
turtle.backward(LENGTH / 2) # restore turtle to original state
turtle.right(90)
wn = Screen()
bill = Turtle()
bill.speed('fastest')
bill.pensize(THICKNESS)
bill.penup()
for offset, (sides, color) in enumerate(SHAPES):
bill.setheading(-DIVISIONS * offset - 90)
bill.forward(HEIGHT / 3) # assumes 3 shapes, should fix!
for _ in range(REPLICATIONS):
bill.pendown()
polygon(bill, sides, color)
bill.penup()
bill.forward(DELTA)
bill.home()
wn.exitonclick()

How to draw Circle using Turtle in Python 3

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

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

Categories

Resources