根据它们在Python龟中的位置设置点颜色?

时间:2013-08-12 04:34:54

标签: python python-2.7 turtle-graphics

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

此代码绘制一个正方形,其中一条线将其拆分为两个相等的三角形。如何让落在广场一半的圆点变成红色,但当它们落在广场的另一半时变成蓝色。没有落在广场上的圆点保持黑色。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

由于已经过了几年,以下是这个问题的可行解决方案。请注意,我从turtle.dot()切换到turtle.stamp(),这加快了执行速度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()

请注意,我使用绿色代替蓝色,因为我太难以区分小蓝点和小黑点!

输出

enter image description here

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

> python3 test.py
Black: 279
Red: 5
Green: 16
>