首页 > 解决方案 > 在 Python 中使用随机 x,y 坐标绘制阿基米德螺线

问题描述

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

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()

然而,这个螺旋只能在一个固定的坐标上绘制。我希望能够使用randint()生成的 x、y 坐标在不同的位置绘制其中的几个。

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

标签: pythonturtle-graphics

解决方案


乌龟从 (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()

在此处输入图像描述


推荐阅读