我是一個從汽車行業轉行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
解壓後放在代碼目錄的同級即可使用。
你也來試一下吧