この記事を三行にまとめると
CPUとじゃんけんして勝ち負けを決めるだけ5回連続であいこになる確率は約0.4%
誰も勝てない、コイツには
この記事は以下の動画の中に出てきたサンプルコードを載せたものです。コピペなどが必要なときに使ってください。
HTML
<div id="container">
<div id="display">
<img src="" width="150" id="cpu" class="hidden">
<span id="text">じゃんけん</span>
</div>
<div id="buttons">
<img src="r.png" data-sign="r">
<img src="s.png" data-sign="s">
<img src="p.png" data-sign="p">
</div>
<div id="result"></div>
</div>
CSS
#container {
text-align: center;
margin: 20px 0;
}
#display {
display: flex;
font-size: 48px;
height: 200px;
justify-content: center;
align-items: center;
}
#buttons {
display: grid;
column-gap: 50px;
place-content: center;
grid-template-columns: repeat(3, 110px);
}
img[data-sign] {
width: 100px;
height: 100px;
opacity: 0.6;
border: 5px solid white;
border-radius: 50%;
}
img[data-sign].hold {
opacity: 1;
border-color: red;
}
img[data-sign]:hover {
opacity: 1;
cursor: pointer;
}
img[data-sign]:active {
position: relative;
top: 2px;
}
#result {
margin-top: 20px;
font-size: 24px;
}
.hidden {
display: none!important;
}
JavaScript
const cpu = document.getElementById('cpu');
const text = document.getElementById('text');
const result = document.getElementById('result');
const buttons = document.querySelectorAll('img[data-sign]');
const cpusign = ['r', 's', 'p'];
buttons.forEach((button) => {
button.onclick = (e) => {
n = Math.floor(Math.random() * cpusign.length);
cpu.src = cpusign[n] + '.png';
cpu.classList.remove('hidden');
text.classList.add('hidden');
e.target.classList.add('hold');
match = e.target.dataset.sign + cpusign[n];
if(match[0] == match[1]) {
text.innerText = 'あいこで';
} else {
judge = ['rs', 'sp', 'pr'].includes(match) ? '勝ち' : '負け';
result.innerText = `あなたの${judge}です`;
text.innerText = 'じゃんけん';
}
setTimeout(() => {
text.classList.remove('hidden');
cpu.classList.add('hidden');
e.target.classList.remove('hold');
result.innerText = '';
}, 1500);
}
});
(おまけ)絶対あいこになるじゃんけん
const cpu = document.getElementById('cpu');
const text = document.getElementById('text');
const result = document.getElementById('result');
const buttons = document.querySelectorAll('img[data-sign]');
buttons.forEach((button) => {
button.onclick = (e) => {
cpu.src = e.target.dataset.sign + '.png';
cpu.classList.remove('hidden');
text.classList.add('hidden');
e.target.classList.add('hold');
text.innerText = 'あいこで';
setTimeout(() => {
text.classList.remove('hidden');
cpu.classList.add('hidden');
e.target.classList.remove('hold');
result.innerText = '';
}, 1500);
}
});