Simple HTML Simon Says Game - Learn to Code with HTML, CSS, and JavaScript
<!DOCTYPE html>
<html>
<head>
<title>Simon Says</title>
<style type="text/css">
div {
width: 100px;
height: 100px;
background-color: #000;
border-radius: 50%;
display: inline-block;
margin: 5px;
}
</style>
</head>
<body>
<h1>Simon Says!</h1>
<p>Repeat the pattern of lights by pressing the buttons in order.</p>
<div id="button-1"></div>
<div id="button-2"></div>
<div id="button-3"></div>
<div id="button-4"></div>
<script type="text/javascript">
// An array to store the order of the buttons
var order = [];
// A variable to keep track of the player's progress
var progress = 0;
// A variable to store the button elements
var buttons = [
document.getElementById("button-1"),
document.getElementById("button-2"),
document.getElementById("button-3"),
document.getElementById("button-4")
];
// A function to generate a random order
function generateOrder() {
for (var i = 0; i < 5; i++) {
order.push(Math.floor(Math.random() * 4));
}
}
// A function to blink the button
function blink(button) {
button.style.backgroundColor = '#FFF';
setTimeout(function() {
button.style.backgroundColor = '#000';
}, 500);
}
// A function to show the order to the player
function showOrder() {
var i = 0;
var interval = setInterval(function() {
blink(buttons[order[i]]);
i++;
if (i >= order.length) {
clearInterval(interval);
}
}, 1000);
}
// A function to check if the player's input is correct
function checkAnswer(input) {
if (input === order[progress]) {
progress++;
if (progress >= order.length) {
alert('You won!');
reset();
}
} else {
alert('Game over!');
reset();
}
}
// A function to reset the game
function reset() {
progress = 0;
order = [];
generateOrder();
showOrder();
}
// Add event listeners to the buttons
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function(e) {
checkAnswer(e.target.id.split('-')[1]);
});
}
// Start the game
generateOrder();
showOrder();
</script>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lmc2 著作权归作者所有。请勿转载和采集!