# MicroPython亂數的應用

在micro:bit的程式應用中隨機亂數是非常有趣的一個函數，這原本是在Python中就有的函數，在microPython中也是一樣可以使用。先來看看以下這個例子：

```python
from microbit import *
import random 

while True:
    display.show(random.randint(0, 9))
    sleep(1000)
```

上面的這個程式會每隔一秒換一個數字，這個數字由random.randint()函數產生，每一次都不一樣。應用這個函數，我們可以設計一個猜數字的遊戲程式。先來看看如何讓使用者透過按鈕選擇一個數字的程式：

```python
from microbit import *
import random 

guess = 5
while True:
    if button_a.is_pressed() and button_b.is_pressed():
        break;
    if button_a.was_pressed():
        guess += 1
        if guess > 9: 
            guess = 9
    elif button_b.was_pressed():
        guess -= 1
        if guess < 0:
            guess = 0
    display.show(guess)
```

這個程式一開始的時候先讓變數guess設定為5，接下來在迴圈中偵測是否A和B按鈕同時被按下，如果是的話，就離開迴圈，這時候guess的內容就是我們要猜的數字。如果只是按下其中一個按鈕的話，就依照按鈕是哪一個來決定要把guess加1或是減1。同樣的，在加減數字的過程中，只要同時按下兩個按鈕之後就會離開迴圈，也就是確定了玩家要選擇的數字，而且是放在guess中。

為了增加趣味性，接下來利用一個迴圈來顯示100個不相關的數字，而且每顯示一個數字之後就增加暫停的時間：

```python
for i in range(100):
    display.show(random.randint(0, 9))
    sleep(20+i*2)
```

在顯示了這些數字之後，再取得正確的答案放在answer中，再作一些小小的閃爍動畫：

```python
answer = random.randint(0, 9)
for i in range(5):
    display.clear()
    sleep(500)
    display.show(answer)
    sleep(500)
```

最後則是比對玩家猜的數字guess和正確答案，再依相等與否顯示不同的圖案，完整的程式如下：

```python
from microbit import *
import random 

guess = 5
while True:
    if button_a.is_pressed() and button_b.is_pressed():
        break;
    if button_a.was_pressed():
        guess += 1
        if guess > 9: 
            guess = 9
    elif button_b.was_pressed():
        guess -= 1
        if guess < 0:
            guess = 0
    display.show(guess)
    
for i in range(100):
    display.show(random.randint(0, 9))
    sleep(20+i*2)
    
answer = random.randint(0, 9)
for i in range(5):
    display.clear()
    sleep(500)
    display.show(answer)
    sleep(500)
    
if answer == guess:
    display.show(Image.HEART)
else:
    display.show(Image.SAD)
```

如果想要再玩一次，只要按下重置按鈕就可以囉。


---

# 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/de-yong.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.
