问题
from turtle import *
from random import randint
speed("fastest")
pendown()
goto(200, 0)
goto(200, 200)
goto(0, 200)
goto(0,0)
goto(200,200)
area_size = 800
max_coord = area_size / 2
num_dots = 300
setup(area_size, area_size)
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(4)
pendown()
hideturtle()
done()
This code draws a square with a line splitting it into two equal triangles. How can i get the dots that land in one half of the square to turn red but turn blue when they land in the other half of the square. The dots that don't land in the square stay black.
回答1:
I'm guessing you're using the random module and generating first the x coordinate and then the y coordinate. If this is indeed your method, then run a check on each as you generate it to see if it's within the confines of your box. ie if (x > 10) and (x < 20):
and if (y > 15) and (y < 25):
If the statement is true then set a variable the_color to red, else
, set it to blue
回答2:
Since it's been a few years, below is a posible solution to this problem. Note that I switched from turtle.dot()
to turtle.stamp()
which speeds up the execution by 2.5X:
from turtle import Turtle, Screen
from random import randint
AREA_SIZE = 800
MAX_COORD = AREA_SIZE / 2
SQUARE_SIZE = 200
DOT_SIZE = 4
NUM_DOTS = 300
STAMP_SIZE = 20
screen = Screen()
screen.setup(AREA_SIZE, AREA_SIZE)
turtle = Turtle(shape="circle")
turtle.shapesize(DOT_SIZE / STAMP_SIZE)
turtle.speed("fastest")
for _ in range(4):
turtle.forward(SQUARE_SIZE)
turtle.left(90)
turtle.left(45)
turtle.goto(SQUARE_SIZE, SQUARE_SIZE)
turtle.penup()
black, red, green = 0, 0, 0
for _ in range(NUM_DOTS):
color = "black"
x = randint(-MAX_COORD, MAX_COORD)
y = randint(-MAX_COORD, MAX_COORD)
turtle.goto(x, y)
# color dot if it's in the square but not smack on any of the lines
if 0 < x < SQUARE_SIZE and 0 < y < SQUARE_SIZE:
if x < y:
color = "green" # easier to distinguish from black than blue
green += 1
elif y < x:
color = "red"
red += 1
else black += 1 # it's on the line!
else:
black += 1 # it's not in the square
turtle.color(color)
turtle.stamp()
turtle.hideturtle()
print("Black: {}\nRed: {}\nGreen: {}".format(black, red, green))
screen.exitonclick()
Note that I used green instead of blue as I was having too hard a time distinguishing the tiny blue dots from the tiny black dots!
OUTPUT
At the end it prints out a tally of how many dots of each color were printed:
> python3 test.py
Black: 279
Red: 5
Green: 16
>
来源:https://stackoverflow.com/questions/18179588/set-dot-color-based-on-where-they-are-in-python-turtle