<script>
// 飞机大战:
// 引擎:难度选择,logo,loading,游戏开始
// 我的飞机:创建,跟随鼠标移动,开火
// 我的子弹:创建,移动,死亡
// 敌机:创建,移动,碰撞检测,死亡
// 引擎:
function Engine(){
// E1.选择元素
this.li = document.querySelectorAll(".options li");
this.main = document.getElementById("body_main");
// E2.绑定事件
this.init();
}
Engine.prototype.init = function(){
var that = this;
for(var i=0;i<this.li.length;i++){
this.li[i].onclick = function(){
// E3.存储难度,删除按钮组
that.v = this.value;
this.parentNode.remove();
// E4.创建logo和loading
that.load();
}
}
}
Engine.prototype.load = function(){
this.logo = createDiv("logo");
this.loading = createDiv("loading");
// var loading=document.createElement("loading");
// loading.className="loading";
// this.main.appendChild(loading);
// 切换照片 属性精确
// var logo=document.createElement("logo");
// logo.className="logo";
// this.main.appendChild(logo);
var i=0;
// loading图的切换
var i = 0;
this.loadingTimer = setInterval(() => {
this.loading.style.backgroundImage = `url(images/loading${(i++)%3+1}.png)`;
}, 300);
// 背景图的运动
var j=0;
setInterval(()=>{
this.main.style.backgroundPositionY = (j+=2)+"px";
},30)
setTimeout(() => {
// E5.游戏开始
this.gameStart()
}, 300);
}
Engine.prototype.gameStart = function(){
// 删除logo和loading,清除没用的计时器
this.logo.remove()
this.loading.remove()
clearInterval(this.loadingTimer);
// E6.开始创建我的飞机
plane.init(this.main);
// P3.开火
plane.fire(this.v);
// 敌机
}
// 我的飞机:
var plane = {
// main:document.getElementById("body_main"),
init:function(main){
this.main = main;
// P1.创建我的飞机,设置默认位置
this.ele = createDiv("my-warplain");
this.ele.style.left = (this.main.offsetWidth - this.ele.offsetWidth)/2 + "px";
this.ele.style.bottom = 0;
// P2.跟随鼠标移动
this.move();
},
move:function(){
var that = this;
document.onmousemove = function(eve){
var e = eve || window.event;
// 计算位置
var l = e.clientX - that.main.offsetLeft - that.ele.offsetWidth/2;
var t = e.clientY - that.ele.offsetHeight/2;
// 边界限定
if(l<0) l=0;
if(t<0) t=0;
if(l>that.main.offsetWidth - that.ele.offsetWidth){
l=that.main.offsetWidth - that.ele.offsetWidth
}
// 生效位置
that.ele.style.left = l + "px";
that.ele.style.top = t + "px";
}
},
fire:function(v){
// 根据难度,持续开火
setInterval(() => {
new Bullet()
}, 1000/v);
}
}
// 我的子弹:
function Bullet(){
}
Bullet.prototype = {
constructor:Bullet,
init:function(){
}
}
// 敌机:
class Enemy{
constructor(){
}
init(){
}
}
function createDiv(classname){
var div = document.createElement("div");
div.className = classname;
document.getElementById("body_main").appendChild(div);
return div;
}
new Engine();
</script>