今回作るピンポンゲーム
必要なもの
micro:bitだけあれば動作します。スピーカーなど特別なものは必要ありません。
「最初だけ」のプログラム
ボールの位置、ボールのひとつ前の位置、ボールの進行方向、バーの位置を初期化しています。
「ボタンAを押したとき」のプログラム
「ボタンAを押したとき」の動作として、下記を行っています。
- バーを左に動かすための処理
- バーとボールの位置を確認してボールを弾き返せる場合はボールの進行方向を逆にする処理
「ボタンBを押したとき」のプログラム
「ボタンBを押したとき」の動作として、下記を行っています。
- バーを右に動かすための処理
- バーとボールの位置を確認してボールを弾き返せる場合はボールの進行方向を逆にする処理
「ずっと」のプログラム
ボールの動作と表示の処理を行っています。
ボールの動作は、Ball()関数で行っています。
- ボールが左右の端まで進んだ場合に、進行方向を逆にする処理
- ボールが上下の端まで進んだ場合に、進行方向を逆にする処理
- バーとボールの位置を確認してボールを弾き返せる場合はボールの進行方向を逆にする処理
ソースコード
Javascript画面に張り付けるだけで動作します。
let ball_direction_x = 0
let ball_direction_y = 0
let bar_x = 0
let ball_old_y = 0
let ball_y = 0
let ball_old_x = 0
let ball_x = 0
function ball() {
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
}
}
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
led.plot(bar_x, 4)
basic.forever(function () {
ball()
led.plot(ball_x, ball_y)
led.unplot(ball_old_x, ball_old_y)
basic.pause(1000)
})