我是一个从汽车行业转行IT的项目经理,我是Edward,如想了解更多,请关注我的公众号【转行项目经理的逆袭之路】。现在我终于知道了为什么前几年网页小游戏如雨后春笋般层出不穷,原来是因为JS强大的网页编程功能让动态网页成为了可能,今天就来带大家实现一个僵尸入侵的页面小游戏。
代码实现:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
body {
background-image: url(../zombimgs/bg1.jpg);
/* background-size: 100px 200px; */
/* 超出边框的不显示 */
overflow: hidden;
}
img {
/* 为了灵活控制僵尸位置设置绝对定位 */
position: absolute;
width: 60px;
height: 60px;
}
#s_h3 {
float: left;
background-color: #62B5EC;
}
#f_h3 {
float: right;
background-color: #62B5EC;
}
</style>
</head>
<body>
<h3 id="s_h3">成功数量:0</h3>
<h3 id="f_h3">失败数量:0</h3>
<script src="../js/jquery-1.4.2.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
//声明统计成功失败的变量
var sCount = 0
var fCount = 0
//得到窗口尺寸
var w = $(window).width()
var h = $(window).height()
//把窗口尺寸设置给body的背景图片尺寸
$("body").css("background-size", w + "px " + h + "px")
//添加窗口尺寸改变事件
onresize = function() {
//得到窗口尺寸
w = $(window).width()
h = $(window).height()
//把窗口尺寸设置给body的背景图片尺寸
$("body").css("background-size", w + "px " + h + "px")
}
//开启定时器 往页面中添加僵尸图片
var timer=setInterval(function() {
//让僵尸的种类和干掉的僵尸数量建立关系
//sCount 0-19 0
//20-39 1
//40-59 2
//60... 3
var type = parseInt(sCount / 20)
if (type > 3) {
type = 3
}
var img = $("<img src='../zombimgs/zomb" + type + ".png'>")
//给僵尸图片设置血量属性
img.attr("hp", type + 1)
img.attr("total_hp",type+1) //给僵尸添加总血量
$("body").append(img)
//得到僵尸的left和top值
var left = w;
var top = parseInt(Math.random() * (h - 60))
//把left和top赋值给图片样式
img.css({
"left": left + "px",
"top": top + "px"
})
//只能出来一个,不对
// $("img").css("left",w+"px")
// $("img").css("top",parseInt(Math.random()*(h-60))+"px")
//给僵尸图片添加鼠标按下事件
img.mousedown(function() {
//得到当前血量
var hp = img.attr("hp")
//减掉一滴血
hp--
//把新的血量给回僵尸
img.attr("hp", hp)
//让僵尸的透明度和当前血量建立关系 当前血量/总血量 1/3
img.css("opacity",hp/img.attr("total_hp"))
if (hp <= 0) {
img.remove()
//成功数量+1 并显示
sCount++
$("#s_h3").text("成功数量:" + sCount)
}
})
}, 500)
//创建移动僵尸定时器
setInterval(function() {
//移动僵尸
//得到所有的僵尸图片并遍历
$("img").each(function() {
//取出僵尸图片当前的left值 去掉px
var left = parseInt($(this).css("left"))
//通过移动速度控制游戏平衡性
//0-19 1 20-39 2 40-59 3
// left -= 1+parseInt(sCount/20)
left -= 1
$(this).css("left", left + "px")
//判断僵尸移动到的位置到了最左边 删除僵尸
if (left <= 100) {
$(this).remove()
fCount++
$("#f_h3").text("失败数量:" + fCount)
if(fCount>=10){
//弹出询问是否重新开始的提示框
if(confirm("游戏结束!重新开始吗?")){
//刷新页面
location.reload()
}
//如果点击取消 不重新开始 删除所有僵尸图片
$("img").remove()
//停止添加僵尸图片的定时器
clearInterval(timer)
}
}
})
}, 10)
</script>
</body>
</html>
让我们一起看一下效果:
代码中关键的地方都给出了注释,相信你稍稍花一点时间就可以理解。仅仅100余行代码就可以实现一个内容丰满的小游戏,这个轻量级的表现是Java无法做到的,放在自家浏览器的console控制台里面就可以运行。
素材获取在这里:
链接:https://pan.baidu.com/s/16RpyIKbaGagtLqXZAch0rg
提取码:mwqw
解压后放在代码目录的同级即可使用。
你也来试一下吧