小鸟游戏
Document
<script>
/*
让小鸟飞起来
1.背景向后移动
*/
//1.获取元素
var game = document.getElementById('game');
var birdEl = document.getElementById('bird');
//以键值对形式保存小鸟和背景的参数
var sky = {
x: 0
}
//初始化bird值
var bird = {
speedX: 5,
speedY: 0,
x: birdEl.offsetLeft,
y: birdEl.offsetTop
}
//判断游戏进程 需要一个状态值
var running = true;
//定义定时器 使游戏背景移动
setInterval(function() {
if (running) {
sky.x -= 5;
game.style.backgroundPositionX = sky.x + 'px';
//实现小鸟的上下移动
//距离 = 时间 * 速度
bird.speedY += 1; //加速度 为 1
bird.y += bird.speedY;
if (bird.y < 0) {
running = false;
bird.y = 0;
}
//当小鸟的offsetTop + 自身的高度 大于背景高度时 游戏停 停止 小鸟固定
if (bird.y + birdEl.offsetHeight > 600) {
running = false;
bird.y = 600 - birdEl.offsetHeight;
}
birdEl.style.top = bird.y + 'px';
}
},20)
//点击文档时,小鸟实现向上运动
document.onclick = function() {
bird.speedY = -10;
}
//创建管道的函数
function createPipe(position) {
//管道有很多参数 水平位置 自身高度 上下两根管子
var pipe = {};
//水平位置
pipe.x = position;
//上管的高度 需求 两个管子的间隔必须200px
pipe.uHeight = 200 + parseInt((Math.random() * 100)) //300 400
//console.log(pipe.uHeight);
//下管的高度
pipe.dHeight = 600 - pipe.uHeight -200; //100 0
//下管的top值
pipe.dTop = pipe.uHeight + 200;
//创建一个div
var uPipe = document.createElement('div');
uPipe.style.width = '52px';
uPipe.style.height = pipe.uHeight + 'px';
uPipe.style.position = 'absolute';
uPipe.style.top = '0px';
uPipe.style.left = pipe.x + 'px';
uPipe.style.background = 'url(../images/pipe2.png) center bottom';
game.appendChild(uPipe);
}
createPipe(400);
</script>