用随机的x,y坐标在Python中绘制一个阿基米德螺旋

时间:2018-08-20 23:01:47

标签: python turtle-graphics

如何使用带有随机x,y坐标的Python 3绘制阿基米德螺线?我在这里有此代码:

p <- as.party(fit)
print(p, FUN = myfun)
## Model formula:
## Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species
## 
## Fitted party:
## [1] root
## |   [2] Petal.Length < 4.25
## |   |   [3] Petal.Length < 3.4
## |   |   |   [4] Sepal.Width < 3.25: 4.735 (serr = 0.239)
## |   |   |   [5] Sepal.Width >= 3.25: 5.17 (serr = 0.289) 
## |   |   [6] Petal.Length >= 3.4: 5.64 (serr = 0.25)  
## |   [7] Petal.Length >= 4.25
## |   |   [8] Petal.Length < 6.05
## |   |   |   [9] Petal.Length < 5.15
## |   |   |   |   [10] Sepal.Width < 3.05: 6.055 (serr = 0.404)
## |   |   |   |   [11] Sepal.Width >= 3.05: 6.53 (serr = 0.38)  
## |   |   |   [12] Petal.Length >= 5.15: 6.604 (serr = 0.302)
## |   |   [13] Petal.Length >= 6.05: 7.578 (serr = 0.228)
## 
## Number of inner nodes:    6
## Number of terminal nodes: 7

但是,该螺旋只能在固定坐标上绘制。我希望能够使用from turtle import * from math import * color("blue") down() for i in range(200): t = i / 20 * pi x = (1 + 5 * t) * cos(t) y = (1 + 5 * t) * sin(t) goto(x, y) up() done() 生成的x,y坐标在不同的位置绘制其中的几个。

我一直在玩它,但是没有运气。你能帮忙吗?

1 个答案:

答案 0 :(得分:2)

乌龟从(x,y)设置为(0,0)开始,这就是为什么螺旋在屏幕上居中的原因。您可以选择一个随机位置,然后在goto()中将该位置的x,y添加到计算出的螺旋x,y中:

from turtle import Turtle, Screen
from math import pi, sin, cos
from random import randint, random

RADIUS = 180  # roughly the radius of a completed spiral

screen = Screen()

WIDTH, HEIGHT = screen.window_width(), screen.window_height()

turtle = Turtle(visible=False)
turtle.speed('fastest')  # because I have no patience

turtle.up()

for _ in range(3):
    x = randint(RADIUS - WIDTH//2, WIDTH//2 - RADIUS)
    y = randint(RADIUS - HEIGHT//2, HEIGHT//2 - RADIUS)
    turtle.goto(x, y)

    turtle.color(random(), random(), random())
    turtle.down()

    for i in range(200):
        t = i / 20 * pi
        dx = (1 + 5 * t) * cos(t)
        dy = (1 + 5 * t) * sin(t)

        turtle.goto(x + dx, y + dy)

    turtle.up()

screen.exitonclick()

enter image description here