简体   繁体   中英

how can i make dots change color when they enter a square

Ok so this code draws a square using turtle graphics and then creates about 300 randomly placed dots on the screen. What could i add or change in my current code to make the dots the land INSIDE the square to change color for example red. and the dots that land outside remain the same color? Is there a simple way of doing this? Could anyone add anything to my code? 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)
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()

I added a few lines to your for loop that does what you requested:

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)
    if -200 <= dots_pos_x <= 200 and -200 <= dots_pos_y <= 200:
        pencolor((255, 0, 0))
    else:
        pencolor((0, 0, 0))
    dot(7)
    pendown()

With regards to your comment in Brionius' Answer, if you have a perfectly sized square and the diagonal line runs through to both corners (ie goes from bottom corner to top corner), all you need to do is say:

if(xcor() < ycor()): 
    # Do whatever
else :
    # Do whatever

This is because we are assuming that a diagonal line through a square has a gradient of 1. I hope I made myself clear.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM