# NumPy 與海龜繪圖（二）

``````def rotate(vt, angle):
c, s = np.cos(theta), np.sin(theta)
rm = np.array([
[c, -s],
[s, c]
])
return rm @ vt # @ 是矩陣相乘
``````

``````class Turtle:
def __init__(self, x = 0, y = 0, angle = 0):
self.coordinateVt = np.array([x, y])

def forward(self, leng):
self.coordinateVt = self.coordinateVt + self.headingVt * leng

def turn(self, angle):
``````

``````import numpy as np
import matplotlib.pyplot as plt

class Turtle:
def __init__(self, x = 0, y = 0, angle = 0):
self.coordinateVt = np.array([x, y])

def forward(self, leng):
self.coordinateVt =  self.coordinateVt + self.headingVt * leng

def turn(self, angle):

def rotate(vt, angle):
c, s = np.cos(theta), np.sin(theta)
rm = np.array([
[c, -s],
[s, c]
])
return rm @ vt

def forward_left(_, t, leng, a):
t.forward(leng)
t.turn(a)
return t.coordinateVt
forward_left = np.frompyfunc(forward_left, 4, 1)

leng = 200
a = 170
n = 37

step = np.arange(n)
coord = forward_left(step, Turtle(), 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()
``````

``````self.coordinateVt =  self.coordinateVt + self.headingVt * leng
``````

``````step = np.arange(n)
angle = step * a

dx = leng * np.cos(angle)
dy = leng * np.sin(angle)
``````

``````x = np.cumsum(dx) # cumsum 可以計算累計加總
y = np.cumsum(dy)
``````

`x``y` 餵給 `plot` 不就好了？也就是說，以下的程式就可以畫出星狀圖了：

``````import numpy as np
import matplotlib.pyplot as plt

leng = 200
n = 37

step = np.arange(n)
angle = step * a

dx = leng * np.cos(angle)
dy = leng * np.sin(angle)

x = np.cumsum(dx)
y = np.cumsum(dy)

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