LoginSignup
2
3

More than 5 years have passed since last update.

GBDKによるゲームボーイソフト制作-3回 キー入力-

Last updated at Posted at 2018-03-30

前回:GBDKによるゲームボーイソフト制作-2回 文字を出してみる-
次回:GBDKによるゲームボーイソフト制作-4回 背景表示-

記事の内容

ゲームボーイのキー入力処理を試してみた記録。

ソースコード

key_input.c
#include <stdio.h>
#include <gb/gb.h>

void main() {
    UINT8 joypad_result;

    while(1) {
        joypad_result = joypad();

        if (joypad_result & J_START) {
            printf("PUSH START\n");
        }
        if (joypad_result & J_SELECT) {
            printf("PUSH SELECT\n");
        }
        if (joypad_result & J_B) {
            printf("PUSH B\n");
        }
        if (joypad_result & J_A) {
            printf("PUSH A\n");
        }
        if (joypad_result & J_DOWN) {
            printf("PUSH DOWN\n");
        }
        if (joypad_result & J_UP) {
            printf("PUSH UP\n");
        }
        if (joypad_result & J_LEFT) {
            printf("PUSH LEFT\n");
        }
        if (joypad_result & J_RIGHT) {
            printf("PUSH RIGHT\n");
        }
    }
}

実行結果

key_input.png

ゲームボーイの各キーに対応した入力を行うと、押されたキーに応じてprintfで指定した1行のメッセージが出力される。

解説のようなもの

2行目

ゲームボーイのキー入力には「gb/gb.h」のincludeが必要。

7行目 while

ゲームプログラムで定番のループ処理。

8行目 joypad関数

今回の本丸。
「gb/gb.h」で以下のように定義されている。

/** Reads and returns the current state of the joypad.
    Follows Nintendo's guidelines for reading the pad.
    Return value is an OR of J_*
    @see J_START
*/
UINT8
joypad(void) NONBANKED;

ざっくり意訳

現在入力されているキー入力状態が数値で返ってくる。
返り値は「J_*」で定義されたキーごとのビット情報を表したもの。

「J_*」の各定数は「gb/gb.h」の上のほうで定義されている。

/** Joypad bits.
    A logical OR of these is used in the wait_pad and joypad
    functions.  For example, to see if the B button is pressed
    try

    UINT8 keys;
    keys = joypad();
    if (keys & J_B) {
        ...
    }

    @see joypad
 */
#define J_START      0x80U
#define J_SELECT     0x40U
#define J_B          0x20U
#define J_A          0x10U
#define J_DOWN       0x08U
#define J_UP         0x04U
#define J_LEFT       0x02U
#define J_RIGHT      0x01U

使い方(判定方法)はこのコメント文の中に書かれている通り。
今回作成したソースコードもこれにならって8キーの分判定処理をしているだけ。

ということで今回はこんな感じで。
このキー入力と前回の文字表示など組み合わせると色々遊べるかも?

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3