置頂

我的 VPython 教學文件 (HackMD 版本)

VPython 教學文件目錄 安裝及測試 基本語法 等速度直線運動 自由落下 終端速度 水平抛射 使用For迴圈計算水平抛射資料 斜向抛射 圓周運動 簡諧運動 單擺 木塊彈簧系統分離 重力及簡諧 行星運動 相疊木塊 雙重簡諧運動 一維彈性碰撞 ...

熱門文章

2024年5月26日 星期日

遞迴樹 Recursive Tree

定義



先由下往上畫出樹幹,如果深度為0時只有樹幹;如果深度加1,在樹幹頂端增加2根互相垂直的分枝,分枝的長度比樹幹短,以下的程式中設定為0.6倍。我原來是用 tkinter 寫的,但它的畫面原點在左上角,向右為 +x 軸、向下為 +y 軸,跟我平常慣用的座標不太一樣。今天晚上再改用 VPython 重寫,並發布在 GlowScript 網站上,網頁版連結在此



程式碼



from vpython import *

"""
 1. 參數設定, 設定變數及初始值
"""
ratio = 0.6       # 長度比例
D = 300           # 畫面長、寬的一半
dep = 0           # 遞迴樹深度

"""
 2. 畫面及函式設定
"""
# 初始畫面設定
scene = canvas(title="<b>遞迴樹 Recursive Tree</b>\n\n", width=2*D, height=2*D, x=0, y=0, center=vec(0, D, 0), background=color.black)

# 畫線
def drawLine(p1, p2):
    curve(pos=[p1, p2], color=color.yellow, radius=1)

# 畫遞迴樹,輸入深度、根、角度預設為90度、長度預設為200
def rtree(depth, root, theta=90, L=200):
    top = vec(root.x - L*cos(radians(theta)), root.y + L*sin(radians(theta)), 0)
    drawLine(root, top)
    if depth == 0: return
    else:
        rtree(depth-1, top, theta-45, ratio*L)
        rtree(depth-1, top, theta+45, ratio*L)

# 先畫一次預設值
rtree(dep, vec(0, 0, 0))  

# 設定遞迴樹深度的選單
text1 = wtext(text="請輸入遞迴樹深度:", pos=scene.title_anchor)
def setDepth(evt):
    global dep, scene
    if evt.index == 0: dep = 0
    elif evt.index == 1: dep = 1
    elif evt.index == 2: dep = 2
    elif evt.index == 3: dep = 3
    elif evt.index == 4: dep = 4
    elif evt.index == 5: dep = 5
    elif evt.index == 6: dep = 6
    elif evt.index == 7: dep = 7
    elif evt.index == 8: dep = 8
    elif evt.index == 9: dep = 9
    elif evt.index == 10: dep = 10
    scene.delete()
    scene = canvas(width=2*D, height=2*D, x=0, y=0, center=vec(0, D, 0), background=color.black)
    rtree(dep, vec(0, 0, 0))

evt = menu(choices=["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"],
           pos=scene.title_anchor, index=0, bind=setDepth)

沒有留言:

張貼留言