python - 在 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 坐标在不同的位置绘制其中的几个。
我一直在玩它,但没有运气。你能帮我吗?
解决方案
乌龟从 (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()
推荐阅读
- r - dplyr - 在同一个管道中变异和计数
- javascript - 为什么这不是一个函数?
- android - 无法使用 Moshi 在 Retrofit 中为类创建 @Body 转换器
- go - 如何在 Cloud Run 上使用 Stackdriver 日志记录
- python-3.x - 使用 azure-storage-blob 或 azure-storage 上传和删除 Azure 存储 Blob
- stm32 - STM32F373 SDADC Hal - 为什么在单端零参考模式下对 HAL_SDADC_Start_DMA 中的 pData 使用 uint32_t 类型?
- python - Pyside2构建几个按钮和内存
- regex - 仅用感叹号提取字母和连字符问题
- sqlite - 一个语句中的两个查询
- xcode - 使用键盘在 Xcode 中的不同区域之间导航