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

这段代码画了一个正方形,用一条线把它分成两个相等的三角形。我怎样才能让落在广场一半的点变成红色但当它们落在广场的另一半时变成蓝色。没有落在正方形中的点保持黑色。

4

2 回答 2

0

我猜您正在使用 random 模块并首先生成 x 坐标,然后生成 y 坐标。如果这确实是您的方法,那么在您生成它时对每个方法进行检查,看看它是否在您的盒子范围内。即if (x > 10) and (x < 20):if (y > 15) and (y < 25):如果语句为真,则将变量 the_color 设置为红色,else将其设置为蓝色

于 2013-08-12T04:42:02.867 回答
0

由于已经有几年了,以下是解决此问题的可能方法。请注意,我切换turtle.dot()turtle.stamp()which 将执行速度提高了 2.5 倍:

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

请注意,我使用绿色而不是蓝色,因为我很难区分小蓝点和小黑点!

输出

在此处输入图像描述

最后,它会打印出每种颜色打印了多少个点:

> python3 test.py
Black: 279
Red: 5
Green: 16
>
于 2016-12-26T21:25:31.230 回答