# NumPy 與海龜繪圖（一）

Python 內建的 `turtle` 模組，提供了海龜繪圖的實作，例如，以下這個簡單的程式，可以畫出星狀圖：

``````from turtle import *

leng = 200
a = 170
n = 37

speed(0)
for _ in range(n):
forward(leng) # 前進
left(a)       # 轉向（角度）

done() # 繪圖完成（不關閉視窗）
``````

``````from turtle import *
import matplotlib.pyplot as plt

leng = 200
a = 170
n = 37

speed(0)
coords = []
for _ in range(n):
coords.append(pos())
forward(leng)
left(a)

x = [coord[0] for coord in coords]
y = [coord[1] for coord in coords]

plt.gca().set_aspect(1)
plt.plot(x, y)
plt.show()
``````

``````step = np.arange(n)
``````

``````def forward_left(_, leng, a):
forward(leng)
left(a)
return np.array(pos())
forward_left = np.frompyfunc(forward_left, 3, 1)

coord = np.array(forward_left(step, leng, a).tolist())

x = np_pos[:,0]
y = np_pos[:,1]
``````

`forward_left``step` 中的每個元素，將之轉換為 `pos` 取得的座標，最後得到的結果，重組為 NumPy 陣列，這是為了後續可以透過索引範圍取出 `x``y`，將以上片段組合起來：

``````from turtle import *
import numpy as np
import matplotlib.pyplot as plt

def forward_left(_, leng, a):
forward(leng)
left(a)
return np.array(pos())
forward_left = np.frompyfunc(forward_left, 3, 1)

leng = 200
a = 170
n = 37

speed(0)

step = np.arange(n)
coord = forward_left(step, leng, a)
np_pos = np.array(coord.tolist())

x = np_pos[:,0]
y = np_pos[:,1]

plt.gca().set_aspect(1)
plt.plot(x, y)
plt.show()
``````