MakeCode JS/Python、積木背後的程式碼
Blockly 最了不起的設計:每一塊積木都能生成文字程式碼。MakeCode 可以直接切換「積木 / JavaScript / Python」三種檢視。
| 積木 | JavaScript | Python(MicroPython) |
|---|---|---|
| on start | function onStart() {} | def on_start(): |
| show string "Hi" | basic.showString("Hi") | display.scroll("Hi") |
| forever | basic.forever(() => {}) | while True: |
| if 太暗 | if (light < 40) {} | if light_level() < 40: |
| 變數 score | let score = 0 | score = 0 |
| score += 1 | score += 1 | score += 1 |
要看懂「積木背後的程式碼」,先分辨積木的兩種類型——它們生成的程式碼型態完全不同:
| 積木類型 | 長相 | 對應程式概念 | 生成結果 |
|---|---|---|---|
| 值積木(Value) | 左側有圓形凸出(output) | 表達式 Expression | 值,如 5 + 2、score > 10 |
| 語句積木(Statement) | 上下有凹凸(previous/next) | 陳述句 Statement | 指令,如 score += 1;、if (…) {…} |
「+ 積木」(值積木)
└─> 生成:"a + b"(一個值,可被別處使用)
「如果積木」(語句積木)
└─> 生成:"if (a > b) {
...
}"(一段執行的指令)
功能:按 A 加一,按 B 重設
積木:
let score = 0
on button A pressed → change score by 1, show number score
on button B pressed → set score to 0
JavaScript:
let score = 0;
input.onButtonPressed(Button.A, () => {
score += 1;
basic.showNumber(score);
});
input.onButtonPressed(Button.B, () => {
score = 0;
});
觀察:積木 → JS 的對應一目了然。
「score += 1」是語句;「score > 10」是值。