[英]Is there a command for touching an object or a colour in turtle python?
[英]Turtle Graphics “if touching colour”
我试图在Turtle中编写一个程序,该程序先绘制一棵圣诞树,然后绘制一些小玩意,然后将它们随机放置在树上。 但是,由于圣诞树是不规则形状,因此我无法通过随机选择x和y坐标来放置小玩意。 有没有办法将小玩意随机放在树上? 我当时考虑的是“ turtle.pendown()”,然后考虑“如果turtle.pen碰到“绿色””,但是我不确定如何编写此代码。 任何帮助将不胜感激。
一种简单的图形方法是:
查找具有用于执行“多边形中的点”包含测试的例程的Python模块
使用turtle的begin_poly()
, end_poly()
和get_poly()
来捕获您的代码在绘制树时生成的顶点
在树的边界框中随机生成装饰物,但也应用交叉编号测试以查看其中心是否在树上
这是使用(异常)抽象树和装饰物的示例实现:
from turtle import Turtle, Screen
from random import randrange, choice
from point_in_polygon import cn_PnPoly
screen = Screen()
WINDOW_WIDTH, WINDOW_HEIGHT = screen.window_width(), screen.window_height()
COLORS = ["red", "yellow", "gold", "blue", "white", "pink"]
def draw_abstract_tree(turtle):
width = WINDOW_WIDTH//4
turtle.penup()
turtle.goto(0, -WINDOW_HEIGHT//4)
turtle.pendown()
for _ in range(8):
turtle.forward(width)
turtle.left(150)
turtle.forward(1.156 * width)
turtle.right(150)
width *= 0.9
turtle.left(210)
for _ in range(8):
turtle.forward(1.156 * width)
turtle.left(150)
turtle.forward(width)
turtle.right(150)
width /= 0.9
turtle.goto(0, -WINDOW_HEIGHT//4)
turtle.setheading(0)
def decorate_tree(turtle, polygon):
turtle.penup()
for _ in range(1000):
x = randrange(-WINDOW_WIDTH/4, WINDOW_WIDTH/4)
y = randrange(-WINDOW_HEIGHT/4, WINDOW_HEIGHT)
diameter = randrange(1, 12)
if cn_PnPoly((x, y), polygon):
turtle.goto(x, y)
turtle.color(choice(COLORS))
turtle.dot(diameter)
yertle = Turtle(visible=False)
yertle.speed("fastest")
yertle.color("darkgreen")
yertle.begin_poly()
draw_abstract_tree(yertle)
yertle.end_poly()
polygon = yertle.get_poly()
yertle.begin_fill()
draw_abstract_tree(yertle)
yertle.end_fill()
decorate_tree(yertle, polygon)
screen.exitonclick()
输出值
我认为turtle
没有检查颜色的方法。
但是turtle
使用Canvas
从tkinter
具有功能find_overlaping(rectangle)
,以检查是否存在重叠对象这个矩形。 也许可以。 也许您可以检查随机位置的小矩形中是否有树。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.