Lernpfad:Einführung in den micro:bit/9: Unterschied zwischen den Versionen
Zur Navigation springen
Zur Suche springen
Ngb (Diskussion | Beiträge) Keine Bearbeitungszusammenfassung |
Ngb (Diskussion | Beiträge) Keine Bearbeitungszusammenfassung |
||
| Zeile 27: | Zeile 27: | ||
x = 0 | x = 0 | ||
y = 0 | y = 0 | ||
display.clear() | |||
display.set_pixel(x, y, 6) | display.set_pixel(x, y, 6) | ||
| Zeile 52: | Zeile 53: | ||
{{Aufgabe:End}} | {{Aufgabe:End}} | ||
{{Lösung:Start}} | {{Lösung:Start}} | ||
<syntaxhighlight lang="python" line="1"> | <syntaxhighlight lang="python" line="1" highlight="15-21,24-28,45,48-50"> | ||
from microbit import * | from microbit import * | ||
Version vom 7. Dezember 2023, 09:31 Uhr
Arbeitsauftrag
Übertrage das Programm unten in den Thonny und überspiele es auf den micro:bit.
Teste das Programm und erkläre seine Funktion. Notiere dir dazu Stichpunkte im Heft und ergänze neue Befehle in deiner Befehlsübersicht.
Tipp: Kippe den micro:bit doch mal leicht in eine Richtung.
from microbit import *
## Hilfsfunktion
def check_coords(x, y):
if x > 4:
x = 4
elif x < 0:
x = 0
if y > 4:
y = 4
elif y < 0:
y = 0
return (x, y)
## Initialisierung
sens = 350 # Mess-Sensitivität des Akzelerometer
x = 0
y = 0
display.clear()
display.set_pixel(x, y, 6)
## Endlosschleife
while True:
x1 = x + int(accelerometer.get_x()/sens)
y1 = y + int(accelerometer.get_y()/sens)
x1, y1 = check_coords(x1, y1)
if x1 != x or y1 != y:
display.set_pixel(x, y, 0)
display.set_pixel(x1, y1, 6)
x, y = x1, y1
sleep(200)
Arbeitsauftrag
Erweitere das Programm nun zu einem kleinen Spiel. Das Ziel soll es sein, alle LEDs des Displays einzuschalten. Nimm dazu folgende Änderungen vor:
- Anstatt die alte LED auszuschalten, setze ihren Wert auf
3. - Implementiere eine Methode
check_display()die prüft, ob alle LEDs an sind und in diesem FallTrueliefert, ansontenFalse. - Nutze
check_display(), um vor jedemsleep()das Display zu prüfen. - Falls das Display komplett an ist, schalte alle LEDs auf
6und breche die Endlosschleife ab.
Lösung
from microbit import *
## Hilfsfunktion
def check_coords(x, y):
if x > 4:
x = 4
elif x < 0:
x = 0
if y > 4:
y = 4
elif y < 0:
y = 0
return (x, y)
## Hilfsfunktion, um das Display zu prüfen
def check_display():
for y in range(5):
for x in range(5):
if display.get_pixel(x, y) == 0:
return False
return True
## Hilfsfunktion, um das Display einzuschalten
def on(value=6):
for y in range(5):
for x in range(5):
display.set_pixel(x, y, value)
## Initialisierung
sens = 350 # Mess-Sensitivität des Akzelerometer
x = 0
y = 0
display.clear()
display.set_pixel(x, y, 6)
## Endlosschleife
while True:
x1 = x + int(accelerometer.get_x()/sens)
y1 = y + int(accelerometer.get_y()/sens)
x1, y1 = check_coords(x1, y1)
if x1 != x or y1 != y:
display.set_pixel(x, y, 3)
display.set_pixel(x1, y1, 6)
x, y = x1, y1
if check_display():
on()
break
sleep(200)