---
# System prepended metadata

title: pen

---

# pen
```
# ch31_13.py #python
import turtle, random

def is_inside():
    ''' 測試是否在繪布範圍 '''
    w, h = t.screen.window_width(), t.screen.window_height()
    x, y = t.pos()    # 海龜座標
    return (-w/2+100 < x < w/2-100) and (-h/2+100 < y < h/2-100)

def turtle_move():
    colors = ['blue', 'pink', 'green', 'red', 'yellow', 'aqua']
    t.color(random.choice(colors))              # 繪圖顏色
    t.begin_fill()
    if is_inside():                             # 如果在繪布範圍
        t.right(random.randint(0, 180))         # 海龜移動角度
        t.forward(length)
    else:
        t.backward(length)
    t.end_fill()
    
t = turtle.Pen()
t.speed(0)
length = 100                                    # 線長
width = 10                                      # 線寬
t.pensize(width)                                # 設定畫筆寬
t.screen.bgcolor('black')                       # 畫布背景
while True: turtle_move()
```
![](https://i.imgur.com/ot68ggT.jpg)