用JavaScript实现打地鼠游戏

源代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
    padding: 0;
    margin: 0;
}

.wrap {
    width: 800px;
    height: 600px;
    margin: 30px auto;
    
}

.wrap h1 {
    text-align: center;
    font-size: 40px;
}

.wrap .area {
    width: 800px;
    height: 550px;
    background-color: lightblue;
    position: relative;
}

.wrap button {
    width: 200px;
    height: 50px;
    display: block;
    font-size: 30px;
    margin: 0 auto;
}

.wrap .area img.mouse {
    width: 80px;
    height: 100px;
    position: absolute;
    left: 0;
    top: 0;
}
</style>
</head>
<body>
<div class="wrap">
    <h1>0</h1>
    <div class="area">
        <!--<img src="mouse.png" alt="" class="mouse">-->
    </div>
    <b
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用JavaScript实现打地鼠游戏代码示例: ```html <!DOCTYPE html> <html> <head> <title>打地鼠游戏</title> <style type="text/css"> #container { width: 500px; height: 500px; border: 1px solid black; position: relative; } #mouse { width: 50px; height: 50px; background-color: brown; border-radius: 50%; position: absolute; display: none; } </style> </head> <body> <h1>打地鼠游戏</h1> <p>点击开始游戏按钮开始游戏</p> <button onclick="start()">开始游戏</button> <div id="container"></div> <script type="text/javascript"> var container = document.getElementById("container"); var mouse = document.getElementById("mouse"); var score = 0; var timer; function start() { timer = setInterval(showMouse, 1000); } function showMouse() { var left = Math.floor(Math.random() * 450); var top = Math.floor(Math.random() * 450); mouse.style.left = left + "px"; mouse.style.top = top + "px"; mouse.style.display = "block"; setTimeout(hideMouse, 500); } function hideMouse() { mouse.style.display = "none"; } function hitMouse() { score++; document.getElementById("score").innerHTML = "得分:" + score; hideMouse(); } mouse.onclick = hitMouse; container.appendChild(mouse); </script> <p id="score">得分:0</p> </body> </html> ``` 这个游戏实现主要是通过JavaScript来控制地鼠的出现和消失,并且在地鼠被点击时增加得分。具体实现过程如下: 1. 首先在HTML文件中创建一个容器div,用来放置地鼠,以及一个按钮和一个得分显示区域。 2. 在CSS文件中设置容器div的样式,包括宽度、高度、边框等。 3. 在JavaScript文件中定义变量container和mouse,分别表示容器div和地鼠。 4. 定义变量score和timer,分别表示得分和计时器。 5. 定义函数start,用来启动游戏,其中使用setInterval函数来定时调用showMouse函数。 6. 定义函数showMouse,用来显示地鼠,其中使用Math.random函数来生成随机的left和top值,然后设置地鼠的位置和显示状态,并且使用setTimeout函数来定时调用hideMouse函数。 7. 定义函数hideMouse,用来隐藏地鼠。 8. 定义函数hitMouse,用来处理地鼠被点击的事件,其中增加得分并且隐藏地鼠。 9. 将hitMouse函数绑定到地鼠的onclick事件上。 10. 将地鼠添加到容器div中。 11. 在HTML文件中添加得分显示区域,并且在JavaScript文件中更新得分。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值