日期:2014-05-17 浏览次数:20555 次
?
最近在网上看到一款灵敏测试的flash小游戏,很感兴趣,于是想自己也写写。一开始是使用JS去实现的,算法是写出来了,但后来发现性能实在太差了,于是放弃了,后来想起HTML5这门新崛起的技术,在动画视频等各方面性能都很强大,而且WEB很有发展前景,很受众多浏览器及大公司欢迎,一直将学习重心放在PHP上,也想多接触一下其他语言,所以就改用html5来实现。废话就不多说了,想了解更的关于HTML5技术就去百度、谷歌一下吧!
? ? ? 程序写得比较简单,算是实现了效果,有时间再去优化一下!
? ? ? 测试地址:http://meego123.net/sheep/
? ? ?源代码:http://meego123.net/post-61.html
以下是部份代码片段
?
function init(){ var map=document.getElementById('map'); context=map.getContext('2d'); drawMap();//创建地图 drawSheep();//绘制绵羊 /*每3秒钟生随机出现一个狼*/ wolfTimeout=setTimeout(createWolfs,wolfRate+wolfCounts*3000); wolfRate+=wolfCounts*3000; drawWolfs(); } 绘制绵羊 /*绘制绵羊*/ function drawSheep(){ var sheepImg=new Image(); sheepImg.src='images/lsheep.gif'; if(moveLeft){ sheepXspeed--; } if(moveRight){ sheepXspeed++; sheepImg.src='images/rsheep.gif'; } if(moveUp){ sheepYspeed--; } if(moveDown){ sheepYspeed++; } context.drawImage(sheepImg,sheepX,sheepY); context.fill(); /*移动距离计算*/ if(sheepX>=0&&sheepX<=(mapWidth-sheepWidth)){ sheepX+=sheepXspeed; }else if(sheepX<0){ sheepX+=Math.abs(sheepXspeed); }else if(sheepX>(mapWidth-sheepWidth)){ sheepX-=Math.abs(sheepXspeed); } if(sheepY>=0&&sheepY<=(mapHeight-sheepHeight)){ sheepY+=sheepYspeed; }else if(sheepY<0){ sheepY+=Math.abs(sheepYspeed); }else if(sheepY>(mapHeight-sheepHeight)){ sheepY-=Math.abs(sheepYspeed); } sheepXspeed*=sheepFriction; sheepYspeed*=sheepFriction; }
? 随机增加一个狼
?
/*增加狼群*/ function createWolfs(){ /*0123 上下左右*/ direction=parseInt(Math.random()*4); /*狼随机出现的x y 坐标*/ wx=parseInt(Math.random()*(mapWidth-wolfWidth)); wy=parseInt(Math.random()*(mapHeight-wolfHeight)); var wolfObj=new Object(); switch(direction){ case 0: wolfObj.x=wx; wolfObj.y=0; break; case 1: wolfObj.x=wx; wolfObj.y=mapHeight-wolfHeight; break; case 2: wolfObj.x=0; wolfObj.y=wy; break; case 3: wolfObj.x=mapWidth-wolfWidth; wolfObj.y=wy; break; } wolfs.push(wolfObj); clearTimeout(wolfTimeout); }
? 代码实现都比较简单~都是一些比较基础的js,见笑了!