【问题标题】:How do i make the dots the land in the triangle change color我如何使三角形中的点改变颜色
【发布时间】:2013-08-13 06:30:46
【问题描述】:

这是我的代码,它使用海龟绘制一个三角形,然后生成 300 个随机点,我的问题是如何使落在三角形内部的点改变颜色,例如蓝色,而三角形外部的点保持黑色?有人可以添加到我的代码中吗?提前致谢。

from turtle import *
from random import randint
speed("fastest")

area_size = 800 
max_coord = area_size / 2
num_dots = 300 
setup(area_size, area_size)

penup()
goto(-200, -200)
pendown()
goto(200, -200)
goto(200, 200)
goto(-200,-200)

for _ in range(num_dots):

    dots_pos_x = randint(-max_coord, max_coord)
    dots_pos_y = randint(-max_coord, max_coord)

    penup()
    goto(dots_pos_x, dots_pos_y)
    dot(7)
    pendown()

hideturtle()
done()

【问题讨论】:

    标签: python python-2.7 turtle-graphics


    【解决方案1】:

    就在您致电dot 之前,添加以下代码:

    if -200 < dots_pos_y < dots_pos_x < 200:
        pencolor('blue')
    else:
        pencolor('black')
    

    if 语句会测试您为点选择的随机坐标是否落在三角形内。 Python 的比较运算符链使这非常紧凑!更明确的测试版本是:

    (dots_pos_y > -200 and      # above bottom edge of the triangle
     dots_pos_x < 200 and       # to the left of the right edge
     dots_pos_x > dots_pos_y)   # to the lower-right of the diagonal edge
    

    在 Python 中,像 A &lt; B &lt; C 这样的链式比较表达式等价于 A &lt; B and B &lt; C,因此这两个版本的结果相同(如果您重新排列它们)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-29
      • 2015-01-23
      相关资源
      最近更新 更多