先写一个敌机类
/*创建敌机: */function Enemy(blood,speed,imgs){ //敌机left this.left = 0; //敌机top this.top = 0; //敌机血量 this.blood = blood; //敌机速度 this.speed = speed; //敌机图片集合 this.imgs = imgs;//爆炸前和爆炸后}Enemy.prototype = { constructor:Enemy, init:function(){ //创建一个元素 var img = document.createElement('img'); //将图片路径赋值给它 img.src=this.imgs[0]; //插入到game中 Engine.game.appendChild(img); //赋值给敌机的初始图片 this.self = img; //当图片加载完成以后获取图片的高度和宽度 var _this = this;//在函数里面this的指向会改变,所以我们提前报存下来 img.onload = function(){ _this.left = parseInt(Math.random()*(320-img.offsetWidth)); _this.top = -img.offsetHeight; img.style.left = _this.left+'px'; img.style.top = _this.top+'px'; }; //生成敌机编号并放入引擎的bullet中 this.id = Math.random(); Engine.enemy[this.id]=this; }, //子弹移动,定时器都交给引擎去做 move:function(){ this.top+=this.speed; this.self.style.top = this.top+'px'; //越界判断 if(this.top>568+this.self.offsetWidth){ this.destroy(); } }, destroy:function(){ //销毁 //从页面小时 this.self.remove(); //从内存消失 delete Engine.bullet[this.id]; }}
在去创建小型 中型 大型敌机
/*创建所有类型的飞机 */function SmallEnemy(){ var s = parseInt(Math.random()*3+3); Enemy.call(this,1,s,['image/enemy1.png','image/enemy1-bang.gif'])}SmallEnemy.prototype = { constructor:SmallEnemy; __proto__:Enemy.prototype;}function MiddleEnemy(){ var s = parseInt(Math.random()*3+2); Enemy.call(this,5,s,['image/enemy2.png','image/enemy2-bang.gif'])}MiddleEnemy.prototype = { constructor:MiddleEnemy; __proto__:Enemy.prototype;}function LargeEnemy(){ var s = parseInt(Math.random()*2+1); Enemy.call(this,10,s,['image/enemy3.png','image/enemy3-bang.gif'])}LargeEnemy.prototype = { constructor:LargeEnemy; __proto__:Enemy.prototype;}
去引擎里面不间断的创建敌机
/*游戏引擎 */var Engine = { //刚开始的游戏状态 gameStatus:false, //所以敌机 enemy:{}, //子弹 bullet:{}, //得分 score:0, //背景图片 game:document.querySelector('.game'), //初始化 init:function(){ this.gameStart(); }, //游戏开始 gameStart:function(){ var _this = this; //点击图片的时候判断游戏状态 this.game.onclick = function(){ if(!_this.gameStatus){ _this.gameStatus = true; //移动移动 _this.bgMove(); _this.handleMove(); _this.createPlane(); } } }, //背景移动 bgMove:function(){ var y=0; var _this = this; this.bgTimer = setInterval(function(){ y+=2; _this.game.style['background-position-y']=y+'px'; },50) }, createPlane:function(){ //创建敌机和英雄机 Hero.init(); //创建敌机 var timer = setInterval(function(){ var num = parseInt(Math.random()*15)+1; switch (num) { case 1: case 3: case 5: case 7: case 9: new SmallEnemy().init(); break; case 2: case 4: case 6: new MiddleEnemy().init(); case 8: case 12: new LargeEnemy().init(); } },500) }, //所有敌机和子弹都要动 handleMove:function(){ var _this=this; var timer = setInterval(function(){ //创建所有子弹 for(var i in _this.bullet){ _this.bullet[i].move() } //c创建所有敌机动 for(var i in _this.enemy){ _this.enemy[i].move() } },30) }};Engine.init();