ミッション:グー・チョキ・パーのボタンを押してCPUとじゃんけんしよう!
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タブに下のコードを貼り付けてください。
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 属性でボタンに情報を持たせる<button class="hand" data-hand="グー">✊ グー</button>
data-hand="グー" はHTMLのカスタム属性です。data- で始まる名前なら自由に情報を持たせられます。
const player = btn.dataset.hand;
JavaScriptでは btn.dataset.hand で data-hand の値("グー" など)を取り出せます。forEach でボタンを1つずつ処理するとき、どのボタンが押されたかをこの方法で判定しています。
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 / elseif (player === cpu) {
judge = 'あいこ!';
} else if (
(player === 'グー' && cpu === 'チョキ') ||
(player === 'チョキ' && cpu === 'パー') ||
(player === 'パー' && cpu === 'グー')
) {
judge = '勝ち!🎉';
} else {
judge = '負け...😢';
}
&& は「かつ」、|| は「または」を意味します。グーはチョキに勝つ、チョキはパーに勝つ、パーはグーに勝つ、の3パターンを || でつないでいます。
judge = '勝ち!🎉'; ← 勝ったときのメッセージ
judge = '負け...😢'; ← 負けたときのメッセージ
judge = 'あいこ!'; ← あいこのときのメッセージ