源码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>气球游戏</title>
</head>
<body>
<div id="app"></div>
<script>
//获取变量
var app = document.getElementById('app');
//构造函数创造类
function Balloon(id, dom, top) {
this.id = id;
this.dom = dom;
this.x = 125;
this.y = parseInt(500 / 3);
this.ball = document.createElement('div');
this.dom.appendChild(this.ball);
this.left = -125;
this.top = top;
this.remove = true; //可以移动
this.text = 'abcdefghijklmnopqrstuvwxyz';
this.letter = this.text[parseInt(Math.random() * 26)].toUpperCase();
var me = this;
//气球移动
this.move = function() {
this.left++;
if (this.left > document.documentElement.clientWidth) {
this.remove = false;
}
this.ball.style.left = this.left + 'px';
}
//移除气球
this.die = function() {
this.dom.removeChild(this.ball);
}
//绘制
this.init = function() {
this.ball.style.width = '125px';
this.ball.style.height = '166px';
this.ball.style.top = this.top + 'px';
this.ball.style.lineHeight = '130px';
this.ball.style.fontSize = '60px';
this.ball.style.fontWeight = 'blod';
this.ball.style.textAlign = 'center';
this.ball.style.position = 'absolute';
this.ball.style.backgroundImage = 'url(./image/balloon.jpg)';
this.ball.style.backgroundPositionX = -this.x * (this.id % 4 - 1) + 'px';
this.ball.style.backgroundPositionY = -this.y * parseInt(this.id / 4) + 'px';
this.ball.innerHTML = this.letter;
}
}
//创建数组容器存储气球
var arr = [];
var time = 0;
var score = 0;
var name = prompt('亲爱的玩家,输入您的名字即可开启游戏!');
var a = setInterval(function() {
if (time % 200 === 0) {
var demo = new Balloon(Math.ceil(Math.random()*12), app, Math.random() * 250 + 50);
demo.move();
demo.init();
arr.push(demo);
}
for (var i = arr.length - 1; i >= 0; i--) {
if (arr[i].remove) {
arr[i].move();
} else {
arr[i].die();
arr.splice(i, 1);
console.log(arr);
}
}
time++;
if (time > 10000) {
clearInterval(a);
confirm('游戏结束,亲爱的' + name + '您的分数为' + score + '分');
}
console.log(time);
}, 1);
//键盘判断
document.onkeydown = function(e) {
for (var i = arr.length - 1; i >= 0; i--) {
if (arr[i].letter === e.key.toUpperCase()) {
arr[i].remove = false;
score++;
return;
}
}
}
</script>
</body>
</html>
balloon.jpg(附上demo中使用到的一张图片,复制代码就可以运行啦)