Python 海龟螺旋
Python Turtle Spiral
我写了一个程序先画分形再画螺旋。螺旋应该遵循斐波那契模式,并且本质上应该是递归的
这是代码 -
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)
#x,y are start coordinates, stLength is the length of first move and k is the number of moves
spiral(225, -120, 35, 5)
s.exitonclick()
您似乎缺少 a
和 b
的初始化:
a = 0
b = 1
这是经过此修复的代码的简化版本:
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()
我写了一个程序先画分形再画螺旋。螺旋应该遵循斐波那契模式,并且本质上应该是递归的
这是代码 -
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)
#x,y are start coordinates, stLength is the length of first move and k is the number of moves
spiral(225, -120, 35, 5)
s.exitonclick()
您似乎缺少 a
和 b
的初始化:
a = 0
b = 1
这是经过此修复的代码的简化版本:
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()