本文主要是介绍WestFighting / 西途决斗 升级 v1.2.0 版 -- 主要增加血瓶功能,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
有点兴奋, 呵呵... 这两天又偷偷把 西途决斗 升级 升级了,升级的内容如下:
1,族人到死了大部分,还剩下1个时,系统自动增加族人部队,数量跟上次的一样,这样理论上游戏可以无限制的玩下去,只要牛仔生命值够;
2,增加了血瓶功能,血制值150--300随机值,当满血时不能喝血,其他情况能喝,血瓶在场景内任意漂浮一定时间[如90秒],之后消失,每隔一定时间[如 30秒]又出现新的血瓶;当牛仔进入虚弱期,或非满血时,进行相关提示,当接触到血瓶并按下 V 键不放开始不断得喝血呵,有点意思,每次喝1点补充生命值;直到喝完血瓶就消失,可以喝到半就走开的情况;
3,游戏的封装进行改善,这样更加直观和容易理解,如游戏的操作控制和时间控制等相关都归到 gameSystem 对象中;
4, 一些变量的清除/改善处理,消除游戏运行久了以后消耗内存过多的情况;
5,图片相应的修改了一些,见图;
整个游戏下载 在 CSDN 下载资源那里
好了首先看图:
增加血瓶功能的战斗界面
增加血瓶后的新动作分解图
westFighting / 西途决斗 v1.2.0版 完整代码
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>West Fighting / 西途决斗 - HTML5 GAME</title>
<style type="text/css">
body{margin:0px; padding:0; overflow-x:hidden;}
body,td,div,span,input,canvas{font-family:verdana,arial; font-size:12px;}
a:link, a:visited{font-family:verdana,arial; font-size:11px; color:#006699; text-decoration:underline;}
a:hover, a:active{font-family:verdana,arial; font-size:11px; color:#FF0033; text-decoration:none;}
#gameContainer{border:1px solid red;}
#gameCanvas{font-size:12px; font-family:verdana,arial; }
#infoPanel{font-family:verdana,arial; font-size:12px; border:1px solid #D63C06; display:block; padding:5px; background-color:#F9EFE9; overflow:hidden;}
#gameInfo{font-family:verdana,arial; font-size:11px; text-align:right; font-weight:normal; display:block; border-bottom:1px solid #999999;padding-bottom:3px;}
#controlPanel{padding:10px 0;}
.num01{font-family:verdana,arial; font-size:10px; padding:0 2px; font-weight:normal;}
.num02{font-family:verdana,arial; font-size:11px; padding:0 2px; font-weight:normal; color:#990000;}
a.a01:link, a.a01:visited{font-family:verdana,arial; font-size:12px; color:#006699; border:1px solid #999999; padding:2px 4px; margin:0 5px; text-decoration:none}
a.a01:hover, a.a01:active{font-family:verdana,arial; font-size:12px; color:#FFFFCC; border:1px solid #999999; padding:2px 4px; margin:0 5px; text-decoration:none; background-color:#990000}
</style>
</head><body οnkeydοwn="javascript:keyPress(event);" οnkeyup="javascript:keyRelease(event);">
<div id="gameContainer">
<canvas id="gameCanvas" width="1024">
<div id="gbTip">请使用支持HTML5的浏览器...</div>
</canvas>
</div>
<!--start: info panel-->
<div id="infoPanel">
<div id="gameInfo"><b>West Fighting[西途决斗]</b>, Version:1.2.0, Current Time:<span class="num02" id="cTime">2010-11-30 10:20:32</span>, Run Time:<span class="num02" id="rTime">0000</span>sec, created by <a target="_blank" title="^_^ welcome..." href="http://hi.csdn.net/shenzhenNBA">shenzhenNBA[CSDN]</a>, <a target="_blank" title="^_^ welcome..." href="http://blog.csdn.net/shenzhennba/">Blog</a> 2011-12-01(商用需授权...)</div>
<div id="controlPanel">
Cowboy Life:<span class="num02" id="cowboyLife">120</span>, Position:[X:<span class="num02" id="cowboyPX">0</span>, Y:<span class="num02" id="cowboyPY">0</span>]
Tribe man Active:<span class="num02" id="tmActive">0</span>, Death:<span class="num02" id="tmDeath">0</span>
control key: [ ↑,←, ↓, → ] or [ W,A,S,D ], fast + [ Ctrl ]
<a class="a01" href="javascript:gameSystem.gameStart();" title="开始">Start</a> <a class="a01" href="javascript:gameSystem.gamePause();" title="暂停">Pause</a> <a class="a01" href="javascript:gameSystem.gameContinue();" title="继续">Continue</a> <a class="a01" href="javascript:gameSystem.gameRestart();" title="结束当前重新开始游戏">Restart</a> <a class="a01" href="javascript:gameSystem.gameEnd();" title="结束游戏">End</a><a class="a01" title="游戏说明" href="javascript:void(0);">How to play</a> <span id="num"></span>
</div>
</div>
<!--end: info panel-->
<script language="javascript" type="text/javascript">
//This is old source code//--------------------start: keep tribe move time define-------------
var timeController={
//function to controll the tribe man keep move in old direction some time and then change the move direction
//设置在上一次方向上持续移动的时间,超过该时间后,动态修正方向[以牛仔为目标]再持续在该方向上移动指定时间在修正方向,一直循环这个过程到死忙
//keepMoveTime 时间越短动态改变方向越快,朝牛仔目标移动越灵敏 i:0,weakTipChangeTime:2,weakTipShowTime:2,t:0,j:1,bottleShowTime:90,newBottleTime:30,timeControllerID:"", timeOn:function(){ //----------------start: about tribe man time control--------------------for(this.t=0;this.t<gameSystem.tribeMen.length;this.t++){gameSystem.tribeMen[this.t].k+=1; if(gameSystem.tribeMen[this.t].k==gameSystem.tribeMen[this.t].keepMoveTime){ gameSystem.tribeMen[this.t].isChangeDirection=true;gameSystem.tribeMen[this.t].k=0;}else{gameSystem.tribeMen[this.t].isChangeDirection=false;} } //----------------end: about tribe man time control--------------------//----------------start: about cowboy weak tip time control------------------//控制牛仔进入虚弱期时每隔2秒中显示虚弱提示,显示2秒后隐藏this.i++;if(this.i > this.weakTipChangeTime){if(this.i >= this.weakTipChangeTime + this.weakTipShowTime) this.i = 0;westCowboy.isWeak=true; }elsewestCowboy.isWeak=false; //----------------end: about cowboy weak tip time control-------------------//----------------start: about blood bottle time control--------------------//bottle 一开始就出现,显示指定时间,超过显示时间消失,进入下一回循环this.j++; if(this.j > this.bottleShowTime){ //show time//hide bottle by 4 step if(this.j == this.bottleShowTime+1) bloodBottle.bloodValue=Math.ceil(bloodBottle.bloodValue*0.6);if(this.j == this.bottleShowTime+2) bloodBottle.bloodValue=Math.ceil(bloodBottle.bloodValue*0.5);if(this.j == this.bottleShowTime+3) bloodBottle.bloodValue=Math.ceil(bloodBottle.bloodValue*0.2);if(this.j > this.bottleShowTime+3) bloodBottle.bloodValue=0; if(this.j >= this.newBottleTime + this.bottleShowTime+4){this.j=1;bloodBottle.init(); }} //----------------end: about blood bottle time control----------------------}
};
//--------------------end: keep tribe move time define---------------//--------------------start: generalTools object define----------------
var generalTools={rangeRandom:function(minValue, maxValue){ if(maxValue >= minValue)return Math.floor(Math.random()*(maxValue-minValue+1)+minValue);elsereturn Math.floor(Math.random()*(minValue-maxValue+1)+maxValue); },rangeRandom2:function(minValue, maxValue,maxValuePercent){//function to get value, maxValue [percent = maxValuePercent ], minValue [percent = 1-maxValuePercent ]var mvPer=0;var v=0;try{ mvPer=parseFloat(maxValuePercent); }catch(e){ mvPer=0.2; }if(Math.random()>=(1-mvPer)) v=maxValue;elsev=minValue;return v;}
};
//--------------------end: generalTools object define-----------------//---------------------start: west cowboy define---------------------
var westCowboy={cowboyVersion:"1.0.0", //about the west Cowboy info and refered authorcowboyPicSRC : "http://hi.csdn.net/attachment/201112/28/65387_1325068968P78Z.png", cowboyPicObj:"",gridSize:50, //width=height=50picSN:0,cowboyPicAuthor : "shenzhenNBA", initLifeValue: 5000,lifeValue : 0,killValue : 1,speed : 1,qspeed : 4,x : 0,y : 0, innerXMin : 0,innerYMin : 0,innerXMax : 0, innerYMax : 0,r : 20, //cowboy size:20*20isShowTip : false, //[show refered info, true=show, false=hide(default)]isWeak : false,init: function(){this.lifeValue=this.initLifeValue;this.innerXMin=this.r;this.innerYMin=this.r;//this.innerXMax= gameSystem.scrW-this.r;//this.innerYMax= gameSystem.scrH-this.r;this.innerXMax=$("gameCanvas").width-this.gridSize*0.8;this.innerYMax=$("gameCanvas").height-this.gridSize*0.8; this.x=Math.floor($("gameCanvas").width/2);this.y=Math.floor($("gameCanvas").height/2);var img=new Image();img.src=this.cowboyPicSRC;this.cowboyPicObj=img;}
};westCowboy.getSpeed = function(){ //get move speed flagreturn (inputFlag.quick ? this.qspeed : this.speed); //attend: this = westCowboy
};westCowboy.showCowboyTip = function(){
//function to show cowboy refered informationif(this.isShowTip){//var c=$("gameCanvas");//var cxt=c.getContext("2d");//cxt.clearRect(this.left+this.r,this.top+this.r,80,25); //clear areagameSystem.cxt.font="10px Arial";gameSystem.cxt.fillStyle="#6600FF"; //FF6600gameSystem.cxt.fillText("Life:"+this.lifeValue,this.x+this.r*2,this.y+this.r); }
};westCowboy.showThew = function(){if(this.lifeValue<1000 && this.lifeValue>0){if(this.isWeak){//var c=$("gameCanvas");//var cxt=c.getContext("2d");//cxt.clearRect(this.left+this.r,this.top+this.r,80,25); //clear areagameSystem.cxt.font="10px Arial";gameSystem.cxt.fillStyle="#6600FF"; //FF6600gameSystem.cxt.fillText(this.lifeValue+", weak, add blood, fighting 1:1 ...",this.x+this.r*2,this.y+this.r*2); } }
};westCowboy.move=function(){if(this.lifeValue>0){if (inputFlag.right)westCowboy.x+=westCowboy.getSpeed();if (inputFlag.left) westCowboy.x-=westCowboy.getSpeed();if (inputFlag.down) westCowboy.y+=westCowboy.getSpeed();if (inputFlag.up) westCowboy.y-=westCowboy.getSpeed();}$("cowboyLife").innerHTML=westCowboy.lifeValue;$("cowboyPX").innerHTML=westCowboy.x;$("cowboyPY").innerHTML=westCowboy.y;if(westCowboy.x >= westCowboy.innerXMax) westCowboy.x=westCowboy.innerXMax;if(westCowboy.x < -this.r) westCowboy.x = -this.r;if(westCowboy.y >= westCowboy.innerYMax) westCowboy.y=westCowboy.innerYMax;if(westCowboy.y < -this.r) westCowboy.y = -this.r;//var c=$("gameCanvas");//var cxt=c.getContext("2d"); //format: drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh) if(this.lifeValue>0){ //not face touch and status is: Move or Stop, include [上下左右,左上,左下,右上,右下]if(inputFlag.left) //move to leftgameSystem.cxt.drawImage(westCowboy.cowboyPicObj,westCowboy.gridSize*westCowboy.picSN,westCowboy.gridSize*3,westCowboy.gridSize,westCowboy.gridSize,this.x,this.y,westCowboy.gridSize,westCowboy.gridSize); else if(inputFlag.right) //move to rightgameSystem.cxt.drawImage(westCowboy.cowboyPicObj,westCowboy.gridSize*westCowboy.picSN,westCowboy.gridSize*4,westCowboy.gridSize,westCowboy.gridSize,this.x,this.y,westCowboy.gridSize,westCowboy.gridSize); else if(inputFlag.up) //move to upgameSystem.cxt.drawImage(westCowboy.cowboyPicObj,westCowboy.gridSize*westCowboy.picSN,westCowboy.gridSize*3,westCowboy.gridSize,westCowboy.gridSize,this.x,this.y,westCowboy.gridSize,westCowboy.gridSize); else if(inputFlag.down) //move to downgameSystem.cxt.drawImage(westCowboy.cowboyPicObj,westCowboy.gridSize*westCowboy.picSN,westCowboy.gridSize*4,westCowboy.gridSize,westCowboy.gridSize,this.x,this.y,westCowboy.gridSize,westCowboy.gridSize); else //stop movegameSystem.cxt.drawImage(westCowboy.cowboyPicObj,westCowboy.gridSize*3,westCowboy.gridSize*3,westCowboy.gridSize,westCowboy.gridSize,this.x,this.y,westCowboy.gridSize,westCowboy.gridSize); westCowboy.picSN+=1;if(westCowboy.picSN>=4) westCowboy.picSN=0;}else{gameSystem.cxt.drawImage(westCowboy.cowboyPicObj,westCowboy.gridSize*4,westCowboy.gridSize*3,westCowboy.gridSize,westCowboy.gridSize,this.x,this.y,westCowboy.gridSize,westCowboy.gridSize); }/* for TEST, ONLY draw a dot *//*gameSystem.cxt.fillStyle="#666666"; //draw the RED dot //, FF0000gameSystem.cxt.beginPath();gameSystem.cxt.arc(westCowboy.x,westCowboy.y,westCowboy.r,0,Math.PI * 2,true); //draw a dot; syntax: context.arc(centerX, centerY, radius, startingAngle, endingAngle, antiClockwise);gameSystem.cxt.closePath();gameSystem.cxt.fill(); */this.showCowboyTip();this.showThew();
};
//---------------------end: west cowboy define-----------------------//---------------------start: tribe man define-----------------------
var tribeMan=function(){//tribeman properties difine areathis.tribeManVersion="1.0.0"; //about the Tribe Man info and refered author,this.tribeManPicSRC= "http://hi.csdn.net/attachment/201112/28/65387_1325068968P78Z.png"; this.tribeManPicAuthor="shenzhenNBA";this.gridSize=50; //width=height=50this.tribeManPicObj="";this.picSN=0;this.lifeValue=80; //value is [80~100],default=80this.killValue=1; //value is [1~3],default=1this.x=0;this.y=0;this.r=20; //tribe man size:20x20this.speed=1; //value is [1~3],default=1this.diffX=0; //offset in X axisthis.diffY=0; //offset in Y axisthis.moveAngle=0; //move anglethis.isXAddFlag=true; //this.isYAddFlag=true; //this.canvasW=$('gameCanvas').width;this.canvasH=$('gameCanvas').height; this.isChangeDirection=true; //change direction [ true = can change, false= can not change ]this.k=0; //temperate variablethis.keepMoveTime=3; //keep move in old direction time(unit:s), random this.isShowLifeValue=false; //show life value [true=show, false=hide(default)]//tribeman init areathis.init=function(){ var img=new Image();img.src=this.tribeManPicSRC;this.tribeManPicObj=img;this.keepMoveTime=generalTools.rangeRandom(2,5); //keep move in old direction time(unit:s), random this.lifeValue=generalTools.rangeRandom(80,100); //attend: this = tribethis.killValue=generalTools.rangeRandom(1,3);this.speed=generalTools.rangeRandom2(1,3,0.25);this.moveAngle=Math.floor(Math.random()*91); //angle value is [0~91]var maxR=Math.floor(Math.sqrt(this.canvasW*this.canvasW+this.canvasH*this.canvasH)); //用勾股定律求画布canvas的对角线的长度var randomR=generalTools.rangeRandom(maxR*0.5,maxR); //value is [maxR/2 ~ maxR]//get X,Y axis position here //以对角线为最大值随机取值,以90为最大角度随机取角度,分别用三角函数求出XY值this.x=randomR*Math.sin(this.moveAngle); //x value is [0~maxR] this.y=randomR*Math.cos(this.moveAngle); //x value is [0~maxR]if(this.x>this.canvasW) this.x=this.canvasW; //限定在 canvas 内部if(this.x<0) this.x=0;if(this.y>this.canvasH) this.y=this.canvasH;if(this.y<0) this.y=0;//判断所在像限:左上[+X,+Y],右上[-X,+Y],左下[+X,-Y],右下[-X,-Y],确定增量的方向,if(this.x<this.canvasW/2 && this.y<=this.canvasH/2){ //左上,含Y中间左轴线this.isXAddFlag=true;this.isYAddFlag=true;}else if(this.x>this.canvasW/2 && this.y<=this.canvasH/2){ //右上,含Y中间右轴线 this.isXAddFlag=false;this.isYAddFlag=true;}else if(this.x<=this.canvasW/2 && this.y>this.canvasH/2){ //左下,含X中间下轴线this.isXAddFlag=true;this.isYAddFlag=false;}else{ //右下this.isXAddFlag=false;this.isYAddFlag=false;}//设置 XY 两个方向的增量方式:增或减,以及位移量this.diffX=Math.sin(Math.PI/180*this.moveAngle)*this.speed;this.diffX=this.isXAddFlag ? this.diffX : 0-this.diffX ;this.diffY=Math.cos(Math.PI/180*this.moveAngle)*this.speed;this.diffY=this.isYAddFlag ? this.diffY : 0-this.diffY; if(this.diffX < 0.001) this.diffX=Math.random(); //diffX,diffY > 0.001, //set the min diffX,diffYif(this.diffY < 0.001) this.diffY=Math.random();//alert('tribe init...'); //for TEST};//tribeman Action area this.move=function(){//function to move tribemen, if death then can not move more. //var c=$('gameCanvas');//var cxt=c.getContext("2d"); if(this.lifeValue>0){ //active lifevar ftFlag=this.faceTouch(); if(ftFlag){ //face touch //face touch then fightinggameSystem.cxt.drawImage(this.tribeManPicObj,this.gridSize*this.picSN,this.gridSize*2,this.gridSize,this.gridSize,this.x,this.y,this.gridSize,this.gridSize); if(westCowboy.lifeValue>0)gameSystem.cxt.drawImage(westCowboy.cowboyPicObj,westCowboy.gridSize*westCowboy.picSN,westCowboy.gridSize*5,westCowboy.gridSize,westCowboy.gridSize,westCowboy.x,westCowboy.y,westCowboy.gridSize,westCowboy.gridSize); elsegameSystem.cxt.drawImage(westCowboy.cowboyPicObj,westCowboy.gridSize*4,westCowboy.gridSize*3,westCowboy.gridSize,westCowboy.gridSize,westCowboy.x,westCowboy.y,westCowboy.gridSize,westCowboy.gridSize); }else{ //no face touch, move continueif(westCowboy.lifeValue<=0){ //cowboy death then tribe man walk free//-----start: walk free-----if(this.x<0) this.diffX = Math.abs(this.diffX);if(this.x>this.canvasW) this.diffX = -Math.abs(this.diffX);if(this.y<0) this.diffY = Math.abs(this.diffY);if(this.y>this.canvasH) this.diffY = -Math.abs(this.diffY);//-----end: walk free-----}else{ //move to cowboy //-----start: walk to cowboy-----if(this.isChangeDirection){ if(westCowboy.x >= this.x) this.diffX = Math.abs(this.diffX);elsethis.diffX = -Math.abs(this.diffX); if(westCowboy.y >= this.y) this.diffY = Math.abs(this.diffY);elsethis.diffY = -Math.abs(this.diffY);} //-----end: walk to cowboy-------}this.x=this.x+this.diffX; //attend: this = tribe classthis.y=this.y+this.diffY; //format: drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh) if(westCowboy.x >= this.x) //move to rightgameSystem.cxt.drawImage(this.tribeManPicObj,this.gridSize*this.picSN,this.gridSize*0,this.gridSize,this.gridSize,this.x,this.y,this.gridSize,this.gridSize); else //move to leftgameSystem.cxt.drawImage(this.tribeManPicObj,this.gridSize*this.picSN,this.gridSize*1,this.gridSize,this.gridSize,this.x,this.y,this.gridSize,this.gridSize); } this.picSN+=1;if(this.picSN>=4) this.picSN=0;}else{ //deathgameSystem.cxt.drawImage(this.tribeManPicObj,this.gridSize*4,0,this.gridSize,this.gridSize,this.x,this.y,this.gridSize,this.gridSize); } /*//only for TEST gameSystem.cxt.fillStyle="#DDDDDD"; //, 0000FFgameSystem.cxt.beginPath();gameSystem.cxt.arc(this.x,this.y,this.r,0,Math.PI*2,true); gameSystem.cxt.closePath();gameSystem.cxt.fill(); */if(this.isShowLifeValue){gameSystem.cxt.font="10px Arial";gameSystem.cxt.fillStyle="#006600";gameSystem.cxt.fillText("Life: "+this.lifeValue,this.x+this.r*2,this.y+this.r); }};this.faceTouch=function(){//function to jugme tribe man face touch cowboy or else,[true=face touch, false=no touch] var dx = Math.abs(westCowboy.x-this.x);var dy = Math.abs(westCowboy.y-this.y);var dl=dx*dx+dy*dy; var tl=(this.r*this.r+this.r*this.r)*2; //attend the Size of tribe man and cowboy should be the sameif(dl<tl){ return true;}else{ return false; } };this.showTribeTip=function(){//function to show the tribe man information//var c=$('gameCanvas');//var cxt=c.getContext("2d"); gameSystem.cxt.font="normal normal 11px verdana";//show tribe man lefe valuegameSystem.cxt.fillStyle="#0000FF";gameSystem.cxt.fillText("Life:"+this.lifeValue,this.x+this.r*2,this.y); //+this.r//show cowboy lefe valuegameSystem.cxt.fillStyle="#FF0000";//cxt.clearRect(westCowboy.x+westCowboy.r,westCowboy.y-11,10*6,11); //format:context.clearRect(x,y,width,height); //clear the block gameSystem.cxt.fillText("Life:"+westCowboy.lifeValue,westCowboy.x+westCowboy.r*2,westCowboy.y); };this.showFightTip=function(){//function to show the tribe man information//var c=$('gameCanvas');//var cxt=c.getContext("2d"); gameSystem.cxt.font="normal normal 11px verdana";//show tribe man fighting WordsgameSystem.cxt.fillStyle="#0000FF";if(this.lifeValue>0) gameSystem.cxt.fillText("kill... kill...",this.x+this.r*2,this.y+this.r/2); elsegameSystem.cxt.fillText("death...",this.x+this.r*2,this.y+this.r/2); //show cowboy fighting WordsgameSystem.cxt.fillStyle="#FF0000";gameSystem.cxt.font="normal normal 11px verdana";//gameSystem.cxt.clearRect(westCowboy.x+westCowboy.r,westCowboy.y-11,10*6,11); //format:context.clearRect(x,y,width,height); //clear the block firstif(westCowboy.lifeValue>0)gameSystem.cxt.fillText("fighting...fighting...",westCowboy.x+westCowboy.r*2,westCowboy.y+this.r/2); elsegameSystem.cxt.fillText("death...",westCowboy.x+westCowboy.r*2,westCowboy.y+this.r/2); };this.fighting=function(){//functionto fighting with cowboy here if face touchvar ft=this.faceTouch(); if(ft){ //face touch here if(this.lifeValue>0){if(westCowboy.lifeValue>0) westCowboy.lifeValue = westCowboy.lifeValue - this.killValue; if(westCowboy.lifeValue<0) westCowboy.lifeValue=0;}if(westCowboy.lifeValue>0){if(this.lifeValue>0) this.lifeValue = this.lifeValue - westCowboy.killValue;if(this.lifeValue<0) this.lifeValue=0;}if(westCowboy.lifeValue>0){this.showTribeTip();this.showFightTip();}}else{ //face touch here //no fighting....}};
};
//---------------------end: tribe man define-------------------------//--------------------start: global function define------------------
var $ = function(id){return "string"==typeof(id) ? document.getElementById(id) : id ;
}//定义键盘值
var KEY = { D: 68, W: 87, A: 65, S:83, DOWN:40, RIGHT:39, UP:38, LEFT:37, QUICK:17, V:86, C:67, Z:90,X:88};//定义输入标志对象
var inputFlag = {right : false,up : false,left : false,down : false,quick : false
};//按键按下相应动作修改
var keyPress = function(event){var e = event || window.event;var code = e.keyCode | e.which | e.charCode; switch(code) {case KEY.RIGHT:case KEY.D: inputFlag.right = true; break;case KEY.UP:case KEY.W: inputFlag.up = true; break;case KEY.LEFT:case KEY.A: inputFlag.left = true; break;case KEY.DOWN:case KEY.S: inputFlag.down = true; break;case KEY.QUICK: inputFlag.quick = true; break;case KEY.C: westCowboy.isShowTip=true; break;case KEY.X: gameSystem.showTribeMenLife(); break; case KEY.V: bloodBottle.isEaten=true; break;}
};//按键放开相应动作修改
var keyRelease = function(event) { var e = event || window.event;var code = e.keyCode | e.which | e.charCode; switch(code) {case KEY.RIGHT:case KEY.D: inputFlag.right = false; break;case KEY.UP:case KEY.W: inputFlag.up = false; break;case KEY.LEFT:case KEY.A: inputFlag.left = false; break;case KEY.DOWN:case KEY.S: inputFlag.down = false; break;case KEY.QUICK: inputFlag.quick = false; break;case KEY.C: westCowboy.isShowTip=false; break;case KEY.V: bloodBottle.isEaten=false; break;case KEY.Z: if(westCowboy.lifeValue >= westCowboy.initLifeValue)westCowboy.lifeValue = westCowboy.initLifeValue;else westCowboy.lifeValue+=2; break;case KEY.X:gameSystem.hideTribeMenLife();break;}
};var gameSystem = {
//function to get game system variables gameName : "West Fighting......", //about game information gameNameCN: "西途决斗......",gameVersion : "1.2.0", //first: v1.0.0gameLastUpdate : "2011-12-23",LUDescription: 'add more tribe man and blood bottle', //Last Update DescriptiongameAuthor : "shenzhenNBA",gameAuthorIM: "",gameAuthorEmail: "qyhzqw@163.com",//scrW : screen.width,//scrH : screen.height, scrW : (document.compatMode == "CSS1Compat" ? document.documentElement.clientWidth : document.body.clientWidth) || screen.availWidth,scrH : (document.compatMode == "CSS1Compat" ? document.documentElement.clientHeight : document.body.clientHeight) || screen.availHeight, canvasObj:'', //canvas objectcxt:'', //canvas context 2dcanvasW:0, //canvas widthcanvasH:0, //canvas heightinitTribeManNum:30, //initlaize tribe man numbertribeMen:[], lastTribeMenNum:0, //last tribe man number before NEXT new tribe teamrunTime: 0,runTimerID : "",gameFrameSpeed: 20, //PFS, refresh speedgamePlayerID: "",i:0,activeTManNum:0,ua: navigator.userAgent,isGameEnd:false,isSupportHTML5: function(){var bn,bv,v;try{bn=this.getBrowserName().toLowerCase();bv=parseFloat(this.getBrowserVersion()); }catch(e){}//first Support HTML5: IE v=9,Firefox v=3.5, Chrome v=3.5,Opera v=10.5, Safari v=3.0 //找的,不知是否对if(bn=="ms ie" && bv>=9){v=true;}else if(bn=="firefox" && bv>=3.5){v=true;}else if(bn=="chrome" && bv>=3.5){v=true;}else if(bn=="opera" && bv>=3.5){v=true;}else if(bn=="safari" && bv>=3.0){v=true;}else{v=false;}return v;}, getBrowserName: function(){var uai=this.ua.toLowerCase(); var bn=''; if(uai.indexOf('msie')>=0) bn="MS IE";if(uai.indexOf('firefox')>=0) bn="FireFox";if(uai.indexOf('chrome')>=0) bn="Chrome";if(uai.indexOf('opera')>=0) bn="Opera";if(uai.indexOf('safari')>=0) bn="Safari";if(bn=="") bn="Unknow browser";return bn;}, getBrowserVersion:function(){var v='';var uai=this.ua.toLowerCase(); if(s = uai.match(/msie ([\d.]+)/)) v = RegExp.$1 ; if(s = uai.match(/firefox\/([\d.]+)/)) v = RegExp.$1 ;if(s = uai.match(/chrome\/([\d.]+)/)) v = RegExp.$1 ;if(s = uai.match(/opera.([\d.]+)/)) v = RegExp.$1 ;if(s = uai.match(/version\/([\d.]+).*safari/)) v = RegExp.$1; if(v=="") v='unknow version';return v;},showTribeMenLife: function(){var n=0;for(n=0;n<gameSystem.tribeMen.length;n++){gameSystem.tribeMen[n].isShowLifeValue=true;}},hideTribeMenLife: function(){var n=0;for(n=0;n<gameSystem.tribeMen.length;n++){gameSystem.tribeMen[n].isShowLifeValue=false;}}
};gameSystem.gameUIFace=function(objCanvas){
//function to create game UI Face var oGC=objCanvas;//var oGC=$('gameCanvas'); //get object directly for Testvar cxt=oGC.getContext("2d");var cx,cy,r1,r2;r1=30; try{ cx=oGC.width/2; }catch(e){ cx=screen.width/2; };try{ cy=oGC.height/2; }catch(e2){ cy=screen.height/2; };try{ r2=oGC.height/2; }catch(e3){ r2=screen.height/2; };/* *///----start: draw radial/gradient circle ----var rg=cxt.createRadialGradient(cx,cy,r1,cx,cy,r2); //create object typerg.addColorStop(0,'#FF6600'); //set the start position colorrg.addColorStop(1,'#FAFAFA'); //set the end position colorcxt.fillStyle=rg; //set the pen style //cxt.strokeStyle=rg; //会使用单色黑色绘制,应该使用 fillStyle cxt.beginPath();cxt.arc(cx,cy,r2,0,Math.PI*2,true);cxt.closePath();cxt.fill(); //----end: draw radial/gradient circle ----//----start: draw cowboy image ----var img=new Image();img.src="http://hi.csdn.net/attachment/201112/17/65387_13241032476Ybf.png"; cxt.globalAlpha=0.5; //value is [0~1],0=hide[disappear], 1 = show [clear] allcxt.drawImage(img,cx/6,-20);cxt.globalAlpha=1;//----end: draw cowboy image ---- //----start: draw gradient line ----var i=0,n=100,step=0;try{ step=Math.floor(oGC.width/n); }catch(e4){ step=Math.floor(screen.width/n);} for(i=0;i<=n;i++){var lg=cxt.createLinearGradient((cx-n/2+i),cy,i*step,cy+300);lg.addColorStop(0,'#FF3300');lg.addColorStop(1,'#FFFFFF'); //0099CC//cxt.fillStyle=lg; //单色黑色绘制cxt.strokeStyle=lg; //多种颜色绘制cxt.beginPath();cxt.moveTo((cx-n*2+i*4),cy+n/4); //set the start position//cxt.moveTo((cx-n/2+i),cy);//cxt.moveTo(cx,cy);//cxt.lineCap = 'round' ;if((i % 5)==0) cxt.lineWidth=2; //set the line size//cxt.lineJoin ="miter";elsecxt.lineWidth=1;cxt.lineTo(i*step,cy+300);cxt.stroke();//cxt.fill();cxt.closePath(); }//----end: draw gradient line ------//----start: draw game Title ------ var moveTXTPos=60; //about game EN Namecxt.font="italic bold 45px Arial Black"; //format: context.font="style variant weight size line-height family"cxt.fillStyle="#0000FF";cxt.shadowColor ="#FFFF99"; //"rgb(255,0,0)" //99CCFFcxt.shadowOffsetX=4;cxt.shadowOffsetY=3; cxt.shadowBlur=3;cxt.fillText(gameSystem.gameName,cx-moveTXTPos*4,cy-40); cxt.font="italic bold 24px 黑体"; //Verdana,Arial Black,,华文新魏 //about game CN Namecxt.shadowColor="#FFFF99"; cxt.shadowOffsetX=2;cxt.shadowOffsetY=2;cxt.shadowBlur=2;cxt.fillStyle="#660066";cxt.fillText(gameSystem.gameNameCN,cx-moveTXTPos*1.5,cy); cxt.font="italic normal 11px verdana"; //about game version and authorcxt.shadowOffsetX=0;cxt.shadowOffsetY=0;cxt.shadowBlur=1;cxt.fillStyle="#FF0000";cxt.fillText("Version: "+gameSystem.gameVersion+' Author: '+gameSystem.gameAuthor,cx+moveTXTPos/4,cy+20); //----end: draw game Title ------
};gameSystem.initGameUI=function(){
//function to initialize Game UI here//var scrW=screen.width;//var scrH=screen.height; //var canvasW=scrW-8; //var canvasH=scrH-infoPanelH-xBarH; var infoPanelH=80; //var xBarH=120; //height of x Bars var canvasW=gameSystem.scrW-6; var canvasH=gameSystem.scrH-infoPanelH-20;var paddingLR=5; //padding of left and right in infoPanelvar bn='',bv='';bn=gameSystem.getBrowserName().toLowerCase();bv=parseFloat(gameSystem.getBrowserVersion());var oGC='';//first Support HTML5: IE v=9,Firefox v=3.5, Chrome v=3.5,Opera v=10.5, Safari v=3.0 //找的,不知是否对if((bn=="ms ie" && bv<9) || (bn=="firefox" && bv<3.5) || (bn=="chrome" && bv<3.5) || (bn=="opera" && bv<10.5) || (bn=="safari" && bv<3.0)){ //not support HTML5 go hereoGC=$('gameContainer');var tempHTML='';tempHTML="<br><p><b> Error:</b></p> 您的浏览器是 "+bn+" ,版本是 "+bv +" ,还不支持 HTML5; ";tempHTML+=" 请使用下列(或更高版本)支持 HTML5 的的浏览器:<br>";tempHTML+="<ul><li>MS IE, version = 9 或更高版本</li>";tempHTML+="<li>Firefox, version = 3.5 或更高版本</li>";tempHTML+="<li>Chrome, version = 3.5 或更高版本</li>";tempHTML+="<li>Opera, version = 10.5 或更高版本</li>";tempHTML+="<li>Safari, version = 3.0 或更高版本</li></ul>";oGC.innerHTML=tempHTML;oGC.style.width=canvasW+"px";oGC.style.height=canvasH+"px"; }else{ //support HTML5 go hereoGC=$('gameCanvas');//oGC.style.width=canvasW+"px";//oGC.style.height=canvasH+"px"; oGC.width=canvasW;oGC.height=canvasH; this.canvasObj=oGC; //attend: this == gameSystem object herethis.cxt=oGC.getContext('2d');this.canvasW=canvasW;this.canvasH=canvasH; this.gameUIFace(oGC); }var oIP=$('infoPanel');oIP.style.left="0"; oIP.style.top=canvasH+2; oIP.style.position="fixed"; oIP.style.zIndex=8000;oIP.style.width=(canvasW-paddingLR*2)+"px"; //canvasW+"px"; oIP.style.height=infoPanelH+"px";
};gameSystem.curTime=function(){ //function to display current system timevar dt=new Date()var strHTML=dt.getFullYear()+"-"+(dt.getMonth()+1<10 ? ('0'+(dt.getMonth()+1)): dt.getMonth()+1);strHTML+="-"+(dt.getDate()<10 ? '0'+dt.getDate() : dt.getDate());strHTML+=" "+(dt.getHours()<10 ? '0'+dt.getHours() : dt.getHours());strHTML+=":"+(dt.getMinutes()<10 ? '0'+dt.getMinutes(): dt.getMinutes());strHTML+=":"+(dt.getSeconds()<10 ? '0'+dt.getSeconds() : dt.getSeconds());$('cTime').innerHTML=strHTML;
};gameSystem.TimeOn=function(){this.runTime++; //attend: this == gameSystem here if(this.runTime < 10) $('rTime').innerHTML='000' + this.runTime;if(this.runTime >= 10 && this.runTime<100) $('rTime').innerHTML='00' + this.runTime;if(this.runTime >= 100 && this.runTime<1000) $('rTime').innerHTML='0' + this.runTime;if(this.runTime >= 1000) $('rTime').innerHTML=this.runTime;
};gameSystem.runTimeStart=function(){gameSystem.runTimerID=setInterval(function(){gameSystem.TimeOn();},1000); //attend: here NOT use this.TimeOn(), as this != gameSystem
};gameSystem.runTimePause=function(){clearInterval(this.runTimerID); //attend: this == gameSystem here this.runTimerID="";
};gameSystem.runTimeStop=function(){clearInterval(this.runTimerID); //attend: this == gameSystem here this.runTimerID="";
}gameSystem.runTimeReset=function(){this.runTime=0; //attend: this == gameSystem here clearInterval(this.runTimerID);this.runTimerID="";$('rTime').innerHTML='0000';
};gameSystem.gameFrameUpdate=function(){
//function to play next Game Frame//var c=$("gameCanvas");//var cxt=c.getContext("2d");//c.width=c.width; //clear and redraw it this.canvasObj.width=this.canvasObj.width; //attend: this == gameSystem here bloodBottle.move();westCowboy.move();this.activeTManNum=0;for(this.i=0; this.i<this.tribeMen.length; this.i++){ this.tribeMen[this.i].move(); this.tribeMen[this.i].fighting();if(this.tribeMen[this.i].lifeValue>0) this.activeTManNum++ ; }$("tmActive").innerHTML = this.activeTManNum ;$("tmDeath").innerHTML = this.tribeMen.length - this.activeTManNum ;//v1.2.0, if the active tribe man number less then 2 then new create some tribe man auto.if(this.activeTManNum<=1){if(!this.isGameEnd) this.newTribeMan();}
};gameSystem.newTribeMan=function(){
//function to create new tribe man team and add to Game var i=0;this.lastTribeMenNum = this.tribeMen.length; //attend: this == gameSystem here for(i=0;i<this.initTribeManNum;i++){ var tMan=new tribeMan();tMan.init();this.tribeMen[i + this.lastTribeMenNum]=tMan;}
};gameSystem.initLoad=function(){
//function to initialize when loading this.initGameUI(); var isSupportHTML5=this.isSupportHTML5(); //attend: this == gameSystem here if(isSupportHTML5){ setInterval('gameSystem.curTime()',1000); //attend: can NOT use this.curTime();bloodBottle.init();westCowboy.init(); this.tribeMen.length=0;var i=0; for(i=0;i<this.initTribeManNum;i++){ var tMan=new tribeMan();tMan.init();this.tribeMen[i]=tMan;}}
}gameSystem.gameStart=function(){ if(this.isSupportHTML5()){ //attend: this == gameSystem here this.runTimeStart(); if(!this.gamePlayerID){this.initLoad();this.isGameEnd=false;this.gamePlayerID=setInterval(function(){gameSystem.gameFrameUpdate()},this.gameFrameSpeed); //attend: can NOT use this.gameFrameUpdate(), as the scpoe is change;timeController.timeControllerID=setInterval(function(){timeController.timeOn();},1000); }elsealert('Game is running...');}elsethis.initGameUI();
}gameSystem.gamePause=function(){if(this.isSupportHTML5()){ //attend: this == gameSystem here this.runTimePause(); clearInterval(this.gamePlayerID); this.gamePlayerID="";clearInterval(timeController.timeControllerID);timeController.timeControllerID="";}elsethis.initGameUI();
}gameSystem.gameContinue=function(){if(this.isSupportHTML5()){ //attend: this == gameSystem here if(!this.runTimerID) this.runTimeStart();if(!this.gamePlayerID) this.gamePlayerID=setInterval(function(){gameSystem.gameFrameUpdate()},this.gameFrameSpeed); //attend: can NOT use this.gameFrameUpdate(), as the scopeif(!timeController.timeControllerID) timeController.timeControllerID = setInterval(function(){timeController.timeOn();},1000);}elsethis.initGameUI();
}gameSystem.gameRestart=function(){if(this.isSupportHTML5()){ //attend: this == gameSystem here this.runTimeReset();this.isGameEnd=false;clearInterval(this.gamePlayerID);this.gamePlayerID="";clearInterval(timeController.timeControllerID);timeController.timeControllerID="";this.initLoad();this.gameStart(); }elsethis.initGameUI();
}gameSystem.gameEnd=function(){if(this.isSupportHTML5()){ //attend: this == gameSystem here this.runTimeStop();this.isGameEnd=true;westCowboy.lifeValue=0; var h=0;for(h=0;this.tribeMen.length;h++){this.tribeMen[h].lifeValue=0;}this.gameFrameUpdate();clearInterval(this.gamePlayerID);this.gamePlayerID="";clearInterval(timeController.timeControllerID);timeController.timeControllerID="";}elsethis.initGameUI();
}window.οnlοad=function(){
gameSystem.initLoad(); //page onload event
};//--------------------end: global function define--------------------//---------------------start: bloodBottle define---------------------
var bloodBottle = {
//function to create Blood Bottle bottleVersion:'1.0.0', //blood bottle informationbottlePicSRC:'http://hi.csdn.net/attachment/201112/28/65387_1325068968P78Z.png',bottlePicAuthor:'shenzhenNBA',bottlePicObj:'',gridSize:50,picSN:0, //about cowboypicSN2:0, //about bottleexistNum:0,xSpeed:1, //value is [1~3]ySpeed:1, //value is [1~3]x:0,y:0,r:20, //bottle sizemaxBloodValue:300,initBloodValue:0, bloodValue:0,eatStep:1, //each time eat value isEaten: false, //true=eaten blood, false= no eaten(default)init: function(){this.touchTime=0;this.initBloodValue=generalTools.rangeRandom(this.maxBloodValue*0.5,this.maxBloodValue); this.bloodValue=this.initBloodValue;this.ySpeed = generalTools.rangeRandom2(1,3,0.2); this.xSpeed = generalTools.rangeRandom2(1,3,0.2); if(Math.random()>0.5){ try { //outsite float into canvasthis.x = generalTools.rangeRandom(-this.gridSize,(gameSystem.canvasW+this.gridSize)); this.y = generalTools.rangeRandom2(-this.gridSize,(gameSystem.canvasH+this.gridSize),0.5); }catch(e){this.x=0;this.y=0;}}else{try {//outsite float into canvasthis.x = generalTools.rangeRandom2(-this.gridSize,(gameSystem.canvasW+this.gridSize),0.5); this.y = generalTools.rangeRandom(-this.gridSize,(gameSystem.canvasH+this.gridSize)); }catch(e2){this.x=gameSystem.canvasW;this.y=gameSystem.canvasH;}} var img=new Image();img.src=this.bottlePicSRC;this.bottlePicObj=img; }, isTouch:function(){//function to jugme cowboy touch the blood bottle or not,[true=touch, false=no touch] var dx = Math.abs(this.x - westCowboy.x);var dy = Math.abs(this.y - westCowboy.y);var dl=dx*dx+dy*dy; var tl=this.r*this.r+this.r*this.r; //attend the Size of tribe man and cowboy should be the sameif(dl<tl){ return true;}else{ return false; } },move: function(){ if(this.bloodValue>0){ //only bloodValue > 0 then action here//change the bottle move XY directionif(this.x <= 0) this.xSpeed = Math.abs(this.xSpeed); if(this.x >= gameSystem.canvasW - this.gridSize*0.8) this.xSpeed = -Math.abs(this.xSpeed);if(this.y <= 0) this.ySpeed = Math.abs(this.ySpeed);if(this.y >= gameSystem.canvasH - this.gridSize*0.8) this.ySpeed = -Math.abs(this.ySpeed);if(this.isTouch() && this.isEaten){ //touch bottle and kep Space down then eat bloodif(westCowboy.lifeValue < westCowboy.initLifeValue){ westCowboy.lifeValue += this.eatStep;this.bloodValue -= this.eatStep;if(this.bloodValue<0) this.bloodValue=0;} //draw cowboy if(this.x>westCowboy.x) //face to right //format: drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh) gameSystem.cxt.drawImage(westCowboy.cowboyPicObj,westCowboy.gridSize*this.picSN,westCowboy.gridSize*6,westCowboy.gridSize,westCowboy.gridSize,westCowboy.x,westCowboy.y,westCowboy.gridSize,westCowboy.gridSize); else //face to leftgameSystem.cxt.drawImage(westCowboy.cowboyPicObj,westCowboy.gridSize*(this.picSN+4),westCowboy.gridSize*6,westCowboy.gridSize,westCowboy.gridSize,westCowboy.x,westCowboy.y,westCowboy.gridSize,westCowboy.gridSize); if(this.picSN>=4) this.picSN=0;elsethis.picSN++;gameSystem.cxt.fillStyle="#6600FF";gameSystem.cxt.font="Arial 12px";gameSystem.cxt.fillText(westCowboy.lifeValue,westCowboy.x+westCowboy.gridSize,westCowboy.y); //draw bottlegameSystem.cxt.drawImage(this.bottlePicObj,this.gridSize*this.picSN2,this.gridSize*7,this.gridSize,this.gridSize,this.x,this.y,this.gridSize,this.gridSize); this.picSN2++;if(this.picSN2>10) this.picSN2=0;gameSystem.cxt.fillStyle="#FF0000";gameSystem.cxt.font="Arial 12px";gameSystem.cxt.fillText(this.bloodValue,this.x+this.gridSize/2,this.y); }else{this.x+=this.xSpeed;this.y+=this.ySpeed; if((this.bloodValue/this.initBloodValue)>=1)this.existNum=0;else if((this.bloodValue/this.initBloodValue)>0.9)this.existNum=1;else if((this.bloodValue/this.initBloodValue)>0.8)this.existNum=2;else if((this.bloodValue/this.initBloodValue)>0.7)this.existNum=3;else if((this.bloodValue/this.initBloodValue)>0.6)this.existNum=4;else if((this.bloodValue/this.initBloodValue)>0.5)this.existNum=5;else if((this.bloodValue/this.initBloodValue)>0.4)this.existNum=6;else if((this.bloodValue/this.initBloodValue)>0.3)this.existNum=7;else if((this.bloodValue/this.initBloodValue)>0.2)this.existNum=8;else if((this.bloodValue/this.initBloodValue)>0.1)this.existNum=9;else if((this.bloodValue/this.initBloodValue)>0)this.existNum=10;elsethis.existNum=11;gameSystem.cxt.drawImage(this.bottlePicObj,this.gridSize*this.existNum,this.gridSize*7,this.gridSize,this.gridSize,this.x,this.y,this.gridSize,this.gridSize); gameSystem.cxt.fillStyle="#FF0000";gameSystem.cxt.font="Arial 12px";gameSystem.cxt.fillText(this.bloodValue,this.x+this.gridSize/2,this.y); }//$('num').innerHTML=westCowboy.lifeValue+' -ddd- '+this.bloodValue + ' == '+this.picSN+' = '+this.existNum; /* for TEST, ONLY draw a dot //var c=$('gameCanvas'); //var cxt=c.getContext('2d');gameSystem.cxt.fillStyle="#660099"; //draw the RED dot //, FF0000gameSystem.cxt.beginPath();gameSystem.cxt.arc(this.x,this.y,20,0,Math.PI * 2,true); //draw a dot; syntax: context.arc(centerX, centerY, radius, startingAngle, endingAngle, antiClockwise);gameSystem.cxt.closePath();gameSystem.cxt.fill(); */} }};
//---------------------end: bloodBottle define---------------------
</script>
</body>
</html>
这篇关于WestFighting / 西途决斗 升级 v1.2.0 版 -- 主要增加血瓶功能的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!