Simple Pair game Array function
<!DOCTYPE html>
<html>
<head>
<title>Button Matching Game</title>
<style>
button {
padding: 15px 30px;
font-size: 20px;
margin: 10px;
}
#message {
font-size: 24px;
margin: 20px;
color: green;
}
</style>
</head>
<body>
<h1>Button Matching Game</h1>
<div id="buttons">
<button id="A">A</button>
<button id="Apple">🍎</button>
<button id="B">B</button>
<button id="Ball">🏀</button>
</div>
<p>Score: <span id="score">0</span></p>
<p id="message"></p>
<script>
// Game variables
var score = 0;
var firstClick = null;
var pairs = {
"A": "Apple",
"Apple": "A",
"B": "Ball",
"Ball": "B"
};
var matchedPairs = [];
// Get all buttons
var buttons = document.querySelectorAll("#buttons button");
// Add click handlers
buttons.forEach(function(button) {
button.onPress = function() {
// Skip if already matched
if (matchedPairs.includes(this.id)) return;
// First click
if (firstClick === null) {
firstClick = this;
this.style.opacity = "0.5";
document.getElementById("message").textContent = "Now click its pair!";
}
// Second click
else {
// Check if it's a correct pair
if (pairs[firstClick.id] === this.id) {
score++;
document.getElementById("score").textContent = score;
// Hide matched buttons
firstClick.style.display = "none";
this.style.display = "none";
// Add to matched pairs
matchedPairs.push(firstClick.id);
matchedPairs.push(this.id);
document.getElementById("message").textContent = "Good match!";
// Check if all pairs are matched
if (matchedPairs.length === 4) {
document.getElementById("message").textContent = "You won! All pairs matched!";
}
} else {
document.getElementById("message").textContent = "Wrong pair! Try again!";
firstClick.style.opacity = "1";
}
// Reset for next try
firstClick = null;
}
};
button.addEventListener("click", button.onPress);
});
</script>
</body>
</html>
Comments
Post a Comment