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