じゃんけんアプリ
選択してください:
以下がじゃんけんアプリのコードです。詳しい解説はコメントで示しています。
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>じゃんけんアプリ</title>
<style>
/* 結果表示用のスタイル */
#result { font-size: 2em; margin-top: 1em; width: fit-content; }
#result.success { color: green; }
#result.failure { color: red; }
/* 負けメッセージ用のスタイル */
#loser { font-size: 4em; color: red; transform: rotate(0); transition: transform .5s ease-in-out; }
#loser.rotate { transform: rotate(1800deg); }
</style>
</head>
<body>
<h1>じゃんけんアプリ</h1>
<p>選択してください:</p>
<button onclick="play('グー👊')">グー✊</button>
<button onclick="play('チョキ✌️')">チョキ✌️</button>
<button onclick="play('パー🖐️')">パー✋</button>
<div id="result"></div>
<div id="loser"></div>
<script>
// 勝利メッセージ
const messages = [
"がんばれ〜!",
"すごい〜!",
"素晴らしい〜!",
"きょうも一日がんばろっ!",
"きみは勇者だ!",
"世界はきみを待っている!",
"地球を救うのはきみだ!",
"できる!",
"最高のパフォーマンスだ!",
];
// play関数:じゃんけんを実行
function play(hand) {
// プレイヤーの手を表示
const resultDiv = document.querySelector("#result");
resultDiv.innerHTML = `あなたの手:${hand}`;
// コンピューターの手をランダムに選択
const hands = ["グー👊", "チョキ✌️", "パー🖐️"];
const computerHand = hands[Math.floor(Math.random() * 3)];
resultDiv.innerHTML += `<br>コンピューターの手:${computerHand}`;
// 勝敗判定
const result = judge(hand, computerHand);
// 勝った時のメッセージ
if (result > 0) {
const message = messages[Math.floor(Math.random() * messages.length)];
resultDiv.innerHTML += `<br><span class="success">${message}</span>`;
}
// 負けた時の処理
else {
const loserDiv = document.querySelector("#loser");
loserDiv.innerHTML = "負け!出直してこい😡";
// テキストを回転するアニメーション
loserDiv.classList.add("rotate");
// 5秒後にアニメーションを終了
setTimeout(() => {
loserDiv.classList.remove("rotate");
}, 5000);
}
}
// judge関数:じゃんけんの勝敗を判定
function judge(playerHand, computerHand) {
if (playerHand === "グー👊" && computerHand === "チョキ✌️" ||
playerHand === "チョキ✌️" && computerHand === "パー🖐️" ||
playerHand === "パー🖐️" && computerHand === "グー👊") {
return 1;
}
else if (playerHand === computerHand) {
return 0;
}
else {
return -1;
}
}
</script>
</body>
</html>
```
アプリを実行すると、以下のような画面が表示されます。

ユーザーは、グー、チョキ、パーの中から1つを選択することができます。選択された手と、コンピューターの手が表示されます。勝った時には、ランダムな応援メッセージが表示されます。負けた時には、「負け!出直してこい😡」という大きな赤文字が高速回転します。
アプリには、以下のようなセキュリティ上の配慮がなされています。
- evalは使用していません。
- 他のサイトに遷移する機能もありません。
- alertを使用していません。
- リダイレクト機能もありません。
- XSS攻撃などの脆弱性に対する対策は、不必要な入力チェックやエスケープ処理を実施することで、完全ではありませんが最小限の対策をしています。