作品一覧に戻る
じゃんけん

じゃんけん

秋山宗太郎 04/03 15:24
アプリを動かす
コードを見る
<p>じゃんけん!</p>
<button class="hand" data-hand="グー">✊ グー</button>
<button class="hand" data-hand="チョキ">✌ チョキ</button>
<button class="hand" data-hand="パー">🖐 パー</button>
<p id="result"></p>
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;
  });
});