Hello,大家好,我是兔哥,我又来分享好玩的入门级项目啦。
今天给大家带来的是一个纯JavaScript入门级小游戏:兔子抢金币,规则非常简单,控制屏幕上的兔子去接天上掉下来的金币,接满20个就可以通关。
下面先放出在线试玩的地址:
http://java18.cn/tuzi/index.html
游戏画面:
用键盘上的A和D控制兔子的左右运动。
兔子是会一直跳动的,这其实是用了帧动画:
如上图所示,运用setInterval不停地更换背景图片就可以实现兔子跳动的效果,相关代码:
animation(document.getElementById('tuzi'),"img/奔跑的兔子.png");
这边有一个animation方法,这是我单独封装的一个帧动画方法。
/** * 帧动画函数 * ele 需要控制的DOM元素 * imgUrl 图片地址 */ function animation(ele,imgUrl){ //变更元素的背景图素材 ele.style.backgroundImage = 'url('+imgUrl+')'; ele.style.backgroundRepeat = 'no-repeat'; var index = 0; function run(){ index++; if (index >= positions.length) { index = 0; } var position = positions[index].split(' '); ele.style.backgroundPosition = position[0]+'px '+position[1]+'px'; } running = setInterval(run,80); //clearInterval(running); //清除定时器 }
在这个案例中,金币也是动态的,其实也是用了类似的方法:
金币的动画我封装到了外部js中
//通用的道具类 function Item(type,speed){ var html = ""; var _timer = null; this.draw = function(){ _timer = setInterval(function(){ if(type == 'medicine'){ var itop = Math.ceil( getScreenHeight() * Math.random() ); var ileft = Math.ceil(getScreenWidth() * Math.random() ); /*console.log(itop + "," + ileft); return;*/ html = "<div class='medicine' style='top:"+itop+"px;left:"+ileft+"px'></div>"; }else if(type == 'gold'){ var itop = Math.ceil( getScreenHeight() * Math.random() ); var ileft = Math.ceil(getScreenWidth() * Math.random() ); html= "<img src='img/gold/左斜转0000.png' class='gold'style='top:"+itop+"px;left:"+ileft+"px'></img>"; if($(".gold").length >= 10) return; } $("body").append(html); },speed); }; this.pause = function(){ clearInterval(_timer); } };
还有一个兔子和金币的碰撞逻辑:
function checkTouch($dom){ var tuzi = document.getElementById('tuzi'); var W = tuzi.clientWidth * 2; //兔子的宽度 var H = tuzi.clientHeight * 2; //兔子的高度 var p_X = (tuzi.offsetLeft * 1 + W / 2); //兔子的当前横坐标 var p_Y = (tuzi.offsetTop * 1 + H / 2); //兔子的当前纵坐标 //console.log(p_X + "," + p_Y); var w = $dom.width(); //金币的宽度 var h = $dom.height(); //金币的高度 var m_top = getTop($dom.get(0)); //金币的当前纵坐标 var m_left = getLeft($dom.get(0)); //金币的当前横坐标 var m_X = (m_left * 1 + w/2); var m_Y = (m_top * 1 + h/2); //console.log(Math.abs(p_Y - m_Y) + "========" + (H + h) / 2) if(Math.abs(p_X - m_X) <= (W + w) / 2 && Math.abs(p_Y - m_Y) <= (H + h) / 2 ){ return true; } return false; }
至于最后的排行榜,是用浏览器缓存做的。
完整源码,放到码云上了:https://gitee.com/skyblue0678/rabbit-grabs-gold-coin