今天我们来做一个简单的js游戏,飞翔的小鸟
首先我们先想一下需要写些什么,
1.小鸟上下的飞行移动,
2.上下障碍物的创建
3.页面障碍物自动从右像左移动,以实现小鸟向前飞的样子
4.游戏结束后,遮罩层显示结束,以及得分
5.小鸟触碰地面,最顶部,以及触碰障碍物时判定游戏结束
首先还是页面的构建,每个人的想法不同,我给大家看一下我的基础界面
接下来我们开始写js代码
先写小鸟在没开始时自动跳动的部分
现在我们写小鸟在点击开始后,跳动的部分
现在创建上下障碍物(柱子),并判断其触碰结束(因为代码长度问题,我先在用代码块来存放)
var creatzz = function (x) {
var zz = {
x: 0,
sheight: 0,
xheight: 0,
}
zz.x = x;
zz.sheight = 50 + Math.floor(Math.random() * 200);
zz.xheight = 600 - 150 - zz.sheight;
//创建上方障碍物
var newszz = document.createElement("div");
newszz.style.height = zz.sheight + "px";
newszz.style.position = "absolute";
newszz.style.width = "52px";
newszz.style.top = "0px";
newszz.style.left = zz.x + "px";
newszz.style.background = "url(images/pipe2.png) no-repeat center bottom";
father.appendChild(newszz);
//创建下方障碍物
var newxzz = document.createElement("div");
newxzz.style.height = zz.xheight + "px";
newxzz.style.position = "absolute";
newxzz.style.width = "52px";
newxzz.style.top = zz.sheight + 150 + "px";
newxzz.style.left = zz.x + "px";
newxzz.style.background = "url(images/pipe1.png) no-repeat center top";
father.appendChild(newxzz);
setInterval(function () {
if (flying) {
zz.x -= 5;
newszz.style.left = zz.x + "px";
newxzz.style.left = zz.x + "px";
if (zz.x < -52) {
zz.x = 1300;
}
}
if (zz.x >= 0 && birds.x >= zz.x + 52) {
count++;
}
//控制小鸟触碰柱子后游戏结束
var ucheck = birds.x + 30 > zz.x && birds.x < zz.x + 52 && birds.y < zz.sheight;
var dcheck = birds.x + 30 > zz.x && birds.x < zz.x + 52 && birds.y + 30 > zz.sheight + 150;
if (ucheck || dcheck) {
flying = false;
mask.style.display = "block";
success.style.display = "block";
results.innerHTML = count;
}
}, 30)
}
//控制柱子分布
creatzz(300);
creatzz(600);
creatzz(900);
creatzz(1200);
creatzz(1400);
}
今天我们就写到这,一个简单的游戏,希望能给你帮助