This commit is contained in:
Galen Nickel 2024-08-15 15:47:18 -07:00 коммит произвёл GitHub
Родитель 93966da92f
Коммит 8b3df11d93
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: B5690EEEBB952194
49 изменённых файлов: 501 добавлений и 504 удалений

Просмотреть файл

@ -5,7 +5,7 @@ Press ``A`` to scroll the value on the screen.
```blocks
let reading = 0
basic.forever(() => {
basic.forever(function () {
reading = pins.analogReadPin(AnalogPin.P0)
led.plotBarGraph(
reading,

Просмотреть файл

@ -7,14 +7,14 @@ Have you ever tried making beat box sounds? Let's try making a beatbox with code
Start by adding a variable to store a musical note. Rename the variable to `sound`. Set the value of the variable to the note block `Middle A` from the **Music** drawer.
```blocks
let sound = music.noteFrequency(Note.A);
let sound = music.noteFrequency(Note.A)
```
We want to play music when the fruit connected to a pin pressed. So, we register an event handler that executes whenever pin **1** is pressed. Pin **1** is, of course, connected to the banana. Add a ``||input:on pin pressed||`` block from the **Input** drawer.
```blocks
let sound = music.noteFrequency(Note.A);
input.onPinPressed(TouchPin.P1, () => {
let sound = music.noteFrequency(Note.A)
input.onPinPressed(TouchPin.P1, function () {
})
```
@ -22,28 +22,28 @@ input.onPinPressed(TouchPin.P1, () => {
Now, let's create some notes to play when the banana is pressed. Click on the **Loops** drawer then insert a ``||loops:repeat||`` loop into the ``||input:on pin pressed||`` block. Click on the **Variables** drawer and pull out a ``||variables:change item by||`` block and put it into the loop. Rename the variable to `sound`. Change the value from `1` to `25`. This will increase the variable `sound` from the note frequency of block `Middle A` to `Middle A` plus 25 and so on. Put a ``||variables:set to||`` block for `sound` right after the loop. Set it to `Middle A` in order to reset the sound after a banana press.
```blocks
let sound = music.noteFrequency(Note.A);
let sound = music.noteFrequency(Note.A)
input.onPinPressed(TouchPin.P1, () => {
input.onPinPressed(TouchPin.P1, function () {
for (let i = 0; i < 4; i++) {
sound += 25;
sound += 25
}
sound = music.noteFrequency(Note.A);
});
sound = music.noteFrequency(Note.A)
})
```
Finally, insert a ``||music:play tone||`` above the ``||variables:change by||``. Pull out the ``sound`` variable block and drop it in the note slot of ``||music:play tone||``. Change the beat fraction from `1` to `1/4`.
```blocks
let sound = music.noteFrequency(Note.A);
let sound = music.noteFrequency(Note.A)
input.onPinPressed(TouchPin.P1, () => {
input.onPinPressed(TouchPin.P1, function () {
for (let i = 0; i < 4; i++) {
music.playTone(sound, music.beat(BeatFraction.Quarter));
sound += 25;
music.playTone(sound, music.beat(BeatFraction.Quarter))
sound += 25
}
sound = music.noteFrequency(Note.A);
});
sound = music.noteFrequency(Note.A)
})
```
Click `|Download|` and try a banana press. Did you hear 4 notes play?
@ -55,23 +55,23 @@ Go back to **[Make](/projects/banana-keyboard/make)** and repeat steps 7 and 8 w
Duplicate the ``||input:on pin pressed||`` event handler to make a second one. For the new ``||input:on pin pressed||``, change the pin name to **P2**. In the pin **P2** event, let's have the the frequency in the variable `sound` decrease by 25 instead of having it increase. Change the `25` in the ``||variables:change by||`` block to `-25`. OK, your code now looks like this:
```blocks
let sound = music.noteFrequency(Note.A);
let sound = music.noteFrequency(Note.A)
input.onPinPressed(TouchPin.P1, () => {
input.onPinPressed(TouchPin.P1, function () {
for (let i = 0; i < 4; i++) {
music.playTone(sound, music.beat(BeatFraction.Quarter));
sound += 25;
music.playTone(sound, music.beat(BeatFraction.Quarter))
sound += 25
}
sound = music.noteFrequency(Note.A);
});
sound = music.noteFrequency(Note.A)
})
input.onPinPressed(TouchPin.P2, () => {
input.onPinPressed(TouchPin.P2, function () {
for (let i = 0; i < 4; i++) {
music.playTone(sound, music.beat(BeatFraction.Quarter));
sound += -25;
music.playTone(sound, music.beat(BeatFraction.Quarter))
sound += -25
}
sound = music.noteFrequency(Note.A);
});
sound = music.noteFrequency(Note.A)
})
```
Click `|Download|` again and play both bananas. It's a fruit jam session!

Просмотреть файл

@ -73,7 +73,7 @@ Your banana keyboard is ready!
Connect your @boardname@ to your computer using your USB cable and run this script:
```blocks
input.onPinPressed(TouchPin.P1, () => {
input.onPinPressed(TouchPin.P1, function () {
music.playTone(music.noteFrequency(Note.C), music.beat(BeatFraction.Quarter));
});
```

Просмотреть файл

@ -25,10 +25,10 @@ Before creating the code for the game actions, let's first add some controls so
```blocks
let bird: game.LedSprite = null
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
bird.change(LedSpriteProperty.Y, -1)
})
input.onButtonPressed(Button.B, () => {
input.onButtonPressed(Button.B, function () {
bird.change(LedSpriteProperty.Y, 1)
})
```
@ -79,11 +79,11 @@ for (let index = 0; index <= 4; index++) {
}
}
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
bird.change(LedSpriteProperty.Y, -1)
})
input.onButtonPressed(Button.B, () => {
input.onButtonPressed(Button.B, function () {
bird.change(LedSpriteProperty.Y, 1)
})
```
@ -97,7 +97,7 @@ Right click on the ``||value||`` block and rename it to ``||obstacle||``
```blocks
let obstacles: game.LedSprite[] = []
basic.forever(() => {
basic.forever(function () {
for (let obstacle of obstacles) {
obstacle.change(LedSpriteProperty.X, -1)
}
@ -114,7 +114,7 @@ Make obstacles disappear after reaching leftmost corner. Iterate over all obstac
```blocks
let obstacles: game.LedSprite[] = []
basic.forever(() => {
basic.forever(function () {
while (obstacles.length > 0 && obstacles[0].get(LedSpriteProperty.X) == 0) {
obstacles.removeAt(0).delete()
}
@ -134,7 +134,7 @@ At the moment, our code generates just one vertical obstacle. We need to put obs
let emptyObstacleY = 0
let obstacles: game.LedSprite[] = []
basic.forever(() => {
basic.forever(function () {
while (obstacles.length > 0 && obstacles[0].get(LedSpriteProperty.X) == 0) {
obstacles.removeAt(0).delete()
}
@ -159,7 +159,7 @@ let ticks = 0
let emptyObstacleY = 0
let obstacles: game.LedSprite[] = []
basic.forever(() => {
basic.forever(function () {
while (obstacles.length > 0 && obstacles[0].get(LedSpriteProperty.X) == 0) {
obstacles.removeAt(0).delete()
}
@ -190,7 +190,7 @@ let ticks = 0
let emptyObstacleY = 0
let obstacles: game.LedSprite[] = []
basic.forever(() => {
basic.forever(function () {
while (obstacles.length > 0 && obstacles[0].get(LedSpriteProperty.X) == 0) {
obstacles.removeAt(0).delete()
}
@ -226,17 +226,17 @@ let emptyObstacleY = 0
let obstacles: game.LedSprite[] = []
let index = 0
let bird: game.LedSprite = null
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
bird.change(LedSpriteProperty.Y, -1)
})
input.onButtonPressed(Button.B, () => {
input.onButtonPressed(Button.B, function () {
bird.change(LedSpriteProperty.Y, 1)
})
index = 0
obstacles = []
bird = game.createSprite(0, 2)
bird.set(LedSpriteProperty.Blink, 300)
basic.forever(() => {
basic.forever(function () {
while (obstacles.length > 0 && obstacles[0].get(LedSpriteProperty.X) == 0) {
obstacles.removeAt(0).delete()
}

Просмотреть файл

@ -34,7 +34,7 @@ When the clock reaches "noon" (let's pick `8` as noon), we turn on the screen br
```block
// the clock ticker
let clock = 0
basic.forever(() => {
basic.forever(function () {
// if clock "hits noon", flash the screen
if (clock >= 8) {
// flash
@ -61,7 +61,7 @@ When a firefly flashes, it also sends a number over radio using ``||radio:radio
```block
// the clock ticker
let clock = 0
basic.forever(() => {
basic.forever(function () {
// if clock "hits noon", flash the screen
if (clock >= 8) {
// notify neighbors
@ -111,7 +111,7 @@ radio.onReceivedNumber(function (receivedNumber) {
// advance clock to catch up neighbors
clock += 1
})
basic.forever(() => {
basic.forever(function () {
// if clock hits noon, flash the screen
if (clock >= 8) {
// notify neighbors

Просмотреть файл

@ -53,7 +53,7 @@ acceleration of gravity.
## Step 1: Graphing acceleration
```blocks
basic.forever(() => {
basic.forever(function () {
led.plotBarGraph(input.acceleration(Dimension.Y), 1023)
})
```
@ -76,11 +76,11 @@ Try graphing the acceleration along the **X** and **Z** axis. Can you explain th
## Step 2: Mapping acceleration to Beat
**@boardname@ sensors produce signal values between 0 to 1023. The *[map block](/reference/pins/map)* converts the signal to a desired range.**
```blocks
basic.forever(() => {
basic.forever(function () {
music.setTempo(pins.map(Math.abs(input.acceleration(Dimension.Y)),
0, 1023,
60, 320))
music.playTone(Note.C, music.beat(BeatFraction.Quarter));
music.playTone(Note.C, music.beat(BeatFraction.Quarter))
})
```
@ -94,14 +94,14 @@ basic.forever(() => {
**Put it all together!**
```blocks
basic.forever(() => {
basic.forever(function () {
music.setTempo(pins.map(Math.abs(input.acceleration(Dimension.Y)),
0, 1023,
60, 320))
music.playTone(
input.lightLevel() * 25,
music.beat(BeatFraction.Quarter)
);
)
})
```
**Combine the code above with the light sensor tone control code from the previous activity**

Просмотреть файл

@ -37,7 +37,7 @@ Headphones
. # . # .
. # # # .
`);
input.onButtonPressed(Button.A, () => {});
input.onButtonPressed(Button.A, function () {})
music.playTone(Note.C, music.beat(BeatFraction.Quarter))
music.rest(music.beat(BeatFraction.Whole))
music.beat(BeatFraction.Quarter)
@ -52,7 +52,7 @@ Open @homeurl@ in your web browser
. # # # .
. # . # .
. # # # .
`);
`)
```
From **Basics**, drag a **show LEDs** block into the coding area
* Create a face with LEDs
@ -63,7 +63,7 @@ Follow the instructions to move the code to your @boardname@.
## Step 2: Add Smiley LED Button Events
```blocks
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
basic.showLeds(`
. # . # .
. . . . .
@ -72,7 +72,7 @@ input.onButtonPressed(Button.A, () => {
. # # # .
`)
})
input.onButtonPressed(Button.B, () => {
input.onButtonPressed(Button.B, function () {
basic.showLeds(`
. # . # .
. . . . .
@ -115,7 +115,7 @@ Connect the headphones with crocodile clips
The **play tone** block allows a range letter note tones from **C** to **B5**.
Songs are played using sequences notes. Like the beginning of a birthday song (C, C, D, C, F, E).
```blocks
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
music.playTone(Note.C, music.beat(BeatFraction.Quarter))
music.rest(music.beat(BeatFraction.Whole))
music.playTone(Note.C, music.beat(BeatFraction.Quarter))
@ -133,7 +133,7 @@ input.onButtonPressed(Button.A, () => {
## ~
## Step 4: Add Tone Playing Events for Buttons A & B
```blocks
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
basic.showLeds(`
. # . # .
. . . . .
@ -143,7 +143,7 @@ input.onButtonPressed(Button.A, () => {
`)
music.playTone(Note.A, music.beat(BeatFraction.Whole))
})
input.onButtonPressed(Button.B, () => {
input.onButtonPressed(Button.B, function () {
basic.showLeds(`
. # . # .
. . . . .

Просмотреть файл

@ -33,7 +33,7 @@ The forever loop really does run forever. The forever loop is useful when there
## Blocks
```cards
basic.forever(() => {})
basic.forever(function () {})
input.lightLevel()
led.plotBarGraph(0, 255)
music.playTone(Note.C, music.beat(BeatFraction.Quarter))
@ -41,7 +41,7 @@ music.playTone(Note.C, music.beat(BeatFraction.Quarter))
## Step 1: Create a light level detector
```blocks
basic.forever(() => {
basic.forever(function () {
led.plotBarGraph(input.lightLevel(), 255)
})
```
@ -80,7 +80,7 @@ music.playTone(261, music.beat(BeatFraction.Half))
## Step 3: Multiply Frequency using Math blocks
```blocks
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
music.playTone(261 * 2, music.beat(BeatFraction.Half))
})
```
@ -95,7 +95,7 @@ Create a **play tone** block using a **Math** section, **multiplication** block
## Step 4: Control the Frequency with the light input
```blocks
basic.forever(() => {
basic.forever(function () {
music.playTone(input.lightLevel() * 25, music.beat(BeatFraction.Quarter))
})
```

Просмотреть файл

@ -22,9 +22,9 @@ Use pin press to switch guitar play on/off
```cards
let on = false
on;
on
if (on) { } else {}
input.onPinPressed(TouchPin.P1, () => {})
input.onPinPressed(TouchPin.P1, function () {})
```
@ -43,13 +43,13 @@ input.onPinPressed(TouchPin.P1, () => {})
## Step 1: Pin Press Test
```blocks
input.onPinPressed(TouchPin.P0, () => {
input.onPinPressed(TouchPin.P0, function () {
basic.showNumber(0)
})
input.onPinPressed(TouchPin.P1, () => {
input.onPinPressed(TouchPin.P1, function () {
basic.showNumber(1)
})
input.onPinPressed(TouchPin.P2, () => {
input.onPinPressed(TouchPin.P2, function () {
basic.showNumber(2)
})
```
@ -88,14 +88,14 @@ https://youtu.be/YkymZGNmkrE
**between ON and OFF**
```blocks
let on = false
basic.forever(() => {
basic.forever(function () {
if (on == true) {
basic.showString("ON")
} else {
basic.showString("OFF")
}
})
input.onPinPressed(TouchPin.P1, () => {
input.onPinPressed(TouchPin.P1, function () {
if (on == true) {
on = false
} else {
@ -110,10 +110,10 @@ input.onPinPressed(TouchPin.P1, () => {
**Test by touching `P1` to toggle the LED message between ON and OFF**
*Final code*
TODO: do we want to use `on = !on;` or be more direct in flipping the switch? `on = true; on = false;`
TODO: do we want to use `on = !on` or be more direct in flipping the switch? `on = true` or `on = false`
```blocks
let on = false
basic.forever(() => {
basic.forever(function () {
if (on) {
music.setTempo(pins.map(Math.abs(input.acceleration(Dimension.Y)),
0, 1023,
@ -121,13 +121,13 @@ basic.forever(() => {
music.playTone(
input.lightLevel() * 25,
music.beat(BeatFraction.Quarter)
);
)
} else {
music.rest(music.beat())
}
})
input.onPinPressed(TouchPin.P1, () => {
on = !on;
input.onPinPressed(TouchPin.P1, function () {
on = !on
})
```
## Now Play!

Просмотреть файл

@ -9,17 +9,17 @@ Have you ever tried to making beat box sounds based on the light level? Let's tr
Let's start by playing music when the **A** button is pressed. To do that, register an event handler that will execute whenever you click on the **A** button. Open the ``||input:Input||`` drawer and get out an ``||input:on button A pressed||`` block. Next, add a ``||music:rest||`` to play nothing for `1/16` of a beat.
```blocks
input.onButtonPressed(Button.A, () => {
music.rest(music.beat(BeatFraction.Sixteenth));
input.onButtonPressed(Button.A, function () {
music.rest(music.beat(BeatFraction.Sixteenth))
});
```
We also want to add a variable where you can store data. Name the variable ``light`` and ``||variables:set||`` the value of the variable to the ``||input:light level||`` block from the ``||input:Input||`` drawer. This will get the light level as some value between `0` (dark) and `255` (bright). The light is measured by using various LEDs from the screen. Your code will look like this:
```blocks
input.onButtonPressed(Button.A, () => {
music.rest(music.beat(BeatFraction.Sixteenth));
let light = input.lightLevel();
input.onButtonPressed(Button.A, function () {
music.rest(music.beat(BeatFraction.Sixteenth))
let light = input.lightLevel()
});
```
@ -29,14 +29,14 @@ Click on the ``||logic:Logic||`` drawer and find an ``||logic:if||`` block to us
* If this condition is not `true`, play ``||music:ring tone||`` for ``Middle A``
```blocks
input.onButtonPressed(Button.A, () => {
music.rest(music.beat(BeatFraction.Sixteenth));
let light = input.lightLevel();
input.onButtonPressed(Button.A, function () {
music.rest(music.beat(BeatFraction.Sixteenth))
let light = input.lightLevel()
if (light < 25) {
music.ringTone(music.noteFrequency(Note.C));
music.ringTone(music.noteFrequency(Note.C))
}
else {
music.ringTone(music.noteFrequency(Note.A));
music.ringTone(music.noteFrequency(Note.A))
}
});
```
@ -50,26 +50,26 @@ Now, we want to add more conditional statements by clicking on the **(+)** at th
* If these conditions are not true, play ``||music:ring tone||`` ``Middle A``
```blocks
input.onButtonPressed(Button.A, () => {
music.rest(music.beat(BeatFraction.Sixteenth));
let light = input.lightLevel();
input.onButtonPressed(Button.A, function () {
music.rest(music.beat(BeatFraction.Sixteenth))
let light = input.lightLevel()
if (light < 25) {
music.ringTone(music.noteFrequency(Note.C));
music.ringTone(music.noteFrequency(Note.C))
}
else if (light < 50) {
music.ringTone(music.noteFrequency(Note.D));
music.ringTone(music.noteFrequency(Note.D))
}
else if (light < 100) {
music.ringTone(music.noteFrequency(Note.E));
music.ringTone(music.noteFrequency(Note.E))
}
else if (light < 150) {
music.ringTone(music.noteFrequency(Note.F));
music.ringTone(music.noteFrequency(Note.F))
}
else if (light < 180) {
music.ringTone(music.noteFrequency(Note.G));
music.ringTone(music.noteFrequency(Note.G))
}
else {
music.ringTone(music.noteFrequency(Note.A));
music.ringTone(music.noteFrequency(Note.A))
}
});
```

Просмотреть файл

@ -32,7 +32,7 @@ radio.setTransmitPower(6)
The beacon just needs to send a radio message every now and then. So, to pace the transmits and give some visual feedback, we add some ``||basic:show icon||`` blocks to animate the screen.
```blocks
basic.forever(() => {
basic.forever(function () {
radio.sendNumber(0)
basic.showIcon(IconNames.Heart)
basic.showIcon(IconNames.SmallHeart)
@ -142,7 +142,7 @@ radio.onReceivedNumber(function (receivedNumber) {
To see the current score, we add an ``||input:on button pressed||`` that displays the score on the screen when the **A** button is pressed.
```block
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
basic.showNumber(game.score())
})
```
@ -172,7 +172,7 @@ radio.onReceivedNumber(function (receivedNumber) {
}
}
})
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
basic.showNumber(game.score())
})
radio.setGroup(1)

Просмотреть файл

@ -21,7 +21,7 @@ radio.setTransmitPower(6)
The beacon just needs to send a radio message every now and then. So, to pace the transmits and give some visual feedback, we add some ``||basic:show icon||`` blocks to animate the screen.
```blocks
basic.forever(() => {
basic.forever(function () {
radio.sendNumber(0)
basic.showIcon(IconNames.Heart)
basic.showIcon(IconNames.SmallHeart)

Просмотреть файл

@ -47,7 +47,7 @@ radio.onReceivedNumber(function (receivedNumber) {
To see the current score, we add an ``||input:on button pressed||`` that displays the score on the screen when the **A** button is pressed.
```block
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
basic.showNumber(game.score())
})
```
@ -77,7 +77,7 @@ radio.onReceivedNumber(function (receivedNumber) {
}
}
})
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
basic.showNumber(game.score())
})
radio.setGroup(1)

Просмотреть файл

@ -22,7 +22,7 @@ To determine how far away or how close they are, we use the signal strength of e
let signal = 0;
radio.onReceivedNumber(function (receivedNumber) {
signal = radio.receivedPacket(RadioPacketProperty.SignalStrength)
basic.showNumber(signal);
basic.showNumber(signal)
});
radio.setGroup(1)
```
@ -47,7 +47,7 @@ Here is an example that uses ``-95`` or less for cold, between ``-95`` and ``-80
### ~
```blocks
let signal = 0;
let signal = 0
radio.onReceivedNumber(function (receivedNumber) {
signal = radio.receivedPacket(RadioPacketProperty.SignalStrength)
if (signal < -90) {

Просмотреть файл

@ -15,11 +15,11 @@ Add code to make the inchworm move.
In order for the inchworm to move, the @boardname@ needs to command the servo to move between ``0`` and ``180`` degrees at a certain pace. The code below starts the inchworm moving when the **A** button is pressed.
```blocks
input.onButtonPressed(Button.A, () => {
pins.servoWritePin(AnalogPin.P0, 0);
basic.pause(500);
pins.servoWritePin(AnalogPin.P0, 180);
basic.pause(500);
input.onButtonPressed(Button.A, function () {
pins.servoWritePin(AnalogPin.P0, 0)
basic.pause(500)
pins.servoWritePin(AnalogPin.P0, 180)
basic.pause(500)
});
```

Просмотреть файл

@ -17,7 +17,7 @@ radio.onReceivedNumber(function (receivedNumber: number) {
pins.servoWritePin(AnalogPin.P0, 180)
basic.pause(500)
})
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
radio.sendNumber(0)
})
```

Просмотреть файл

@ -106,10 +106,10 @@ As a result, it will not convert back to blocks.
* Healthy: IconNames.Happy
*
*/
const INCUBATION = 20000; // time before showing symptoms
const DEATH = 40000; // time before dying off the disease
const RSSI = -45; // db
const TRANSMISSIONPROB = 40; // % probability to transfer disease
const INCUBATION = 20000 // time before showing symptoms
const DEATH = 40000 // time before dying off the disease
const RSSI = -45 // db
const TRANSMISSIONPROB = 40 // % probability to transfer disease
enum GameState {
Stopped,
@ -147,366 +147,366 @@ const GameIcons = {
class Message {
private _data: Buffer;
private _data: Buffer
constructor(input?: Buffer) {
this._data = input || control.createBuffer(13);
this._data = input || control.createBuffer(13)
}
get kind(): number {
return this._data.getNumber(NumberFormat.Int8LE, 0);
return this._data.getNumber(NumberFormat.Int8LE, 0)
}
set kind(x: number) {
this._data.setNumber(NumberFormat.Int8LE, 0, x);
this._data.setNumber(NumberFormat.Int8LE, 0, x)
}
get fromSerialNumber(): number {
return this._data.getNumber(NumberFormat.Int32LE, 1);
return this._data.getNumber(NumberFormat.Int32LE, 1)
}
set fromSerialNumber(x: number) {
this._data.setNumber(NumberFormat.Int32LE, 1, x);
this._data.setNumber(NumberFormat.Int32LE, 1, x)
}
get value(): number {
return this._data.getNumber(NumberFormat.Int32LE, 5);
return this._data.getNumber(NumberFormat.Int32LE, 5)
}
set value(x: number) {
this._data.setNumber(NumberFormat.Int32LE, 5, x);
this._data.setNumber(NumberFormat.Int32LE, 5, x)
}
get toSerialNumber(): number {
return this._data.getNumber(NumberFormat.Int32LE, 9);
return this._data.getNumber(NumberFormat.Int32LE, 9)
}
set toSerialNumber(x: number) {
this._data.setNumber(NumberFormat.Int32LE, 9, x);
this._data.setNumber(NumberFormat.Int32LE, 9, x)
}
send() {
radio.sendBuffer(this._data);
basic.pause(250);
radio.sendBuffer(this._data)
basic.pause(250)
}
}
const playerIcons = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const playerIcons = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
class Player {
id: number;
icon: number;
health: HealthState;
id: number
icon: number
health: HealthState
show() {
basic.showString(playerIcons[this.icon]);
basic.showString(playerIcons[this.icon])
}
}
// common state
let state = GameState.Stopped;
let state = GameState.Stopped
// master state
let master = false;
let patientZero: Player;
const players: Player[] = [];
let master = false
let patientZero: Player
const players: Player[] = []
// player state
let paired = false;
let infectedBy = -1; // who infected (playerIcon)
let infectedTime = 0; // local time when infection happened
let playerIcon = -1; // player icon and identity
let health = HealthState.Healthy;
let paired = false
let infectedBy = -1 // who infected (playerIcon)
let infectedTime = 0 // local time when infection happened
let playerIcon = -1 // player icon and identity
let health = HealthState.Healthy
// get a player instance (creates one as needed)
function player(id: number): Player {
for (const p of players)
if (p.id == id) return p;
if (p.id == id) return p
// add player to game
let p = new Player();
p.id = id;
p.icon = (players.length + 1) % playerIcons.length;
p.health = HealthState.Healthy;
players.push(p);
let p = new Player()
p.id = id
p.icon = (players.length + 1) % playerIcons.length
p.health = HealthState.Healthy
players.push(p)
serial.writeLine(`player ==> ${p.id}`)
return p;
return p
}
function allDead(): boolean {
for (const p of players)
if (p.health != HealthState.Dead) return false;
return true;
if (p.health != HealthState.Dead) return false
return true
}
function gameOver() {
state = GameState.Over;
state = GameState.Over
if (patientZero)
patientZero.show();
patientZero.show()
}
function gameFace() {
switch (state) {
case GameState.Stopped:
basic.showIcon(GameIcons.Pairing);
break;
basic.showIcon(GameIcons.Pairing)
break
case GameState.Pairing:
if (playerIcon > -1)
basic.showString(playerIcons[playerIcon]);
basic.showString(playerIcons[playerIcon])
else
basic.showIcon(paired ? GameIcons.Paired : GameIcons.Pairing, 1);
break;
basic.showIcon(paired ? GameIcons.Paired : GameIcons.Pairing, 1)
break
case GameState.Infecting:
case GameState.Running:
switch (health) {
case HealthState.Dead:
basic.showIcon(GameIcons.Dead, 1);
break;
basic.showIcon(GameIcons.Dead, 1)
break
case HealthState.Sick:
basic.showIcon(GameIcons.Sick, 1);
break;
basic.showIcon(GameIcons.Sick, 1)
break
default:
basic.showIcon(GameIcons.Healthy, 1);
break;
basic.showIcon(GameIcons.Healthy, 1)
break
}
break;
break
case GameState.Over:
// show id
basic.showString(playerIcons[playerIcon]);
basic.pause(2000);
basic.showString(playerIcons[playerIcon])
basic.pause(2000)
// show health
switch (health) {
case HealthState.Dead:
basic.showIcon(GameIcons.Dead, 2000);
break;
basic.showIcon(GameIcons.Dead, 2000)
break
case HealthState.Sick:
basic.showIcon(GameIcons.Sick, 2000);
break;
basic.showIcon(GameIcons.Sick, 2000)
break
case HealthState.Incubating:
basic.showIcon(GameIcons.Incubating, 2000);
break;
basic.showIcon(GameIcons.Incubating, 2000)
break
default:
basic.showIcon(GameIcons.Healthy, 2000);
break;
basic.showIcon(GameIcons.Healthy, 2000)
break
}
// show how infected
if (infectedBy > -1) {
basic.showString(" INFECTED BY");
basic.showString(playerIcons[infectedBy]);
basic.pause(2000);
basic.showString(" INFECTED BY")
basic.showString(playerIcons[infectedBy])
basic.pause(2000)
} else {
basic.showString(" PATIENT ZERO");
basic.pause(2000);
basic.showString(" PATIENT ZERO")
basic.pause(2000)
}
// show score
game.showScore();
basic.pause(1000);
break;
game.showScore()
basic.pause(1000)
break
}
}
// master button controller
input.onButtonPressed(Button.AB, () => {
input.onButtonPressed(Button.AB, function () {
// register as master
if (state == GameState.Stopped && !master) {
master = true;
paired = true;
state = GameState.Pairing;
serial.writeLine("registered as master");
radio.setTransmitPower(7); // beef up master signal
basic.showString("0");
return;
master = true
paired = true
state = GameState.Pairing
serial.writeLine("registered as master")
radio.setTransmitPower(7) // beef up master signal
basic.showString("0")
return
}
if (!master) return; // master only beyond this
if (!master) return // master only beyond this
// launch game
if (state == GameState.Pairing) {
// pick 1 player and infect him
patientZero = players[randint(0, players.length - 1)];
patientZero = players[randint(0, players.length - 1)]
// infecting message needs to be confirmed by
// the player
state = GameState.Infecting;
serial.writeLine(`game started ${players.length} players`);
state = GameState.Infecting
serial.writeLine(`game started ${players.length} players`)
} // end game
else if (state == GameState.Running) {
gameOver();
gameOver()
}
})
radio.setGroup(42);
radio.setGroup(42)
radio.onReceivedBuffer(function (receivedBuffer: Buffer) {
const incomingMessage = new Message(receivedBuffer);
const signal = radio.receivedPacket(RadioPacketProperty.SignalStrength);
const incomingMessage = new Message(receivedBuffer)
const signal = radio.receivedPacket(RadioPacketProperty.SignalStrength)
if (master) {
switch (incomingMessage.kind) {
case MessageKind.PairRequest:
// register player
let n = players.length;
player(incomingMessage.fromSerialNumber);
let n = players.length
player(incomingMessage.fromSerialNumber)
// show player number if changed
if (n != players.length) {
basic.showNumber(players.length);
basic.showNumber(players.length)
}
break;
break
case MessageKind.HealthValue:
let p = player(incomingMessage.fromSerialNumber);
p.health = incomingMessage.value;
let p = player(incomingMessage.fromSerialNumber)
p.health = incomingMessage.value
// check if all infected
if (allDead())
gameOver();
break;
gameOver()
break
}
} else {
switch (incomingMessage.kind) {
case MessageKind.GameState:
// update game state
state = incomingMessage.value as GameState;
break;
state = incomingMessage.value as GameState
break
case MessageKind.InitialInfect:
if (infectedBy < 0 &&
incomingMessage.toSerialNumber == control.deviceSerialNumber()) {
// infected by master
infectedBy = 0; // infected my master
infectedTime = input.runningTime();
health = HealthState.Incubating;
serial.writeLine(`infected ${control.deviceSerialNumber()}`);
infectedBy = 0 // infected my master
infectedTime = input.runningTime()
health = HealthState.Incubating
serial.writeLine(`infected ${control.deviceSerialNumber()}`)
}
break;
break
case MessageKind.HealthSet:
if (incomingMessage.toSerialNumber == control.deviceSerialNumber()) {
const newHealth = incomingMessage.value;
const newHealth = incomingMessage.value
if (health < newHealth) {
health = newHealth;
health = newHealth
}
}
break;
break
case MessageKind.PairConfirmation:
if (!paired && state == GameState.Pairing &&
incomingMessage.toSerialNumber == control.deviceSerialNumber()) {
// paired!
serial.writeLine(`player paired ==> ${control.deviceSerialNumber()}`)
playerIcon = incomingMessage.value;
paired = true;
playerIcon = incomingMessage.value
paired = true
}
break;
break
case MessageKind.TransmitVirus:
if (state == GameState.Running) {
if (health == HealthState.Healthy) {
serial.writeLine(`signal: ${signal}`);
serial.writeLine(`signal: ${signal}`)
if (signal > RSSI &&
randint(0, 100) > TRANSMISSIONPROB) {
infectedBy = incomingMessage.value;
infectedTime = input.runningTime();
health = HealthState.Incubating;
infectedBy = incomingMessage.value
infectedTime = input.runningTime()
health = HealthState.Incubating
}
}
}
break;
break
case MessageKind.HealthValue:
if (health != HealthState.Dead && signal > RSSI) {
game.addScore(1);
game.addScore(1)
}
break;
break
}
}
})
// main game loop
basic.forever(() => {
let message: Message;
basic.forever(function () {
let message: Message
if (master) {
switch (state) {
case GameState.Pairing:
// tell each player they are registered
for (const p of players) {
message = new Message();
message.kind = MessageKind.PairConfirmation;
message.value = p.icon;
message.toSerialNumber = p.id;
message.send();
message = new Message()
message.kind = MessageKind.PairConfirmation
message.value = p.icon
message.toSerialNumber = p.id
message.send()
}
serial.writeLine(`pairing ${players.length} players`);
basic.pause(500);
break;
serial.writeLine(`pairing ${players.length} players`)
basic.pause(500)
break
case GameState.Infecting:
if (patientZero.health == HealthState.Healthy) {
message = new Message();
message.kind = MessageKind.InitialInfect;
message.toSerialNumber = patientZero.id;
message.send();
basic.pause(100);
message = new Message()
message.kind = MessageKind.InitialInfect
message.toSerialNumber = patientZero.id
message.send()
basic.pause(100)
} else {
serial.writeLine(`patient ${patientZero.id} infected`);
serial.writeLine(`patient ${patientZero.id} infected`)
// show startup
basic.showIcon(GameIcons.Dead);
state = GameState.Running;
basic.showIcon(GameIcons.Dead)
state = GameState.Running
}
break;
break
case GameState.Running:
for (const p of players) {
message = new Message();
message.kind = MessageKind.HealthSet;
message.value = p.health;
message.toSerialNumber = p.id;
message.send();
message = new Message()
message.kind = MessageKind.HealthSet
message.value = p.health
message.toSerialNumber = p.id
message.send()
}
break;
break
case GameState.Over:
if (patientZero)
patientZero.show();
break;
patientZero.show()
break
}
message = new Message()
message.kind = MessageKind.GameState;
message.value = state;
message.send();
message.kind = MessageKind.GameState
message.value = state
message.send()
} else { // player loop
switch (state) {
case GameState.Pairing:
// broadcast player id
if (playerIcon < 0) {
message = new Message();
message.kind = MessageKind.PairRequest;
message.fromSerialNumber = control.deviceSerialNumber();
message.send();
message = new Message()
message.kind = MessageKind.PairRequest
message.fromSerialNumber = control.deviceSerialNumber()
message.send()
} else if (infectedBy > -1) {
message = new Message();
message.kind = MessageKind.HealthValue;
message.fromSerialNumber = control.deviceSerialNumber();
message.value = health;
message.send();
message = new Message()
message.kind = MessageKind.HealthValue
message.fromSerialNumber = control.deviceSerialNumber()
message.value = health
message.send()
}
break;
break
case GameState.Infecting:
message = new Message();
message.kind = MessageKind.HealthValue;
message.fromSerialNumber = control.deviceSerialNumber();
message.value = health;
message.send();
break;
message = new Message()
message.kind = MessageKind.HealthValue
message.fromSerialNumber = control.deviceSerialNumber()
message.value = health
message.send()
break
case GameState.Running:
// update health status
if (health != HealthState.Healthy && input.runningTime() - infectedTime > DEATH)
health = HealthState.Dead;
health = HealthState.Dead
else if (health != HealthState.Healthy && input.runningTime() - infectedTime > INCUBATION)
health = HealthState.Sick;
health = HealthState.Sick
// transmit disease
if (health == HealthState.Incubating || health == HealthState.Sick) {
message = new Message();
message.kind = MessageKind.TransmitVirus;
message.fromSerialNumber = control.deviceSerialNumber();
message.value = playerIcon;
message.send();
message = new Message()
message.kind = MessageKind.TransmitVirus
message.fromSerialNumber = control.deviceSerialNumber()
message.value = playerIcon
message.send()
}
message = new Message();
message.kind = MessageKind.HealthValue;
message.fromSerialNumber = control.deviceSerialNumber();
message.value = health;
message.send();
break;
message = new Message()
message.kind = MessageKind.HealthValue
message.fromSerialNumber = control.deviceSerialNumber()
message.value = health
message.send()
break
}
// show current animation
gameFace();
gameFace()
}
})

Просмотреть файл

@ -56,7 +56,7 @@ For patterns that you design, decide which LEDs you want to turn on and then mak
Figure out how to make the first letter of your name with the LEDs.
```sim
basic.forever(() => {
basic.forever(function () {
basic.showAnimation(`
# # # . . # # # . . # # # . . # # # . .
. . . . . # . . . . # . . . . # . . # .
@ -75,7 +75,7 @@ basic.forever(() => {
Make something fun!
```sim
basic.forever(() => {
basic.forever(function () {
basic.showAnimation(`
# . . . . # . . . . # . . . . # . . . . # . . . . # . . . .
. . . . . # . . . . # . . . . # . . . . # . . . # # . # # #
@ -99,86 +99,86 @@ Copy this code into the JavaScript editor and then download it to the board.
```typescript
class Board {
public isKarelActive: boolean;
public karelX: number;
public karelY: number;
public isKarelActive: boolean
public karelX: number
public karelY: number
public ledState: Image;
private karelDirection: Direction;
public ledState: Image
private karelDirection: Direction
constructor() {
this.isKarelActive = true;
this.karelX = 2;
this.karelY = 2;
this.karelDirection = Direction.UP;
this.isKarelActive = true
this.karelX = 2
this.karelY = 2
this.karelDirection = Direction.UP
this.ledState = images.createImage(`
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
`);
`)
}
pressedA() {
if (!this.isKarelActive) {
return;
return
}
this.karelDirection = (this.karelDirection + 1) % 4;
this.karelDirection = (this.karelDirection + 1) % 4
}
pressedB() {
if (!this.isKarelActive) {
return;
return
}
this.ledState.setPixel(this.karelX, this.karelY, true);
this.ledState.setPixel(this.karelX, this.karelY, true)
this.moveKarel()
}
shake() {
if (!this.isKarelActive) {
return;
return
}
this.moveKarel()
}
private moveKarel() {
if (!this.isKarelActive) {
return;
return
}
switch (this.karelDirection) {
case Direction.UP:
if (this.karelY > 0) {
this.karelY -= 1;
this.karelY -= 1
}
break;
break
case Direction.LEFT:
if (this.karelX > 0) {
this.karelX -= 1;
this.karelX -= 1
}
break;
break
case Direction.DOWN:
if (this.karelY < 4) {
this.karelY += 1;
this.karelY += 1
}
break;
break
case Direction.RIGHT:
if (this.karelX < 4) {
this.karelX += 1;
this.karelX += 1
}
break;
break
}
}
pressedAB() {
this.isKarelActive = !this.isKarelActive;
this.isKarelActive = !this.isKarelActive
}
update() {
this.ledState.showImage(0);
this.ledState.showImage(0)
}
}
const board = new Board();
const board = new Board()
enum Direction {
UP = 0,
LEFT,
@ -186,21 +186,21 @@ enum Direction {
RIGHT
}
input.onButtonPressed(Button.B, function () {
board.pressedB();
board.update();
board.pressedB()
board.update()
})
input.onGesture(Gesture.Shake, function () {
board.shake();
board.update();
board.shake()
board.update()
})
input.onButtonPressed(Button.A, function () {
board.pressedA();
board.update();
board.pressedA()
board.update()
})
input.onButtonPressed(Button.AB, function () {
board.pressedAB();
board.update();
board.pressedAB()
board.update()
})
basic.forever(function () {
if (board.isKarelActive) {

Просмотреть файл

@ -13,7 +13,7 @@ Add code to open the mouth when light is detected.
We are going to add code to open the mouth proportionally to the amount of light on the @boardname@. The code is in a loop so we'll continually read the light level and map it to an angle using the ``||pins:map||`` function.
```blocks
basic.forever(() => {
basic.forever(function () {
pins.servoWritePin(AnalogPin.P0, pins.map(
input.lightLevel(),
0,

Просмотреть файл

@ -11,13 +11,13 @@ Remote control your monster with another @boardname@.
You will need one more @boardname@ for this part. By using the radio, we can control the monster with another @boardname@. Download the code below to the @boardname@ on the monster and then again onto a "controller" @boardname@. Whenever button **A** is pressed, the monster's mouth moves once.
```blocks
radio.onReceivedNumber(({ receivedNumber }) => {
radio.onReceivedNumber(function(receivedNumber) {
pins.servoWritePin(AnalogPin.P0, 30)
basic.pause(500)
pins.servoWritePin(AnalogPin.P0, 150)
basic.pause(500)
})
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
radio.sendNumber(0)
})
```

Просмотреть файл

@ -23,10 +23,10 @@ The only things you need for this trick are your @boardname@ and any magnet that
Before we code the trick itself, we need to get the buttons working as you would expect them to such that pressing button **A** displays 'A' and pressing button **B** displays 'B':
```blocks
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
basic.showString("A")
})
input.onButtonPressed(Button.B, () => {
input.onButtonPressed(Button.B, function () {
basic.showString("B")
})
```
@ -48,7 +48,7 @@ If you've ever played with magnets you know they have two ends, often called a N
So, in the code below, we will check if the absolute value of our magnetic field strength reading is more than `100` and save the result of that check in a new variable called ``isSwitched``:
```blocks
let force = Math.abs(input.magneticForce(Dimension.Strength));
let force = Math.abs(input.magneticForce(Dimension.Strength))
let isSwitched = force > 100
```
## Step 4: Running our 'magnet nearby' check all the time
@ -56,10 +56,10 @@ let isSwitched = force > 100
At the moment, our code to detect a magnet being nearby will only run once. We need to put it into a ``||basic:forever||`` loop so that it keeps running again and again, checking for the magnet to come near to the @boardname@. We should also make sure ``isSwitched`` is set to `false` when our program starts.
```blocks
let force = 0;
let isSwitched = false;
basic.forever(() => {
force = Math.abs(input.magneticForce(Dimension.Strength));
let force = 0
let isSwitched = false
basic.forever(function () {
force = Math.abs(input.magneticForce(Dimension.Strength))
isSwitched = force > 100
})
```
@ -69,21 +69,21 @@ basic.forever(() => {
Now we can check the value of our variable ``isSwitched`` whenever we want and we will know that the magnet is nearby if it's value is `true`. Let's use that to change how the buttons work and complete the code for our trick. We will add an ``||logic:if then else||`` block to each button's code and check if we should swap over what's displayed for each button if ``isSwitched`` is equal to `true`:
```blocks
let force = 0;
let isSwitched = false;
basic.forever(() => {
force = Math.abs(input.magneticForce(Dimension.Strength));
let force = 0
let isSwitched = false
basic.forever(function () {
force = Math.abs(input.magneticForce(Dimension.Strength))
isSwitched = force > 100
})
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
if (isSwitched) {
basic.showString("B")
} else {
basic.showString("A")
}
})
input.onButtonPressed(Button.B, () => {
input.onButtonPressed(Button.B, function () {
if (isSwitched) {
basic.showString("A")
} else {

Просмотреть файл

@ -43,7 +43,7 @@ The code uses blocks from the [radio-blockchain](https://makecode.microbit.org/p
```blocks
// shaking is mining...
input.onGesture(Gesture.Shake, () => {
input.onGesture(Gesture.Shake, function () {
led.stopAnimation()
basic.clearScreen()
basic.pause(200) // display a short pause
@ -58,7 +58,7 @@ input.onGesture(Gesture.Shake, () => {
})
// show my coins
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
led.stopAnimation()
let coins = blockchain.valuesFrom(blockchain.id()).length;
basic.showNumber(coins);
@ -66,7 +66,7 @@ input.onButtonPressed(Button.A, () => {
})
// show the block chain size
input.onButtonPressed(Button.B, () => {
input.onButtonPressed(Button.B, function () {
led.stopAnimation()
basic.showNumber(blockchain.length());
basic.showString("BLOCKS");

Просмотреть файл

@ -18,10 +18,10 @@ https://youtu.be/m-HS8OyS0pw
## Step 2: code light sensor
Code the lightsensor on the @boardname@ to control the servo.
Code the light sensor on the @boardname@ to control the servo.
```blocks
basic.forever(() => {
basic.forever(function () {
led.plotBarGraph(
input.lightLevel(),
0
@ -48,7 +48,7 @@ angle range, ``[closed, opened]`` using ``pins.map``.
let angle = 0
let closed = 0
let opened = 0
basic.forever(() => {
basic.forever(function () {
led.plotBarGraph(
input.lightLevel(),
0

Просмотреть файл

@ -12,13 +12,13 @@ You will need 2 @boardname@ for this part. By using the radio, we can make the M
Download the code below to the @boardname@ on the Milk Carton Monster and another "controller" @boardname@. Whenever ``A`` is pressed, the Milk Carton Monster will move once.
```blocks
radio.onReceivedNumber((receivedNumber) => {
radio.onReceivedNumber(function(receivedNumber) {
pins.servoWritePin(AnalogPin.P0, 0)
basic.pause(500)
pins.servoWritePin(AnalogPin.P0, 180)
basic.pause(500)
})
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
radio.sendNumber(0)
})
```

Просмотреть файл

@ -17,11 +17,11 @@ In order for the Milky Monster to move, the @boardname@ needs to command the ser
- Press button ``B`` to switch the servo to 0 degrees (to open the mouth of Milky Monster).
```blocks
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
pins.servoWritePin(AnalogPin.P0, 180)
basic.showNumber(180)
})
input.onButtonPressed(Button.B, () => {
input.onButtonPressed(Button.B, function () {
pins.servoWritePin(AnalogPin.P0, 0)
basic.showNumber(0)
})
@ -64,7 +64,7 @@ https://youtu.be/fAR58GJUZdM
Code the light sensor on the @boardname@ to control the servo.
```blocks
basic.forever(() => {
basic.forever(function () {
pins.servoWritePin(AnalogPin.P0, input.lightLevel())
led.plotBarGraph(
input.lightLevel(),

Просмотреть файл

@ -12,13 +12,13 @@ You will need a second @boardname@ for this part. By using the radio, we can con
Download the code below to the @boardname@ that's on the Milky Monster and again to another "controller" @boardname@. Whenever button **A** is pressed, the Milky Monster will move one time.
```blocks
radio.onReceivedNumber((receivedNumber) => {
radio.onReceivedNumber(function(receivedNumber) {
pins.servoWritePin(AnalogPin.P0, 0)
basic.pause(500)
pins.servoWritePin(AnalogPin.P0, 180)
basic.pause(500)
})
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
radio.sendNumber(0)
})
```

Просмотреть файл

@ -16,7 +16,7 @@ Let's add blocks that send a number when button ``A`` is pressed. We assume that
```blocks
radio.setGroup(1)
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
radio.sendNumber(0)
basic.showIcon(IconNames.Happy)
})
@ -41,7 +41,7 @@ radio.onReceivedNumber(function (receivedNumber) {
Adding another mood to our messaging app done in a similar way. We decide that the "mood code" of `1` means **frowny**. We can add a ``B`` button event that sends that code.
```blocks
input.onButtonPressed(Button.B, () => {
input.onButtonPressed(Button.B, function () {
radio.sendNumber(1)
basic.showIcon(IconNames.Sad)
})
@ -70,11 +70,11 @@ Try adding a new code and use the ``||input:on shake||`` event to send it.
```blocks
radio.setGroup(1)
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
radio.sendNumber(0)
basic.showIcon(IconNames.Happy)
})
input.onButtonPressed(Button.B, () => {
input.onButtonPressed(Button.B, function () {
radio.sendNumber(1)
basic.showIcon(IconNames.Sad)
})

Просмотреть файл

@ -30,7 +30,7 @@ radio.setTransmitSerialNumber(true)
radio.setGroup(4)
led.setBrightness(64)
let reading = 0
basic.forever(() => {
basic.forever(function () {
pins.analogWritePin(AnalogPin.P1, 1023)
reading = pins.analogReadPin(AnalogPin.P0)
radio.sendNumber(reading / 4);

Просмотреть файл

@ -15,7 +15,7 @@ We are going to use the light sensor to detect if a train is passing. We will do
Let's first explore how the light sensor works by downloading the following program onto our @boardname@.
```block
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
basic.showNumber(input.lightLevel())
})
```
@ -49,7 +49,7 @@ Add the following blocks to your program to make the top-left led indicate if a
Replace 40 with your threshold.
```block
basic.forever(() => {
basic.forever(function () {
if (input.lightLevel() < 40) {
led.plot(0, 0)
} else {
@ -95,7 +95,7 @@ We can turn on one LED by writing a digital 1 to one pin and a digital 0 to the
Now use the following program to make the lights blink indefinitely.
```block
basic.forever(() => {
basic.forever(function () {
pins.digitalWritePin(DigitalPin.P1, 1)
pins.digitalWritePin(DigitalPin.P2, 0)
basic.pause(300)
@ -120,11 +120,11 @@ First of all, remove the forever block from step 5. Then add the following code:
```block
let flashes_remaining = 0
input.onButtonPressed(Button.B, () => {
input.onButtonPressed(Button.B, function () {
flashes_remaining = 5
})
basic.forever(() => {
basic.forever(function () {
while (flashes_remaining > 0) {
pins.digitalWritePin(DigitalPin.P1, 0)
pins.digitalWritePin(DigitalPin.P2, 1)

Просмотреть файл

@ -18,7 +18,7 @@ https://youtu.be/pD6tM1nXCPA
The first program has the car drive around in a circle for 5 seconds when the user presses the ``A`` button. This is simply done by turning both motor controllers on for 5 seconds.
```blocks-ignore
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
basic.showIcon(IconNames.Happy)
kitronik.motorOn(kitronik.Motors.Motor1, kitronik.MotorDirection.Reverse, 100)
kitronik.motorOn(kitronik.Motors.Motor2, kitronik.MotorDirection.Forward, 100)
@ -46,7 +46,7 @@ https://youtu.be/agor9wtiAkE
Instead of stopping after 5 seconds, we reverse the steering motor to turn in the other direction. This will create a figure eight path.
```blocks-ignore
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
basic.showIcon(IconNames.Happy)
kitronik.motorOn(kitronik.Motors.Motor1, kitronik.MotorDirection.Reverse, 100)
kitronik.motorOn(kitronik.Motors.Motor2, kitronik.MotorDirection.Forward, 100)

Просмотреть файл

@ -14,23 +14,23 @@ radio.onReceivedValue(function (name: string, value: number) {
led.toggle(0, 0)
if (name == "throttle") {
if (value > 0) {
kitronik.motorOn(kitronik.Motors.Motor1, kitronik.MotorDirection.Reverse, 100);
kitronik.motorOn(kitronik.Motors.Motor1, kitronik.MotorDirection.Reverse, 100)
} else if (value < 0) {
kitronik.motorOn(kitronik.Motors.Motor1, kitronik.MotorDirection.Forward, 100);
kitronik.motorOn(kitronik.Motors.Motor1, kitronik.MotorDirection.Forward, 100)
} else {
kitronik.motorOff(kitronik.Motors.Motor1);
}
} else if (name == "steering") {
if (value > 0) {
kitronik.motorOn(kitronik.Motors.Motor2, kitronik.MotorDirection.Forward, 100);
kitronik.motorOn(kitronik.Motors.Motor2, kitronik.MotorDirection.Forward, 100)
} else if (value < 0) {
kitronik.motorOn(kitronik.Motors.Motor2, kitronik.MotorDirection.Reverse, 100);
kitronik.motorOn(kitronik.Motors.Motor2, kitronik.MotorDirection.Reverse, 100)
} else {
kitronik.motorOff(kitronik.Motors.Motor2);
kitronik.motorOff(kitronik.Motors.Motor2)
}
}
})
basic.forever(() => {
basic.forever(function () {
throttle = 0
if (input.buttonIsPressed(Button.A)) {
throttle = 100

Просмотреть файл

@ -46,10 +46,10 @@ let start = 0
let end = 0
let false_start = false
let running = false
input.onPinPressed(TouchPin.P0, () => {
input.onPinPressed(TouchPin.P0, function () {
})
input.onPinPressed(TouchPin.P1, () => {
input.onPinPressed(TouchPin.P1, function () {
})
running = false
@ -67,13 +67,13 @@ let start = 0
let end = 0
let false_start = false
let running = false
input.onPinPressed(TouchPin.P0, () => {
input.onPinPressed(TouchPin.P0, function () {
basic.showNumber(3)
basic.showNumber(2)
basic.showNumber(1)
basic.clearScreen()
})
input.onPinPressed(TouchPin.P1, () => {
input.onPinPressed(TouchPin.P1, function () {
})
running = false
@ -93,7 +93,7 @@ let start = 0
let end = 0
let false_start = false
let running = false
input.onPinPressed(TouchPin.P0, () => {
input.onPinPressed(TouchPin.P0, function () {
basic.showNumber(3)
basic.showNumber(2)
basic.showNumber(1)
@ -101,7 +101,7 @@ input.onPinPressed(TouchPin.P0, () => {
running = false
false_start = false
})
input.onPinPressed(TouchPin.P1, () => {
input.onPinPressed(TouchPin.P1, function () {
})
running = false
@ -119,7 +119,7 @@ let start = 0
let end = 0
let false_start = false
let running = false
input.onPinPressed(TouchPin.P0, () => {
input.onPinPressed(TouchPin.P0, function () {
basic.showNumber(3)
basic.showNumber(2)
basic.showNumber(1)
@ -128,7 +128,7 @@ input.onPinPressed(TouchPin.P0, () => {
false_start = false
basic.pause(1000 + randint(0, 2000))
})
input.onPinPressed(TouchPin.P1, () => {
input.onPinPressed(TouchPin.P1, function () {
})
running = false
@ -146,10 +146,10 @@ let start = 0
let end = 0
let false_start = false
let running = false
input.onPinPressed(TouchPin.P1, () => {
input.onPinPressed(TouchPin.P1, function () {
})
input.onPinPressed(TouchPin.P0, () => {
input.onPinPressed(TouchPin.P0, function () {
basic.showNumber(3)
basic.showNumber(2)
basic.showNumber(1)
@ -184,7 +184,7 @@ let start = 0
let end = 0
let false_start = false
let running = false
input.onPinPressed(TouchPin.P1, () => {
input.onPinPressed(TouchPin.P1, function () {
if (running) {
running = false
end = input.runningTime()
@ -208,7 +208,7 @@ input.onPinPressed(TouchPin.P1, () => {
`)
}
})
input.onPinPressed(TouchPin.P0, () => {
input.onPinPressed(TouchPin.P0, function () {
basic.showNumber(3)
basic.showNumber(2)
basic.showNumber(1)
@ -241,7 +241,7 @@ let start = 0
let end = 0
let false_start = false
let running = false
input.onPinPressed(TouchPin.P0, () => {
input.onPinPressed(TouchPin.P0, function () {
basic.showNumber(3)
basic.showNumber(2)
basic.showNumber(1)
@ -257,7 +257,7 @@ input.onPinPressed(TouchPin.P0, () => {
led.plot(randint(0, 4), randint(0, 4))
}
})
input.onPinPressed(TouchPin.P1, () => {
input.onPinPressed(TouchPin.P1, function () {
if (running) {
running = false
end = input.runningTime()
@ -281,7 +281,7 @@ input.onPinPressed(TouchPin.P1, () => {
`)
}
})
input.onPinPressed(TouchPin.P2, () => {
input.onPinPressed(TouchPin.P2, function () {
if (running) {
running = false
end = input.runningTime()

Просмотреть файл

@ -37,7 +37,7 @@ Choose a random number between 0 and 9.
```blocks
let randomNbr = 0
input.onGesture(Gesture.ScreenUp, () => {
input.onGesture(Gesture.ScreenUp, function () {
randomNbr = randint(0, 10)
basic.showNumber(randomNbr)
})
@ -47,7 +47,7 @@ Choose a random number between 1 and 9.
```blocks
let randomNbr = 0
input.onGesture(Gesture.ScreenUp, () => {
input.onGesture(Gesture.ScreenUp, function () {
randomNbr = 0
while (randomNbr < 1) {
randomNbr = randint(0, 10)
@ -63,13 +63,13 @@ The score keeper program adds one point for a player when button ``A`` or ``B``
```blocks
let player1Score = 0
let player2Score = 0
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
player1Score += 1
})
input.onButtonPressed(Button.B, () => {
input.onButtonPressed(Button.B, function () {
player2Score += 1
})
input.onButtonPressed(Button.AB, () => {
input.onButtonPressed(Button.AB, function () {
if (player1Score == player2Score) {
basic.showString("TIE")
} else if (player1Score > player2Score) {

Просмотреть файл

@ -9,17 +9,17 @@ in a loop.
```blocks
let angle = 90
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
angle = Math.max(0, angle - 5)
pins.servoWritePin(AnalogPin.P0, angle)
led.stopAnimation()
})
input.onButtonPressed(Button.B, () => {
input.onButtonPressed(Button.B, function () {
angle = Math.min(180, angle + 5)
pins.servoWritePin(AnalogPin.P0, angle)
led.stopAnimation()
})
basic.forever(() => {
basic.forever(function () {
basic.showNumber(angle)
})
pins.servoWritePin(AnalogPin.P0, angle)

Просмотреть файл

@ -12,7 +12,7 @@ To measure this, we read the voltage on pin **P0** using ``||pins:analog read pi
which returns a value between ``0`` (no current) and ``1023`` (maximum current). The value is graph on the screen using ``||led:plot bar graph||``.
```blocks
basic.forever(() => {
basic.forever(function () {
led.plotBarGraph(
pins.analogReadPin(AnalogPin.P0),
1023
@ -33,7 +33,7 @@ This code needs to go into the ``||basic:forever||`` loop. We've also added the
```blocks
let reading = 0
basic.forever(() => {
basic.forever(function () {
reading = pins.analogReadPin(AnalogPin.P0)
led.plotBarGraph(
reading,
@ -77,7 +77,7 @@ This saves electricity and also avoids corrosion of the probes.
```blocks
led.setBrightness(64)
let reading = 0
basic.forever(() => {
basic.forever(function () {
pins.digitalWritePin(DigitalPin.P1, 1)
basic.pause(1)
reading = pins.analogReadPin(AnalogPin.P0)

Просмотреть файл

@ -9,16 +9,13 @@ To make it happen, we need to change the program to:
* send the moisture level **divided by 4** as the dashboard takes values between ``0`` and ``255``.
```blocks
radio.setTransmitSerialNumber(true)
radio.setGroup(4)
led.setBrightness(64)
let reading = 0
basic.forever(() => {
basic.forever(function () {
pins.digitalWritePin(DigitalPin.P1, 1)
basic.pause(1)
reading = pins.analogReadPin(AnalogPin.P0)
pins.digitalWritePin(DigitalPin.P1, 0)
radio.sendNumber(reading / 4)
led.plotBarGraph(
reading,
1023
@ -26,7 +23,7 @@ basic.forever(() => {
if (input.buttonIsPressed(Button.A)) {
basic.showNumber(reading)
}
basic.pause(5000);
basic.pause(5000)
})
```

Просмотреть файл

@ -14,7 +14,7 @@ Add an event to run code when ``||input:button A pressed||``. We'll put our coin
code in here.
```spy
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
})
```
@ -26,7 +26,7 @@ The ``||math:random boolean||`` value is used to determine a ``heads`` or ``tail
a coin toss.
```spy
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
if (Math.randomBoolean()) {
} else {
}
@ -39,7 +39,7 @@ Now, ``||basic:show icon||`` for a `skull` ``||logic:if||`` the ``||math:random
``tails``.
```spy
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
if (Math.randomBoolean()) {
basic.showIcon(IconNames.Skull)
} else {
@ -59,7 +59,7 @@ icons before the check of the ``||math:random boolean||`` value to show that the
coin is flipping.
```spy
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
basic.showIcon(IconNames.Diamond)
basic.showIcon(IconNames.SmallDiamond)
basic.showIcon(IconNames.Diamond)

Просмотреть файл

@ -13,7 +13,7 @@ Turn your micro:bit into a **Rock Paper Scissors** game that you can play with y
We'll start our Rock Paper Scissors game when we shake 👋 our micro:bit. Add an ``||input:on shake||`` function to run code when you shake the @boardname@. Type the code below, or drag a code snippet from the ``||input:Input||`` Toolbox category.
```spy
input.onGesture(Gesture.Shake, () => {
input.onGesture(Gesture.Shake, function () {
})
```
@ -24,7 +24,7 @@ Create a variable named "hand" - this will help us keep track of whether we have
```spy
let hand = 0
input.onGesture(Gesture.Shake, () => {
input.onGesture(Gesture.Shake, function () {
hand = randint(1, 3)
})
```
@ -35,7 +35,7 @@ To check the value of the hand variable, type ``||logic:if hand==1||`` then use
```spy
let hand = 0
input.onGesture(Gesture.Shake, () => {
input.onGesture(Gesture.Shake, function () {
hand = randint(1, 3)
if (hand == 1) {
basic.showIcon(IconNames.SmallSquare)

Просмотреть файл

@ -20,7 +20,7 @@ We want to detect when the solid state occurs. On Pin 2 Pressed, you want to rep
```blocks
let temperature = 0
let atmos_temperature = 0
input.onPinPressed(TouchPin.P2, () => {
input.onPinPressed(TouchPin.P2, function () {
atmos_temperature = 0
basic.showString("SOLID")
})
@ -35,11 +35,11 @@ We want to detect when the liquid state happens. On Pin 1 Pressed, you want to r
```blocks
let temperature = 0
let atmos_temperature = 0
input.onPinPressed(TouchPin.P2, () => {
input.onPinPressed(TouchPin.P2, function () {
atmos_temperature = 0
basic.showString("SOLID")
})
input.onPinPressed(TouchPin.P1, () => {
input.onPinPressed(TouchPin.P1, function () {
atmos_temperature = 80
basic.showString("LIQUID")
})
@ -54,15 +54,15 @@ We want to detect when matter will be a gas. On Pin 0 Pressed, you want to repre
```blocks
let atmos_temperature = 0
let temperature = 0
input.onPinPressed(TouchPin.P0, () => {
input.onPinPressed(TouchPin.P0, function () {
atmos_temperature = 250
basic.showString("GAS")
})
input.onPinPressed(TouchPin.P2, () => {
input.onPinPressed(TouchPin.P2, function () {
atmos_temperature = 0
basic.showString("SOLID")
})
input.onPinPressed(TouchPin.P1, () => {
input.onPinPressed(TouchPin.P1, function () {
atmos_temperature = 80
basic.showString("LIQUID")
})
@ -79,19 +79,19 @@ We want to display a change of temperature on shake. When you shake the states o
```blocks
let atmos_temperature = 0
let temperature = 0
input.onGesture(Gesture.Shake, () => {
input.onGesture(Gesture.Shake, function () {
temperature += 50
basic.showIcon(IconNames.Triangle)
})
input.onPinPressed(TouchPin.P0, () => {
input.onPinPressed(TouchPin.P0, function () {
atmos_temperature = 250
basic.showString("GAS")
})
input.onPinPressed(TouchPin.P2, () => {
input.onPinPressed(TouchPin.P2, function () {
atmos_temperature = 0
basic.showString("SOLID")
})
input.onPinPressed(TouchPin.P1, () => {
input.onPinPressed(TouchPin.P1, function () {
atmos_temperature = 80
basic.showString("LIQUID")
})
@ -117,11 +117,11 @@ The second condition follows this logic:
```blocks
let atmos_temperature = 0
let temperature = 0
input.onGesture(Gesture.Shake, () => {
input.onGesture(Gesture.Shake, function () {
temperature += 50
basic.showIcon(IconNames.Triangle)
})
basic.forever(() => {
basic.forever(function () {
if (temperature < atmos_temperature) {
temperature += 20
} else {
@ -137,15 +137,15 @@ basic.forever(() => {
basic.clearScreen()
basic.pause(100)
})
input.onPinPressed(TouchPin.P0, () => {
input.onPinPressed(TouchPin.P0, function () {
atmos_temperature = 250
basic.showString("GAS")
})
input.onPinPressed(TouchPin.P2, () => {
input.onPinPressed(TouchPin.P2, function () {
atmos_temperature = 0
basic.showString("SOLID")
})
input.onPinPressed(TouchPin.P1, () => {
input.onPinPressed(TouchPin.P1, function () {
atmos_temperature = 80
basic.showString("LIQUID")
})

Просмотреть файл

@ -55,7 +55,7 @@ To make the game less predictable, we use the ``||math:pick random||`` block to
```blocks
let potato = 0
input.onButtonPressed(Button.AB, () => {
input.onButtonPressed(Button.AB, function () {
potato = randint(10, 20)
})
```
@ -67,7 +67,7 @@ we have the potato and we can send it. After sending it, we set the **potato** v
```blocks
let potato = 0
input.onGesture(Gesture.Shake, () => {
input.onGesture(Gesture.Shake, function () {
if (potato > 0) {
radio.sendNumber(potato)
potato = -1
@ -97,7 +97,7 @@ Making the clock tick down is done with a ``||loops:forever||`` loop.
```blocks
let potato = 0
basic.forever(() => {
basic.forever(function () {
if (potato == 0) {
basic.showIcon(IconNames.Skull)
}
@ -122,18 +122,18 @@ let potato = 0
radio.onReceivedNumber(function (receivedNumber) {
potato = receivedNumber
})
input.onGesture(Gesture.Shake, () => {
input.onGesture(Gesture.Shake, function () {
if (potato > 0) {
radio.sendNumber(potato)
potato = -1
}
})
input.onButtonPressed(Button.AB, () => {
input.onButtonPressed(Button.AB, function () {
potato = randint(10, 20)
})
radio.setGroup(1)
potato = -1
basic.forever(() => {
basic.forever(function () {
if (potato == 0) {
basic.showIcon(IconNames.Skull)
}

Просмотреть файл

@ -54,7 +54,7 @@ Let's wrap it all in a forever loop so this code is running in the background al
Modify your code to add the blocks below. Download the code onto one of the @boardname@s, press and release button **A** a few times.
```blocks
basic.forever(() => {
basic.forever(function () {
if (input.buttonIsPressed(Button.A)) {
pins.digitalWritePin(DigitalPin.P1, 1)
led.plot(2, 2)
@ -78,18 +78,18 @@ We'll turn the LED in the bottom right corner (4, 4) on to show that we received
Make sure your code looks like this:
```blocks
basic.forever(() => {
basic.forever(function () {
if (input.buttonIsPressed(Button.A)) {
pins.digitalWritePin(DigitalPin.P1, 1);
led.plot(2, 2);
pins.digitalWritePin(DigitalPin.P1, 1)
led.plot(2, 2)
} else {
pins.digitalWritePin(DigitalPin.P1, 0);
pins.digitalWritePin(DigitalPin.P1, 0)
basic.clearScreen();
}
if (pins.digitalReadPin(DigitalPin.P2) == 1) {
led.plot(4, 4);
led.plot(4, 4)
} else {
led.unplot(4, 4);
led.unplot(4, 4)
}
});
```

Просмотреть файл

@ -48,11 +48,11 @@ basic.showLeds(`
. . . . .
. . . . .
`)
input.onPinPressed(TouchPin.P0, () => {})
input.onPinPressed(TouchPin.P0, function () {})
let t = 0
input.runningTime()
t - 1
control.eventTimestamp();
control.eventTimestamp()
basic.showNumber(0)
```
@ -101,7 +101,7 @@ basic.showLeds(`
. . . . .
. . . . .
`)
input.onPinPressed(TouchPin.P0, () => {
input.onPinPressed(TouchPin.P0, function () {
basic.showLeds(`
# . . . .
# . . . .
@ -156,7 +156,7 @@ basic.showLeds(`
. . . . .
. . . . .
`)
input.onPinPressed(TouchPin.P0, () => {
input.onPinPressed(TouchPin.P0, function () {
basic.showLeds(`
# . . . .
# . . . .
@ -165,7 +165,7 @@ input.onPinPressed(TouchPin.P0, () => {
# . . . .
`)
})
input.onPinPressed(TouchPin.P1, () => {
input.onPinPressed(TouchPin.P1, function () {
basic.showLeds(`
# . . . #
# . . . #
@ -186,8 +186,8 @@ We will record the time where each gate is tripped in variables ``t0`` and ``t1`
We take the different between ``t1`` and ``t0`` to compute the duration between the gates.
```blocks
let t0 = 0;
let t1 = 0;
let t0 = 0
let t1 = 0
basic.showLeds(`
. . . . .
. . . . .
@ -195,8 +195,8 @@ basic.showLeds(`
. . . . .
. . . . .
`)
input.onPinPressed(TouchPin.P0, () => {
t0 = control.eventTimestamp();
input.onPinPressed(TouchPin.P0, function () {
t0 = control.eventTimestamp()
basic.showLeds(`
# . . . .
# . . . .
@ -205,8 +205,8 @@ input.onPinPressed(TouchPin.P0, () => {
# . . . .
`)
})
input.onPinPressed(TouchPin.P1, () => {
t1 = control.eventTimestamp();
input.onPinPressed(TouchPin.P1, function () {
t1 = control.eventTimestamp()
basic.showLeds(`
# . . . #
# . . . #

Просмотреть файл

@ -18,7 +18,7 @@ The turtle scans the display over and over again.
turtle.setPosition(0, 0)
turtle.turnRight()
turtle.setSpeed(20)
basic.forever(() => {
basic.forever(function () {
turtle.forward(4)
turtle.turnRight()
turtle.forward(1)

Просмотреть файл

@ -17,7 +17,7 @@ A turtle that spirals into the center of the display and back out again.
```blocks
turtle.setPosition(0, 0)
turtle.turnRight()
basic.forever(() => {
basic.forever(function () {
for (let index = 0; index <= 4; index++) {
turtle.forward(4 - index)
turtle.turnRight()

Просмотреть файл

@ -21,7 +21,7 @@ Assuming button ``A`` is for a NO vote and ``B`` is for YES, the voter program w
When button ``A`` is pressed, a number ``0`` is sent via radio and the ``X`` symbol is shown on the screen.
```block
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
radio.sendNumber(0)
basic.showIcon(IconNames.No)
})
@ -32,7 +32,7 @@ input.onButtonPressed(Button.A, () => {
When button ``B`` is pressed, a number ``255`` is sent via radio and the ``Y`` symbol is shown on the screen.
```block
input.onButtonPressed(Button.B, () => {
input.onButtonPressed(Button.B, function () {
radio.sendNumber(255)
basic.showIcon(IconNames.Yes)
})
@ -56,11 +56,11 @@ radio.setGroup(4)
Putting all the parts together, here's the complete voter program:
```blocks
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
radio.sendNumber(0)
basic.showIcon(IconNames.No)
})
input.onButtonPressed(Button.B, () => {
input.onButtonPressed(Button.B, function () {
radio.sendNumber(255)
basic.showIcon(IconNames.Yes)
})

Просмотреть файл

@ -5,7 +5,7 @@
Let's start by using a combination of [forever](/reference/basic/forever) and [show leds](/reference/basic/show-leds) to create animation:
```blocks
basic.forever(() => {
basic.forever(function () {
basic.showLeds(`
# # . # #
# # . # #
@ -34,7 +34,7 @@ How do we know that the wallet is in the pocket? It is really dark in there... W
Using an [if statement](/blocks/logic/if), we can test if the level of light is sufficient to turn on the screen. Otherwise, we turn off the screen for a few second to save energy.
```blocks
basic.forever(() => {
basic.forever(function () {
if (input.lightLevel() > 16) {
basic.showLeds(`
# # . # #

Просмотреть файл

@ -17,9 +17,9 @@ We need a variable to keep track of how many motions you make.
3. Let's show that there are no motions counted yet. Get a ``||basic:show number||`` from **Basic** and put it after the variable. Now, change the `0` to the `motions` variable from the **Variables** category in the toolbox.
```blocks
let motions = 0;
motions = 0;
basic.showNumber(motions);
let motions = 0
motions = 0
basic.showNumber(motions)
```
## Count your movements
@ -31,10 +31,10 @@ Ok, now we'll count and show all of your movements.
3. Grab another ``||basic:show number||`` and put it at the bottom of the ``||input:on shake||``. Find `motions` again back over in **Variables** and replace the `0` with it.
```blocks
let motions = 0;
input.onGesture(Gesture.Shake, () => {
motions += 1;
basic.showNumber(motions);
let motions = 0
input.onGesture(Gesture.Shake, function () {
motions += 1
basic.showNumber(motions)
})
```
@ -46,10 +46,10 @@ If we want to start over from zero, then we need to have a way to reset the moti
2. Grab another ``||basic:show number||`` and change the `0` to the a `motions` variable.
```blocks
let motions = 0;
input.onButtonPressed(Button.A, () => {
motions = 0;
basic.showNumber(motions);
let motions = 0
input.onButtonPressed(Button.A, function () {
motions = 0
basic.showNumber(motions)
})
```

Просмотреть файл

@ -39,9 +39,9 @@ So, let's try showing the time on the display. We aren't keeping time yet but we
let time = ""
let minutes = 0
let hours = 0
input.onGesture(Gesture.Shake, () => {
time = hours + (":" + minutes);
basic.showString(time);
input.onGesture(Gesture.Shake, function () {
time = hours + (":" + minutes)
basic.showString(time)
})
```
## Set the time with buttons
@ -58,12 +58,12 @@ Let's make a way to set the hours for the watch.
6. In the ``||logic:else||`` section, put a ``||variables:set to||`` there. Select the `hours` variable name from the dropdown and leave the `0`.
```blocks
let hours = 0;
input.onButtonPressed(Button.A, () => {
let hours = 0
input.onButtonPressed(Button.A, function () {
if (hours < 23) {
hours += 1;
hours += 1
} else {
hours = 0;
hours = 0
}
})
```
@ -76,12 +76,12 @@ Setting minutes is almost the same as setting hours but with just a few changes.
3. Change every variable name from `hours` to `minutes`. Change the `23` in the ``||logic:if||`` condition to ``59``. This is the limit of minutes we count.
```blocks
let minutes = 0;
input.onButtonPressed(Button.B, () => {
let minutes = 0
input.onButtonPressed(Button.B, function () {
if (minutes < 59) {
minutes += 1;
minutes += 1
} else {
minutes = 0;
minutes = 0
}
})
```
@ -95,9 +95,9 @@ Time is shown in either 24 hour or 12 hour format. We'll use one more button to
3. Pick up a `ampm` from **Variables** and connect it on the right of the ``||logic:not||``. This switches our 24 hour format to 12 hour and back.
```blocks
let ampm = false;
input.onButtonPressed(Button.AB, () => {
ampm = !(ampm);
let ampm = false
input.onButtonPressed(Button.AB, function () {
ampm = !(ampm)
})
```
@ -114,12 +114,12 @@ A watch really has three parts: the display, settings, and timer. We need a way
```blocks
let minutes = 0;
basic.forever(() => {
basic.forever(function () {
basic.pause(60000)
if (minutes < 59) {
minutes += 1;
minutes += 1
} else {
minutes = 0;
minutes = 0
}
})
```
@ -134,7 +134,7 @@ basic.forever(() => {
```blocks
let minutes = 0
let hours = 0
basic.forever(() => {
basic.forever(function () {
basic.pause(60000)
if (minutes < 59) {
minutes += 1
@ -167,7 +167,7 @@ First, we have to code an adjustment for the hours number when we're using the 1
let hours = 0;
let adjust = 0;
let ampm = false;
input.onGesture(Gesture.Shake, () => {
input.onGesture(Gesture.Shake, function () {
adjust = hours;
if (ampm) {
if (hours > 12) {
@ -194,24 +194,24 @@ Now, we have to join up the hours and minutes to make text that will display on
7. In the fourth copy, change the first `""` in the ``||text:join||`` to the variable `time`. Change the second string in the ``||text:join||`` to a ``minutes``.
```blocks
let minutes = 0;
let hours = 0;
let adjust = 0;
let time = "";
let ampm = false;
input.onGesture(Gesture.Shake, () => {
adjust = hours;
let minutes = 0
let hours = 0
let adjust = 0
let time = ""
let ampm = false
input.onGesture(Gesture.Shake, function () {
adjust = hours
if (ampm) {
if (hours > 12) {
adjust = hours - 12;
adjust = hours - 12
} else {
if (hours == 0) {
adjust = 12;
adjust = 12
}
}
}
time = "" + adjust;
time = time + ":";
time = "" + adjust
time = time + ":"
if (minutes < 10) {
time = time + "0"
}
@ -230,12 +230,12 @@ Ok, we're getting close to finishing now. Here we need to add the 'AM' or 'PM' i
5. Finally, at the very bottom of ``||input:on shake||``, go get a ``||basic:show string||`` from **Basic** and put it there. Change the string `"Hello!"` to the `time` variable.
```blocks
let minutes = 0;
let hours = 0;
let adjust = 0;
let time = "";
let ampm = false;
input.onGesture(Gesture.Shake, () => {
let minutes = 0
let hours = 0
let adjust = 0
let time = ""
let ampm = false
input.onGesture(Gesture.Shake, function () {
adjust = hours;
if (ampm) {
if (hours > 12) {
@ -246,7 +246,7 @@ input.onGesture(Gesture.Shake, () => {
}
}
}
time = "" + adjust;
time = "" + adjust
time = time + ":"
if (minutes < 10)
{

Просмотреть файл

@ -35,7 +35,7 @@ We'll use button `A` to add `10` seconds to our time count. The time count of `s
```blocks
let seconds = 0;
input.onButtonPressed(Button.A, () => {
input.onButtonPressed(Button.A, function () {
if (seconds < 50) {
seconds += 10;
basic.showNumber(seconds)
@ -57,9 +57,9 @@ Now, we'll use the `B` button to add just `1` second the time count. The time co
```blocks
let seconds = 0;
input.onButtonPressed(Button.B, () => {
input.onButtonPressed(Button.B, function () {
if (seconds < 60) {
seconds += 1;
seconds += 1
basic.showNumber(seconds)
basic.clearScreen()
}
@ -71,13 +71,13 @@ input.onButtonPressed(Button.B, () => {
Ok, now we'll get the timer going and show how many seconds are left. This will happen when the watch is shaken!
1. Get an ``||input:on shake||`` block and place it in the workspace.
2. Pull out a ``||loops:while||`` from **Loops** and put it in the ``||input:on shake||``. Replace the `true` condition with the ``||logic:0 < 0||`` conditon from **Logic**. Make the `<` go to `>`. Change the `0` on the left to the `seconds` variable.
2. Pull out a ``||loops:while||`` from **Loops** and put it in the ``||input:on shake||``. Replace the `true` condition with the ``||logic:0 < 0||`` condition from **Logic**. Make the `<` go to `>`. Change the `0` on the left to the `seconds` variable.
3. Take out another ``||basic:show number||`` and put it inside the ``||loops:while||``. Change the `0` to the `seconds` variable. Put a ``||basic:pause||`` under that and set the time to `1000` milliseconds. This means our timer will count down by **1000** milliseconds, which is actually one second, each time through the loop.
4. To change the number of seconds left, get a ``||variables:change by||`` and place it below the ``||basic:pause||``. Find the ``||math:0 - 0||`` block in **Math** and put it in the ``||variables:change by||``. Set the `0` on the right of the minus to be a `1`.
```blocks
let seconds = 0;
input.onGesture(Gesture.Shake, () => {
input.onGesture(Gesture.Shake, function () {
while (seconds > 0) {
basic.showNumber(seconds);
basic.pause(1000);
@ -91,11 +91,11 @@ Add a few ``||basic:show icon||`` blocks at the bottom of the ``||loops:while||`
```blocks
let seconds = 0;
input.onGesture(Gesture.Shake, () => {
input.onGesture(Gesture.Shake, function () {
while (seconds > 0) {
basic.showNumber(seconds);
basic.pause(1000);
seconds -= 1;
basic.showNumber(seconds)
basic.pause(1000)
seconds -= 1
}
basic.showIcon(IconNames.Diamond)
basic.showIcon(IconNames.SmallDiamond)