用html写一个简单手机小游戏
时间: 2023-10-01 12:07:50 浏览: 58
好的,我可以给你一个简单的示例游戏,使用HTML和JavaScript编写,叫做“点击方块”。
HTML代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>点击方块</title>
<style>
body {
background-color: #f0f0f0;
}
#square {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
</style>
</head>
<body>
<div id="square"></div>
<script src="game.js"></script>
</body>
</html>
```
JavaScript代码:
```javascript
var score = 0;
var time = 10;
var timer;
// 随机生成方块位置
function randomSquare() {
var square = document.getElementById("square");
var x = Math.floor(Math.random() * 80);
var y = Math.floor(Math.random() * 80);
square.style.top = x + "%";
square.style.left = y + "%";
}
// 点击方块增加得分
function addScore() {
score++;
document.getElementById("score").innerHTML = score;
randomSquare();
}
// 倒计时结束游戏
function endGame() {
clearInterval(timer);
alert("游戏结束,得分:" + score);
}
// 开始游戏
function startGame() {
score = 0;
time = 10;
document.getElementById("score").innerHTML = score;
document.getElementById("time").innerHTML = time;
timer = setInterval(function() {
time--;
document.getElementById("time").innerHTML = time;
if (time == 0) {
endGame();
}
}, 1000);
randomSquare();
}
// 页面加载完成后开始游戏
window.onload = startGame;
```
这个游戏的规则很简单,页面上有一个红色方块,每次点击方块可以得到一分,游戏时间为10秒,时间结束后游戏结束,弹出得分。
你可以将以上代码保存为`index.html`和`game.js`文件,然后在浏览器中打开`index.html`文件开始游戏。