簡體   English   中英

如何使Turtle識別一個圓圈?

[英]How can I make Turtle recognize a circle?

我正在嘗試使用Turtle Graphics制作一個Python程序,該程序在矩形內繪制兩個重疊的圓(如維恩圖),並在維恩圖上繪制隨機點。

我已經成功完成了此操作,但是現在我想讓程序識別點是否在圓中之一或在維恩圖的交點中。 然后,我想根據它們所在的區域來更改點的顏色。

到目前為止,我對該程序所做的工作是列出變量,定義形狀並進行for循環以隨機生成點。

turtle只是一個圖形庫-它無法跟蹤您在屏幕上繪制的對象。 因此,要計算給定點是否在您的維恩圖圓中,您需要執行以下步驟:

  1. 調用circle()時,存儲每個圓的坐標(類會有所幫助,但是可能您還沒有學到這些)
  2. 調用一個函數以測試該點是否在存儲的圓坐標空間中。 這將是對笛卡爾坐標的純數學運算。 @Tim提供的鏈接( 用於測試點是否在圓內的方程式 )將幫助您實現這一目標。

關於步驟1的一些指導

畫圓時,有其中心(當前烏龜位置)和半徑。 從那里開始,獲得該圓內的所有點僅僅是幾何(如果您不能推導公式,快速搜索將為您提供幫助)。 我建議您創建一個繪制維恩圖圓的函數,並返回一個圓內的點。 像這樣:

def venn_circle(circle_color, circle_radius):
    """ Draws a colored circle, returns the points within. """
    turtle.color(circle_color)
    # <fill in: code to move, orient the turtle>
    center = turtle.position()
    # <fill in: code to draw the circle>
    return circle_coords(center, circle_radius)


def circle_coords(center, radius):
    """ Return the set of pixels within the circle. """
    raise NotImplementedError()

還有一個簡短的提示-絕對不要from package import * 在某些情況下可以,但是通常只會帶來麻煩。 在我的示例代碼中,我假設您已將此慣用法替換為import turtle

我有非常相似的作業,試圖通過簡單的方法解決它:

import tkinter
import random

canvas = tkinter.Canvas(width = 300, height = 200, bg = "white")
canvas.pack()

n = 500

for i in range(n):
    x = random.randrange(0, 300)
    y = random.randrange(0, 200)
    bod = canvas.create_oval(x+3, y+3, x-3, y-3, fill = "black")
    if (x - 100)**2+(y - 100)**2 < 80**2:       #for dot in circle1 fill red
        canvas.itemconfig(bod, fill = "red")
    if (x - 180)**2+(y - 100)**2 < 90**2:       #for dot in circle2 fill blue
        canvas.itemconfig(bod, fill = "blue")
    if (x - 100)**2+(y - 100)**2 < 80**2 and (x - 180)**2+(y - 100)**2 < 90**2:
        canvas.itemconfig(bod, fill = "green")  #overlapping of circle1 and 2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM