【jQuery】じゃんけんゲームをつくる
jQueryでじゃんけんゲームをつくってみます。
過去、JavaScriptでじゃんけんゲーム、PHPでじゃんけんゲームでも同じものをつくりました。
- HTML
- 5
- JavaScript
- ES2015
- jQuery
- 3.1.1
HTML
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>JavaScriptでじゃんけんゲーム</title>
<script src="janken.js"></script>
</head>
<body>
<p>選んでください。</p>
<button type="button" data-num="1">グー</button>
<button type="button" data-num="2">チョキ</button>
<button type="button" data-num="3">パー</button>
<div id="result"></div>
</body>
</html>
JavaScript
$(function(){
'use strict';
const $els = $('button'),
hand = new Map(),
result = new Map([
[0, 'あいこ'],
[1, '負け'],
[2, '勝ち']
]);
$els.each(function(){
const num = parseInt($(this).val()),
val = $(this).text();
hand.set(num, val);
});
$els.on('click', function(){
const playerSelect = parseInt($(this).val()),
comSelect = Math.floor(Math.random() * 3 + 1),
judge = (playerSelect - comSelect + 3) % 3;
$('#result').html(
`<h2 class="notice">結果</h2>` +
`<p><b>あなた:</b> ${hand.get(playerSelect)}<br>` +
`<b>あいて:</b> ${hand.get(comSelect)}</p>` +
`<p><b>「${result.get(judge)}」</b>です</p>`
);
});
});