定義
先由下往上畫出樹幹,如果深度為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)
沒有留言:
張貼留言