Button id matching game chat GPT add score 1
<!DOCTYPE html>
<html>
<head>
<title>Match Button Pairs Game</title>
<style>
.btn {
padding: 10px 20px;
margin: 5px;
font-size: 16px;
transition: all 0.3s;
}
.hidden {
opacity: 0;
pointer-events: none;
}
.matched {
background-color: lightgreen;
transform: scale(1.1);
}
.selected {
background-color: yellow;
}
</style>
</head>
<body>
<h2>Match Score: <span id="score">0</span></h2>
<button class="btn" id="btn1" onclick="handleClick('btn1')">Button 1</button>
<button class="btn" id="btn1" onclick="handleClick('btn1')">Button 1</button>
<button class="btn" id="btn2" onclick="handleClick('btn2')">Button 2</button>
<button class="btn" id="btn2" onclick="handleClick('btn2')">Button 2</button>
<script>
let firstSelected = null;
let score = 0;
let matchesFound = 0;
const totalPairs = 2; // Since we have 2 pairs (btn1 and btn2)
function handleClick(btnId) {
const button = event.target;
// Ignore if button is already matched or is the same as first selection
if (button.classList.contains('matched') ||
button.classList.contains('selected')) {
return;
}
// If no button is currently selected
if (firstSelected === null) {
firstSelected = button;
button.classList.add('selected');
return;
}
// If we're selecting the second button
button.classList.add('selected');
// Check for match
if (firstSelected.id === button.id) {
// Match found
score += 1;
document.getElementById('score').textContent = score;
matchesFound++;
// Mark both as matched
firstSelected.classList.remove('selected');
firstSelected.classList.add('matched');
button.classList.remove('selected');
button.classList.add('matched');
// Reset selection
firstSelected = null;
// Check if all pairs found
if (matchesFound === totalPairs) {
setTimeout(() => {
alert(`Game Over! Your score: ${score}`);
resetGame();
}, 500);
}
} else {
// No match
setTimeout(() => {
firstSelected.classList.remove('selected');
button.classList.remove('selected');
firstSelected = null;
}, 1000);
}
}
function resetGame() {
// Reset all buttons
document.querySelectorAll('.btn').forEach(btn => {
btn.classList.remove('matched', 'selected');
});
firstSelected = null;
matchesFound = 0;
score = 0;
document.getElementById('score').textContent = score;
}
</script>
</body>
</html>
Comments
Post a Comment