用 Python 海龟堆叠三角形

N.普莱斯纳

我需要在彼此之上绘制 4 个不同颜色的三角形。我已经想出了如何将 4 个并排绘制,但我无法将它们叠在一起。这是我的代码:

import turtle
import math
from random import randint

otto = turtle.Turtle()

def repeat_triangle(t, l):
    setcolor(t, 1)
    for i in range(4):
        t.color(randint(0,255),randint(0,255),randint(0,255))
        t.begin_fill()
        t.fd(100) 
        t.lt(120)
        t.fd(100)
        t.lt(120)
        t.fd(100)
        t.lt(120)
        t.fd(100)
        otto.end_fill()


otto.shape('turtle')
repeat_triangle(otto, 80)

turtle.mainloop()
turtle.bye()

奥托是我的乌龟的名字。setcolor 是我编写的用于分配随机颜色的函数。另外,你能告诉我如何画一堆 3x3 的三角形吗?非常感谢。我正在使用 jupyter notebooks,所以它可能与常规 Python 有一些不同。图片参考可以在这里找到

cdlane

通过冲压而不是绘图更好地生活的另一个例子

from turtle import Screen, Turtle
from random import random

TRIANGLE_EDGE = 100
CURSOR_EDGE = 20

TRIANGLE_HEIGHT = TRIANGLE_EDGE * 3 ** 0.5 / 2

def repeat_triangle(turtle, repetitions):
    for _ in range(repetitions):
        turtle.color(random(), random(), random())
        turtle.stamp()
        turtle.forward(TRIANGLE_HEIGHT)

screen = Screen()

otto = Turtle('triangle', visible=False)
otto.penup()
otto.setheading(90)
otto.shapesize(TRIANGLE_EDGE / CURSOR_EDGE)

repeat_triangle(otto, 4)

screen.mainloop()

在此处输入图片说明

此外,此代码可能不正确,具体取决于您使用的海龟变体:

t.color(randint(0,255),randint(0,255),randint(0,255))

Python 附带的海龟默认为float从 0 到 1 - 如果您想使用int从 0 到 255,则必须通过以下方式请求:

turtle.colormode(255)

对您的绘图代码进行简单的返工以堆叠三角形可能是:

from turtle import Screen, Turtle
from random import randint

def repeat_triangle(t, length):
    height = length * 3 ** 0.5 / 2

    for _ in range(4):
        t.color(randint(0, 255), randint(0, 255), randint(0, 255))

        t.begin_fill()

        for _ in range(3):
            t.fd(length)
            t.lt(120)

        t.end_fill()

        t.sety(t.ycor() + height)

screen = Screen()
screen.colormode(255)

otto = Turtle('turtle')
otto.penup()

repeat_triangle(otto, 100)

screen.mainloop()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章