# MicroPython程式簡易入門

接下來我們所有的程式都會在Mu Editor中編輯，並寫入micro:bit中測試顯示的結果。

{% hint style="info" %}
同學們如果對於Python不太熟練的話，請前往老師的[Python入門教](https://nkust.gitbook.io/python/)中先練習一下喔。
{% endhint %}

## 變換不同的表情

```python
from microbit import *

while True:
    display.show(Image.HAPPY)
    sleep(500)
    display.show(Image.SAD)
    sleep(500)
```

第1行的目的是要匯入所有驅動micro:bit所需要的函數（例如display），第3行的目的是讓接下來的程式可以永久執行。

在 永久執行的迴圈中，第4行顯示一個笑臉，第5行暫停0.5秒，第6行顯示悲傷的臉，第7行再次暫停0.5秒。

這個程式在寫入micro:bit之後，就會不斷地在兩個不同的表情之間進行變換，每0.5秒變化一次喔。

{% hint style="info" %}
所有可以使用的預設圖像畫面，可以在[說明文件](https://microbit-micropython.readthedocs.io/en/v1.0.1/tutorials/images.html)中找到喔。
{% endhint %}

## 以串列和迴圈的技巧來變換表情

如 果我們有許多的圖像需要依序呈現（例如要製作動畫的時候），那麼就需要使用一個串列放置所有要依序顯示的圖像，最後再利用一個迴圈來依序顯示串列資料中的內容，如下所示：

```python
from microbit import *

images = [Image.ARROW_E, Image.ARROW_S, Image.ARROW_W, Image.ARROW_N]
while True:
    for img in images:
        display.show(img)
        sleep(500)
```

若是要加入更多的圖像，可以在images變數之後加上更多的圖像，加入的方法就如底下的程式中的第4行，以+=運算子把另一個串列加到原有的串列中即可。

```python
from microbit import *

images = [Image.ARROW_E, Image.ARROW_SE, Image.ARROW_S, Image.ARROW_SW]
images += [Image.ARROW_W, Image.ARROW_NW, Image.ARROW_N, Image.ARROW_NE]
while True:
    for img in images:
        display.show(img)
        sleep(300)
```

## 預設的圖案串列ALL\_ARROWS以及ALL\_CLOCKS

不過，其實有一個預設的串列ALL\_ARROWS用來放置所有的箭頭符號，也就是它的內容就是上面這個程式中的images後來的內容，利用這個串列，同樣的箭頭動畫程式可以簡化成如下所示的樣子：

```python
from microbit import *

while True:
    for arrow in Image.ALL_ARROWS:
        display.show(arrow)
        sleep(200)
```

不過，對於放在同一個串列中的圖案而言，display函數身就支援動畫顯示的功能，上述的程式其實可以用一行指令就可以完成了：

```python
from microbit import * 

display.show(Image.ALL_ARROWS, loop=True, delay=300)
```

除了箭頭的符號之外，所有的指針符號也有，它是ALL\_CLOCKS，修改後的程式如下：

```python
rom microbit import *

while True:
    for arrow in Image.ALL_CLOCKS:
        display.show(arrow)
        sleep(5000)
```

在這個例子中我們把切換的時間設定為5秒，如此指針轉動一圈之後剛好就是1分鐘。同樣的，上述的程式功能也可以利用一行來完成：

```python
from microbit import * 

display.show(Image.ALL_CLOCKS, loop=True, delay=5000)
```

## 自訂圖案及動畫

除了使用原有的圖案之外，我們也可以在micro:bit中建立自己的圖案，並透過這些圖案建立一些自訂動畫。建立圖案的類別是Image，方法如下：

```
from microbit import * 

airplane = Image('00900:00900:09990:90909:00900')
display.show(airplane)
```

在程式第3行的地方，使用Image類別的初始化功能，傳入如上所示之格式的字串，就可以建立自訂圖案，得到的airplane這個變數即可利用display.show()顯示出來。還記得micro:bit共有25顆LED嗎？上述的每一個數字分別代表該位置的LED的亮度，9是最亮，0就是關閉。不過，上面的寫法並不容易看得出來圖案的樣式，因此大部份的情形下我們把它寫成以下的樣子：

```python
from microbit import * 

airplane = Image(
    '00900:'
    '00900:'
    '09990:'
    '90909:'
    '00900')
display.show(airplane)
```

請留意，以上的寫法只是把一個原本放在同一行的字串分成不同行來顯示，在第4行到第7行後面都沒有逗號喔。

有了以上自訂圖案的功能之後，我們就可以把自訂的動畫的每一格圖案都設計好交由程式幫我們展示出來，同學們可以執行下面這個例子，執行看看會看到什麼動畫喔。

```python
from microbit import * 

airplane = list()
airplane.append(Image(
    '00000:'
    '00000:'
    '00000:'
    '00000:'
    '00900'))
airplane.append(Image(
    '00000:'
    '00000:'
    '00000:'
    '00900:'
    '00900'))
airplane.append(Image(
    '00000:'
    '00000:'
    '00900:'
    '00900:'
    '09990'))
airplane.append(Image(
    '00000:'
    '00900:'
    '00900:'
    '09990:'
    '90909'))
airplane.append(Image(
    '00900:'
    '00900:'
    '09990:'
    '90909:'
    '00900'))
airplane.append(Image(
    '00900:'
    '09990:'
    '90909:'
    '00900:'
    '00000:')) 
airplane.append(Image(
    '09990:'
    '90909:'
    '00900:'
    '00000:'
    '00000:')) 
airplane.append(Image(
    '90909:'
    '00900:'
    '00000:'
    '00000:'
    '00000:'))
airplane.append(Image(
    '00900:'
    '00000:'
    '00000:'
    '00000:'
    '00000:'))
airplane.append(Image(
    '00000:'
    '00000:'
    '00000:'
    '00000:'
    '00000:'))

display.show(airplane, delay=100, loop=True)
```

## 活用invert()函數

Image的iinvert()函數可以讓目前的圖案內容進行反相顯示，如果我們想要讓某一個圖案反相顯示，只要針對該圖案使用invert函數就可以，請看以下的程式例：

```python
from microbit import *

image = Image.HAPPY
while True:
    display.show(image)
    sleep(200)
    display.show(image.invert())
    sleep(200)
```

上述的程式可以讓笑臉的圖案以0.2秒為間隔持續不斷地閃爍。透過一個迴圈，我們也可以製作出由暗而亮的LED圖案，讓利用循環動畫來播放，程式如下：

```python
from microbit import *

images = [Image().invert()*(i/9) for i in range(10)]
while True:
    display.show(images, delay=50, loop=False)
    display.show(reversed(images), delay=50, loop=False)
```

執行上面的程式，同學們可以看到micro:bit的25顆LED同時由暗到亮 ，再由亮變化到暗的動態效果。

## 使用Image函數製作平移動畫

在上面的程式中定義了幾個不同的圖案依序輪流顯示以建立動畫，但是，有些情形的動畫是屬於移動圖案型的，例如把一個物件往上下左右四個方向的其中一個方向來移動的這種動畫，還可以利用Image所提供的方法函數來完成。在REPL環境中，如果以dir(Image)來查詢Image中所有支援的函數，可以看到如下所示的顯示內容：

```
['width', 'height', 'get_pixel', 'set_pixel', 'shift_left', 'shift_right', 'shift_up', 
'shift_down', 'copy', 'crop', 'invert', 'fill', 'blit', 
'HEART', 'HEART_SMALL', 'HAPPY', 'SMILE', 'SAD', 'CONFUSED', 
'ANGRY', 'ASLEEP', 'SURPRISED', 'SILLY', 'FABULOUS', 'MEH', 
'YES', 'NO', 'CLOCK12', 'CLOCK1', 'CLOCK2', 'CLOCK3', 'CLOCK4', 
'CLOCK5', 'CLOCK6', 'CLOCK7', 'CLOCK8', 'CLOCK9', 'CLOCK10', 'CLOCK11', 
'ARROW_N', 'ARROW_NE', 'ARROW_E', 'ARROW_SE', 'ARROW_S', 'ARROW_SW', 
'ARROW_W', 'ARROW_NW', 'TRIANGLE', 'TRIANGLE_LEFT', 'CHESSBOARD', 
'DIAMOND', 'DIAMOND_SMALL', 'SQUARE', 'SQUARE_SMALL', 'RABBIT', 'COW', 
'MUSIC_CROTCHET', 'MUSIC_QUAVER', 'MUSIC_QUAVERS', 'PITCHFORK', 'XMAS',
'PACMAN', 'TARGET', 'ALL_CLOCKS', 'ALL_ARROWS', 'TSHIRT', 'ROLLERSKATE', 
'DUCK', 'HOUSE', 'TORTOISE', 'BUTTERFLY', 'STICKFIGURE', 'GHOST', 'SWORD', 
'GIRAFFE', 'SKULL', 'UMBRELLA', 'SNAKE']
```

在這些內容中，所有大寫的項目都是預設的圖案名稱，而小寫的部份就是支援的函數。其中，shift\_right、shift\_up等四個函數分別就是針對Image的內容做四個方向平移的操作，透過這幾個函數的應用，就可以輕易地製作平移式的動畫效果，請看以下這個程式例子：

```python
from microbit import *
import random
             
while True:
    track = Image(
                  '00000:'
                  '00000:'
                  '00000:'
                  '00000:'
                  '00900:'
                  '00900:'
                  '09990:'
                  '90909:'
                  '00900:'
                  '09990:'
                  '00000')
    for i in range(11):
        display.show(track.shift_up(i))
        sleep(150)
```

同樣都是一架飛機向上飛過的動畫，這個程式看起來是否比較簡單一些呢？

## 顯示捲動文字

雖然micro:bit只有一個5x5的點矩陣LED，但是顯示文字也難不倒它，只要使用display.scroll指令就可以了。以下是顯示文字的簡易程式：

```python
from microbit import *

display.scroll('Hello')
```

由於它只有一行指令沒有任何的迴圈，因此這個Hello文字訊息只會捲動一次，接著就沒有任何畫面了，如果想要再看一次訊息，可以按下micro:bit背面的重置按鈕（在USB連接器旁邊）。

也可以使用以下的迴圈指令讓這些訊息一直不斷地捲動播放：

```python
from microbit import *

while True:
    display.scroll('Hello!')
    display.scroll('Richard')
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://nkust.gitbook.io/micro-bit/micropython-cheng-shi-yi-ru.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
