项目演示
项目演示地址:
项目源码:
代码结构
本节做完效果
info.js
//画出塔的攻击范围以及升级等信息 drawScope : function(tower){ var select = Game.canvasList.select; Canvas.clear(select,500,500); Canvas.fillArc(select,tower.x+25,tower.y+25,TowerType[tower.type]["level_"+tower.level].scope,"rgba(25,174,70,0.5)"); if(tower.level < 3)Canvas.drawImg(select,Game.imgList.btn_img,0,0,20,20,tower.x,tower.y,20,20); Canvas.drawImg(select,Game.imgList.btn_img,20,0,20,20,tower.x+30,tower.y+30,20,20); }, //升级或卖掉 upgradeOrSell : function(x,y){ var tower = Game.nowSelectTower; //升级 if(tower.level < 3 && T.pointInRect({x:x,y:y},{x:tower.x,y:tower.y,width:20,height:20})){ if(this.score - TowerType[tower.type]["level_"+(tower.level+1)].buyIt < 0)return false; tower.level += 1; this.updateScore(TowerType[tower.type]["level_"+tower.level].buyIt * -1); this.drawScope(tower); //update } //卖掉 else if(T.pointInRect({x:x,y:y},{x:tower.x+30,y:tower.y+30,width:20,height:20})){ var money = Math.floor((tower.level * TowerType[tower.type]["level_1"].buyIt)/2); this.updateScore(money); delete this.installTower[Math.floor(tower.x/50)+"_"+Math.floor(tower.y/50)]; Game.towerList.remove(tower); Canvas.clearRect(Game.canvasList.tower,tower.x,tower.y,tower.width,tower.height); Canvas.clear(Game.canvasList.select,500,500); tower = null; //sell } }
enemy.js
game.js
新增initBind 函数
//初始化绑定塔的事件 initBind : function(){ var select = document.getElementById("select"); select.onclick = function(e){ var x = e.offsetX || e.layerX, y = e.offsetY || e.layerY; //遍历塔的列表 for(var i=0,l=Game.towerList.length;i<l;i++){ //判断是否选择到了塔 if(T.pointInRect({x:x,y:y},Game.towerList[i])){ //画出范围 Info.drawScope(Game.towerList[i]); if(Game.nowSelectTower){ //升级或卖掉 Info.upgradeOrSell(x,y); } Game.nowSelectTower = Game.towerList[i]; break; } } //没有选中,清除 if(i == l){ Canvas.clear(Game.canvasList.select,500,500); Game.nowSelectTower = null; } } }
//重新开始 restart : function(){ this.stop(); this.towerList = []; this.enemyList = []; this.bulletList = []; this.mission = 0; this.missionEnemey = 0; this.missionLazy = 2000; this.enemyLazy = 0; this.nowSelectTower = null; Info.score = 100; Info.life = 10; Info.mission = 1; Info.installTower = {}; Canvas.clear(this.canvasList.map,500,500); Canvas.clear(this.canvasList.main,500,500); Canvas.clear(this.canvasList.tower,500,500); Canvas.clear(this.canvasList.select,500,500); Info.redraw(); this.start(); }, //停止 stop : function(){ clearInterval(this.timer); }, //结束 over : function(){ this.stop(); alert("你输了!"); }, //赢了 win : function(){ this.stop(); alert("你赢了!"); }