根据它们在 Python 海龟中的位置设置点颜色? [英] Set dot color based on where they are in Python turtle?

查看:37
本文介绍了根据它们在 Python 海龟中的位置设置点颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

推荐答案

几年过去了,下面是这个问题的可能解决方案.请注意,我从 turtle.dot() 切换到 turtle.stamp() 这将执行速度提高了 2.5 倍:

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!

输出

最后它会打印出每种颜色的打印点数:

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
>

这篇关于根据它们在 Python 海龟中的位置设置点颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆