Create and click on 9 image holes, keep score and time limit
HTML
<h1>🎯 Whack-Nanci</h1>
<div id="info">
<div id="score">Score: 0</div>
<div id="time">Starting in 3</div>
</div>
<div id="game"></div>
<div id="message"></div>
CSS
body{
font-family:Arial;
background:#f5f5f5;
text-align:center;
margin:0;
padding:20px;
}
#info{
display:flex;
justify-content:center;
gap:40px;
margin-bottom:20px;
font-size:24px;
font-weight:bold;
}
#game{
width:340px;
margin:auto;
display:grid;
grid-template-columns:repeat(3,100px);
gap:20px;
}
.hole{
width:100px;
height:100px;
background:#ccc;
border-radius:50%;
position:relative;
overflow:hidden;
cursor:pointer;
}
.nanci{
position:absolute;
width:100%;
height:100%;
display:flex;
align-items:center;
justify-content:center;
transform:translateY(100%);
transition:0.2s;
}
.hole.active .nanci{
transform:translateY(0%);
}
.nanci img{
width:80px;
height:80px;
object-fit:cover;
border-radius:50%;
}
#message{
margin-top:20px;
font-size:28px;
color:green;
font-weight:bold;
}
JavaScript
const game =
document.getElementById("game");
const scoreText =
document.getElementById("score");
const timeText =
document.getElementById("time");
const message =
document.getElementById("message");
let score = 0;
let time = 30;
let currentHole = null;
let timer;
let nanciInterval;
/* 创建9个洞 */
for(let i = 0; i < 9; i++){
const hole =
document.createElement("div");
hole.className = "hole";
hole.innerHTML =
'<div class="nanci">' +
'<img src="https://community.robotime.com/uploads/default/original/3X/a/8/a8afc5aa21258dbe0ad6175b472362c6bf1066e1.jpeg">' +
'</div>';
hole.addEventListener(
"click",
function(){
if(hole.classList.contains(
"active")){
score++;
scoreText.innerHTML =
"Score: " + score;
hole.classList.remove(
"active");
}
});
game.appendChild(hole);
}
const holes =
document.querySelectorAll(".hole");
/* 321倒计时 */
let countdown = 3;
const countdownInterval =
setInterval(()=>{
countdown--;
if(countdown > 0){
timeText.innerHTML =
"Starting in " + countdown;
}else{
clearInterval(
countdownInterval);
startGame();
}
},1000);
/* 开始游戏 */
function startGame(){
timeText.innerHTML =
"Time: 30";
nanciInterval =
setInterval(randomNanci,700);
timer =
setInterval(function(){
time--;
timeText.innerHTML =
"Time: " + time;
if(time <= 0){
clearInterval(timer);
clearInterval(
nanciInterval);
message.innerHTML =
"🎉 Game Over! Final Score: "
+ score;
}
},1000);
}
/* 随机出现 */
function randomNanci(){
if(currentHole){
currentHole.classList.remove(
"active");
}
const index =
...