在 python 乌龟中绘制 3D 多色三角形

Drawing a 3D multicolor triangle in python turtle

我需要制作这个三角形 (https://i.imgur.com/DKVMxfW.png) in turtle, but just can't quite get the dimensions right. In addition to this, I also need each quadrant of the triangle to display in a different color according to a list I have set... I can do that later. But I am having trouble getting the length/widths of the triangle to be correct. I will link a picture of something similar to what It needs to be here (https://i.imgur.com/E7Skzcc.png) 这是我能找到的最接近我需要它做的事情。我如何使用 width, width * math.sqrt(2), and width 之类的东西来获取三角形的长度和宽度?任何帮助是极大的赞赏。对不起,如果我的英语不好,那不是我的母语。以下是我到目前为止所写的内容。


turtle.setup(575,575)
pen = turtle.Turtle()
pen.speed(0)
pen.pensize(2)
pen.hideturtle()

width = random.randint(25,100)

def draw_art_cube(x,y):
    draw_triangle(width, width * math.sqrt(2) + width)

def draw_triangle(x,y):
    pen.up()
    pen.setpos(x,y)
    pen.down()
    pen.setheading(0)
    pen.forward(width)
    pen.left(width)





turtle.onscreenclick(draw_art_cube)

turtle.done()

您的 draw_triangle() 功能被严重承保了。您至少需要画六行,但您的代码只画了 一行 !让我们充实这个函数,让它绘制示例图像:

from turtle import Screen, Turtle
from random import randint

def draw_art_cube(x, y):
    screen.onscreenclick(None)  # Disable handler inside handler

    pen.up()
    pen.setposition(x, y)
    pen.down()

    width = randint(25, 100)
    draw_triangle(width)

    screen.onscreenclick(draw_art_cube)  # Reenable handler on exit

def draw_triangle(short):

    long = short * 2**0.5

    pen.setheading(0)

    for _ in range(4):
        pen.forward(short)
        pen.left(135)
        pen.forward(long)
        pen.left(135)
        pen.forward(short)

        pen.left(180)

screen = Screen()
screen.setup(575, 575)

pen = Turtle()
pen.hideturtle()
pen.speed('fastest')
pen.pensize(2)

screen.onscreenclick(draw_art_cube)
screen.mainloop()

此绘图代码效率低下,因为它绘制了 12 条(有些冗余)线,而我们可以只用一半的线。但它应该为您提供一个工作起点,让您思考绘制此图的最佳方式。