6-Day2
注意
js样式属性值必须是字符串,有单位
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
#game{
width: 800px;
height: 600px;
background: url(images/sky.png);
background-position-x: 50px;
position: relative;
overflow: hidden;
}
#bird{
width: 34px;
height: 25px;
background: url(images/birds.png) -8px -10px;
top:100px;
left: 100px;
position: absolute;
}
</style>
</head>
<body>
<div id="game">
<div id="bird"></div>
</div>
<script>
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;
}
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;
//上管的高度
pipe.uHeight =200 + parseInt(Math.random() * 100)
//下管的高度 需求:管道之间保持200距离
pipe.dHeight = 600 - pipe.uHeight -200;
//下管的位置
pipe.dTop = pipe.uHeight + 200;
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) no-repeat center bottom';
game.appendChild(uPipe);
var dPipe = document.createElement('div');
dPipe.style.width = '52px';
dPipe.style.height = pipe.uHeight + 'px';
dPipe.style.background = 'url(images/pipe1.png)';
dPipe.style.position = 'absolute';
dPipe.style.top = pipe.dTop + 'px';
dPipe.style.left = pipe.x + 'px';
game.appendChild(dPipe);
//让管道动起来
setInterval(function() {
if (running) {
pipe.x -= 2;
uPipe.style.left = pipe.x + 'px';
dPipe.style.left = pipe.x + 'px';
if (pipe.x < -52) {
pipe.x = 800;
}
var uCheck =bird.x + 34 > pipe.x && bird.x < pipe.x + 52 && bird.y <pipe.uHeight;
var dCheck =bird.x + 34 > pipe.x && bird.x < pipe.x + 52 && bird.y > pipe.uHeight + 200;
if (uCheck || dCheck) {
running = false;
}
}
},20)
}
//调用
createPipe(400);
createPipe(600);
createPipe(800);
createPipe(1000);
</script>
</body>
</html>