ミッション一覧に戻る
じゃんけん

じゃんけん

03/26 13:45
ミッション内容

「じゃんけん」

ミッション:グー・チョキ・パーのボタンを押してCPUとじゃんけんしよう!

コードを写そう

HTMLタブに下のコードを貼り付けてください。

html
<p>じゃんけん!</p>
<button class="hand" data-hand="グー">✊ グー</button>
<button class="hand" data-hand="チョキ">✌ チョキ</button>
<button class="hand" data-hand="パー">🖐 パー</button>
<p id="result"></p>

JSタブに下のコードを貼り付けてください。

js
const hands = ['グー', 'チョキ', 'パー'];
const result = document.querySelector('#result');

document.querySelectorAll('.hand').forEach(function(btn) {
  btn.addEventListener('click', function() {
    const player = btn.dataset.hand;
    const cpu = hands[Math.floor(Math.random() * 3)];

    let judge = '';
    if (player === cpu) {
      judge = 'あいこ!';
    } else if (
      (player === 'グー'   && cpu === 'チョキ') ||
      (player === 'チョキ' && cpu === 'パー')   ||
      (player === 'パー'   && cpu === 'グー')
    ) {
      judge = '勝ち!🎉';
    } else {
      judge = '負け...😢';
    }

    result.textContent = 'あなた:' + player + ' CPU:' + cpu + ' → ' + judge;
  });
});

ボタンを押してCPUとじゃんけんできることを確認してください。

コードを読み解こう

data-hand 属性でボタンに情報を持たせる

html
<button class="hand" data-hand="グー">✊ グー</button>

data-hand="グー" はHTMLのカスタム属性です。data- で始まる名前なら自由に情報を持たせられます。

js
const player = btn.dataset.hand;

JavaScriptでは btn.dataset.handdata-hand の値("グー" など)を取り出せます。forEach でボタンを1つずつ処理するとき、どのボタンが押されたかをこの方法で判定しています。

CPUの手をランダムに決める

js
const hands = ['グー', 'チョキ', 'パー'];
const cpu = hands[Math.floor(Math.random() * 3)];

hands は3つの文字列を並べた配列です。hands[0]'グー'hands[1]'チョキ'hands[2]'パー' です。

Math.random() * 3 で0〜2.99...のランダムな小数を作り、Math.floor() で切り捨てて0・1・2のどれかを得ます。これを添え字として使うことで、毎回ランダムな手を引き出せます。

勝敗判定の if / else if / else

js
if (player === cpu) {
  judge = 'あいこ!';
} else if (
  (player === 'グー'   && cpu === 'チョキ') ||
  (player === 'チョキ' && cpu === 'パー')   ||
  (player === 'パー'   && cpu === 'グー')
) {
  judge = '勝ち!🎉';
} else {
  judge = '負け...😢';
}

&& は「かつ」、|| は「または」を意味します。グーはチョキに勝つ、チョキはパーに勝つ、パーはグーに勝つ、の3パターンを || でつないでいます。

改造しよう

ミッション:勝敗のメッセージを変えよう

js
judge = '勝ち!🎉';   ← 勝ったときのメッセージ
judge = '負け...😢';  ← 負けたときのメッセージ
judge = 'あいこ!';   ← あいこのときのメッセージ

自己チェック

  • [ ] 3つのボタンでじゃんけんできる
  • [ ] CPUの手がランダムに変わる
  • [ ] 勝ち・負け・あいこが正しく判定される