micro:bit(マイクロビット)
Please do not reuse without prior permission.

micro:bit(マイクロビット)のピンポンゲームに開始と終了画面を付ける

先日、公開したピンポンゲームに開始画面と終了画面を付けてほしいとリクエストを頂きましたので追加してみました。実現方法は、色々あると思いますが一番簡単で変更量が少ないと思う方法でやってみました。
0 Shares
0
0
0

先日、公開したピンポンゲームに開始画面と終了画面を付けてほしいとリクエストを頂きましたので追加してみました。

実現方法は、色々あると思いますが一番簡単で変更量が少ないと思う方法でやってみました。

今回作るピンポンゲーム

必要なもの

micro:bitだけあれば動作します。スピーカーなど特別なものは必要ありません。

「最初だけ」のプログラム

ピンポンゲーム中かどうかを判断する変数を追加しています。

「最初だけ」のプログラム

「ボタンAを押したとき」のプログラム

「ボタンAを押したとき」のプログラムは変更していません。

「ボタンAを押したとき」のプログラム

「ボタンBを押したとき」のプログラム

「ボタンBを押したとき」のプログラムは変更していません。

「ボタンBを押したとき」のプログラム

「ずっと」のプログラム

ゲーム中であれば、ループを繰り返すようなプログラムに変更しました。
ボールの位置が、LEDの最下段まで来たらゲーム中ではなくなるようにBall()関数で行っています。

「ずっと」のプログラム

ソースコード

Javascript画面に張り付けるだけで動作します。

let on_game = false
let ball_direction_x = 0
let ball_direction_y = 0
let bar_x = 0
let ball_y = 0
let ball_old_y = 0
let ball_x = 0
let ball_old_x = 0
function ball2() {
    ball_old_x = ball_x
    ball_old_y = ball_y
    ball_x += ball_direction_x
    ball_y += ball_direction_y
    if (ball_x == 4) {
        ball_direction_x = -1
    } else if (ball_x == 0) {
        ball_direction_x = 1
    }
    if (ball_y == 3) {
        if (ball_x == bar_x) {
            ball_direction_y = -1
        }
    } else if (ball_y == 0) {
        ball_direction_y = 1
    } else if (ball_y >= 4) {
        on_game = false
    }
}
input.onButtonPressed(Button.A, function () {
    if (bar_x != 0) {
        led.unplot(bar_x, 4)
        bar_x += -1
        led.plot(bar_x, 4)
    }
    if (ball_x == bar_x && ball_y == 3) {
        ball_direction_y = -1
    }
})
input.onButtonPressed(Button.B, function () {
    if (bar_x != 4) {
        led.unplot(bar_x, 4)
        bar_x += 1
        led.plot(bar_x, 4)
    }
    if (ball_x == bar_x && ball_y == 3) {
        ball_direction_y = -1
    }
})
ball_x = 1
ball_y = 0
ball_old_x = 0
ball_old_y = 0
ball_direction_x = 1
ball_direction_y = 1
bar_x = 2
on_game = false
basic.forever(function () {
    basic.showNumber(3)
    basic.showNumber(2)
    basic.showNumber(1)
    basic.showNumber(0)
    basic.showLeds(`
        . . . . .
        . . . . .
        . . . . .
        . . . . .
        . . . . .
        `)
    on_game = true
    led.plot(bar_x, 4)
    while (on_game == true) {
        ball2()
        led.plot(ball_x, ball_y)
        led.unplot(ball_old_x, ball_old_y)
        basic.pause(1000)
    }
    basic.showString("Game Over!")
    control.reset()
})
0 Shares
コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

You May Also Like