[英]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.