效果如下:
游戏规则:
把行走的南瓜拖到下方的"锅里"游戏倒计时30s,时间越短南瓜速度越快,抓住的南瓜积分达到120分即可获得抽奖机会
整体思路:
圈出南瓜行走区和煮锅区南瓜从行走区右方随机位置出现给南瓜添加“跳走”的动画南瓜“跳出”行走区后删除拖曳南瓜的时候检测touchmove
事件,实时改变南瓜的位置拖曳的南瓜到达煮锅区的时候,南瓜被煮增加积分,删除南瓜时间到判断积分是否获得抽奖机会,然后抽奖或是再玩一次
关键代码:
<script>var param={ppkTime:30,//单次游戏总时间t:300,//跳一下需要的时间ppkNum:0,//抓到的南瓜数量out_time:500,//南瓜出来的速度inter:10//抓一个南瓜所得积分};function CatchPumpkin(fig){this.out_time=fig.out_time;this.ppkTime=fig.ppkTime;this.ppkNum=fig.ppkNum;this.inter=fig.inter;this.t=fig.t;this.init=function(){let that=this;that.jump();that.randomOut();that.timer();$(".catchNum").html(that.ppkNum)};var timer2,timer3;// 南瓜跳this.jump=function(){let that=this;var leftN=(Math.random()*20+20);timer2=setInterval(function(){$(".pumpkin").removeClass("on").animate({"left":"-="+leftN+"px","top":"-=20px"},that.t/2);$(".pumpkin").animate({"left":"-="+leftN+"px","top":"+=20px"},that.t/2,function(){$(".pumpkin").addClass("on");});},that.t);};// 随机南瓜this.randomOut=function(){let that=this;timer3=setInterval(function(){var topN=(Math.random()*3);$(".run-pumpkin").append("<span class='pumpkin on' style='top:"+topN+"rem;'</span>");that.catch();that.jump();},that.out_time)};// 倒计时this.timer=function(){let that=this;$(".time span").html(that.ppkTime);var timer1=setInterval(function(){that.t-=5;$(".pumpkin").each(function(i,e){if(e.offsetLeft<-155){e.remove();}});clearInterval(timer2);if(that.ppkTime>0){that.ppkTime-=1;if(that.ppkTime<10){that.ppkTime="0"+that.ppkTime;}}else{$(".pumpkin").remove();clearInterval(timer1);clearInterval(timer2);clearInterval(timer3);//游戏时间到var totalInter = that.ppkNum*that.inter;//本轮总积分$(".inter").html(totalInter+"积分")//判断是否满120积分if(totalInter<120){$(".drawNow").hide();}else {$(".onceAgain").hide()}$(".gameOver").show();}$(".time span").html(that.ppkTime);},1000)};// 抓南瓜this.catch=function() {var that=this;// 拖曳$(".pumpkin").each(function(){var this_ = $(this)var pan,pumpkin_top,pan_left, pan_right, pan_top,this_left,this_top;this_.on('touchstart', function(evt) {pan=$(".pan");pumpkin_top = this_.parent().position().top;pan_left = pan.position().left;//锅的左边距pan_right = pan.position().left+pan.width();//锅的右边距pan_top = pan.position().top;//锅的上边距var e = event || evt;e.preventDefault();}).on('touchmove', function(evt) {var e = event || evt;e.preventDefault();if (e.targetTouches.length == 1) {var touch = e.targetTouches[0]; // 把元素放在手指所在的位置this_.css("left",(touch.pageX- parseInt(this_.width())/2 + 'px'));this_.css("top",(touch.pageY -pumpkin_top - parseInt(this_.height())/2 + 'px'));this_.stop();this_left = this_.position().left;this_top = this_.position().top;//到达锅的区域if(this_left>pan_left && this_left<pan_right && this_top+pumpkin_top>pan_top){this_.remove();$(".catchNum").html(that.ppkNum+=1);}}}).on('touchend', function(evt) {var e = event || evt;e.preventDefault();})});}}var start = new CatchPumpkin(param);start.init();</script>
小白菜一枚,欢迎指正(〃‘▽’〃)
效果预览:https://bestjhh.github.io/pumpkin/
完整代码:/bestjhh/pumpkin