简体   繁体   中英

Python Turtle Spiral

I wrote a program to draw a fractal and then draw a fibonaaci spiral after the fractal funnction is completed. However, my spiral function isn't working. I'm unsure of the problem. I had copy pasted some code from GeeksforGeeks for this ( https://www.geeksforgeeks.org/python-plotting-fibonacci-spiral-fractal-using-turtle/ ) and the problem lies in the spiral() function of the code.

Here's the code -

from turtle import Turtle, Screen
import math

t = Turtle()
s = Screen()
t.speed(0)

def square(x, y, side):
    t.setpos(x,y)
    for i in range(4):
        t.forward(side)
        t.right(90)

def tiltsquare(x, y, side):
    t.left(45)
    square(x, y, side)

def squareinsquare(x, y, side):
    square(x, y, side)
    half = side / 2
    b = math.sqrt(half**2 + half**2)

    tiltsquare(x, y - side/2, b)

#squareinsquare(0, 0, 200)

def fractal(x, y, startSide, k):  
    t.setpos(x, y)
    for i in range(k):
        square(*t.pos(), startSide)
        t.forward(startSide / 2)
        t.right(45)
        startSide /= math.sqrt(2) 

fractal(0, 0, 200, 15)

#x,y are start coordinates, stLength is the length of first move and k is the number of moves
def spiral(x, y, stLength, k): 
    t.up()
    t.setpos(x, y)
    t.seth(45)
    t.down()
    
    for i in range(k):
        fdwd = math.pi * b * x / 2
        fdwd /= 90
        for j in range(90):
            t.forward(fdwd)
            t.left(1)
        temp = a
        a = b
        b = temp + b

spiral(225, -120, 35, 5)


s.exitonclick()

You appear to be missing the initialization of a and b :

    a = 0
    b = 1

Here's a simplified version of the code with this fix:

from turtle import Turtle, Screen
from math import pi

def square(x, y, side):
    turtle.setpos(x, y)

    for _ in range(4):
        turtle.forward(side)
        turtle.right(90)

def fractal(x, y, startSide, k):
    turtle.setpos(x, y)

    for _ in range(k):
        square(*turtle.position(), startSide)
        turtle.forward(startSide / 2)
        turtle.right(45)
        startSide /= 2**0.5

screen = Screen()

turtle = Turtle()
turtle.speed('fastest')

fractal(0, 0, 200, 15)

# x, y are start coordinates and k is the number of moves

def spiral(x, y, k):
    turtle.penup()
    turtle.setposition(x, y)
    turtle.setheading(45)
    turtle.pendown()

    a = 0
    b = 1

    for _ in range(k):
        distance = (pi * b * x / 2) / 90

        for _ in range(90):
            turtle.forward(distance)
            turtle.left(1)

        a, b = b, a + b

spiral(225, -120, 5)

screen.exitonclick()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM