[英]How do I make the Turtle drawing speed faster?
如何制作 Python 库 Turtle,运行并在 1 个屏幕刻度内绘制一个正方形?
import turtle as t
import math
def square():
t.penup()
t.goto(cord_x_1, cord_y_1)
t.pendown()
t.goto(cord_x_2, cord_y_2)
t.goto(cord_x_3, cord_y_3)
t.goto(cord_x_4, cord_y_4)
t.goto(cord_x_1, cord_y_1)
t.penup()
t.speed(0)
theta = 0
print("What do you want for angle Θ?")
radians_theta = math.fmod(float(theta), 360)
sqrt = math.sqrt((50)**2+(50)**2)
while 2 > 1:
radians_theta = math.fmod(float(theta), 360)
#cord setup
cord_x_1 = sqrt * math.cos(radians_theta)
cord_y_1 = sqrt * math.sin(radians_theta)
cord_x_2 = sqrt * math.cos(radians_theta + math.radians(90))
cord_y_2 = sqrt * math.sin(radians_theta + math.radians(90))
cord_x_3 = sqrt * math.cos(radians_theta + math.radians(180))
cord_y_3 = sqrt * math.sin(radians_theta + math.radians(180))
cord_x_4 = sqrt * math.cos(radians_theta + math.radians(270))
cord_y_4 = sqrt * math.sin(radians_theta + math.radians(270))
#repeat
t.clear()
square()
theta += 30
theta = theta % 360
print(theta)
我想要的是让乌龟非常快地绘制旋转的正方形。 我尝试将速度设置为 0,但这还不够快。 有谁知道我怎样才能加速乌龟?
当然。 有时乌龟速度不够快,所以有一种方法可以让 go 更快。 方法是完全禁用animation 。 t.tracer(0)
将禁用 animation。所以把它放在代码顶部附近的某个地方。 现在,在您的代码结束时,您将需要t.update()
来在海龟完成后强制更新并将其显示在屏幕上。
我们可能会通过预先计算绘制的固定图像集来简单地添加tracer()
和update()
:
from turtle import Screen, Turtle, Vec2D
from math import sin, cos, radians, sqrt
from itertools import cycle
def square(cord_1, cord_2, cord_3, cord_4):
turtle.goto(cord_1)
turtle.pendown()
turtle.goto(cord_2)
turtle.goto(cord_3)
turtle.goto(cord_4)
turtle.goto(cord_1)
turtle.penup()
def draw():
theta, cord_1, cord_2, cord_3, cord_4 = next(endless_coordinates)
turtle.clear()
square(cord_1, cord_2, cord_3, cord_4)
screen.update()
print(theta)
screen.ontimer(draw)
theta = 0
delta = 30
diagonal = sqrt(2 * 50**2)
coordinates = []
for theta in range(0, 360, delta):
theta_radians = radians(theta)
cord_1 = diagonal * Vec2D(cos(theta_radians), sin(theta_radians))
cord_2 = diagonal * Vec2D(cos(theta_radians + radians(90)), sin(theta_radians + radians(90)))
cord_3 = diagonal * Vec2D(cos(theta_radians + radians(180)), sin(theta_radians + radians(180)))
cord_4 = diagonal * Vec2D(cos(theta_radians + radians(270)), sin(theta_radians + radians(270)))
coordinates.append((theta, cord_1, cord_2, cord_3, cord_4))
endless_coordinates = cycle(coordinates)
screen = Screen()
screen.tracer(False)
turtle = Turtle()
turtle.hideturtle()
turtle.penup()
draw()
screen.exitonclick()
我们还可以通过旋转海龟本身来消除海龟级别的绘图,将所有绘图向下推到C级别:
from turtle import Screen, Turtle
SQUARE_SIZE = 100
DELTA = 30
CURSOR_SIZE = 20
theta = 0
def draw():
global theta
turtle.left(DELTA)
screen.update()
theta = (theta + DELTA) % 360
print(theta)
screen.ontimer(draw)
screen = Screen()
screen.tracer(False)
turtle = Turtle()
turtle.shape('square')
turtle.fillcolor('white')
turtle.shapesize(SQUARE_SIZE / CURSOR_SIZE)
turtle.penup()
draw()
screen.exitonclick()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.