1

This is my code, it draws a triangle using turtle, and then generate 300 random dots, my question is how do i make the dots that land INSIDE the triangle change color for example blue and the dots outside the triangle remain black? could someone add onto my code please? Thanks in advance.

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()
4

1 回答 1

0

就在您调用 之前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 中,链式比较表达式 likeA < B < C等价于A < B and B < C,因此两个版本的结果相同(如果您重新排列它们)。

于 2013-08-13T07:51:41.987 回答