每天一个jquery插件-做打字游戏
做打字游戏
嗯,看了看别的大佬做的打字游戏,我感觉我好想也能弄个低配的诶,所有有了今天的笔记
效果如下
代码部分
*{
margin: 0;
padding: 0;
}
.rel{
position: relative;
overflow: hidden;
display: flex;
justify-content: center;
align-items: center;
}
.item{
font-size: 48px;
position: absolute;
z-index: 2;
}
#score{
z-index: 1;
width: 200px;
height: 200px;
font-size: 48px;
display: flex;
justify-content: center;
align-items: center;
color: gray;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>做打字游戏</title>
<script src="js/jquery-3.4.1.min.js"></script>
<script src="js/zdzyx.js"></script>
<link href="css/zdzyx.css" rel="stylesheet" type="text/css" />
<style>
html,body{
width: 100%;
height: 100%;
}
#div{
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div id="div"></div>
</body>
</html>
<script>
var temp = zdzyx("div");
temp.load();
</script>
var zdzyx = function(id){
var $id = $("#"+id);
$id.addClass("rel");
$score = $("<div id='score'>0</div>");
$score.appendTo($id);
return{
$id:$id,
w:0,//容器宽度
h:0,//容器高度
t:null,//这个用来计时器的
arr:[],//这个用来存随机出来的数据对象的
span:1200,//这个是多久出一个字的速度
fall:10000,//这个是字多久会触及边界,
score:0,
$score:$score,
load:function(){
var that = this;
that.first();
//开始加载动画了
that.t = setInterval(function(){
var obj = {
};
var num = Math.floor(Math.random()*26)+97;
obj.str = String.fromCharCode(num);
obj.$dom = $("<div class='item'>"+obj.str+"</div>");
obj.$dom.css({
"color":"rgb("+Math.floor(Math.random()*256)+","+Math.floor(Math.random()*256)+","+Math.floor(Math.random()*256)+")",
"left":Math.floor(Math.random()*that.h),
"bottom":that.h
})
obj.$dom.appendTo(that.$id);
obj.$dom.animate({
"bottom":"-52px"
},that.fall)
obj.t = setTimeout(function(){
that.score-=1;
that.draw();
obj.f = false;//假如已经扣了分了,那么这个元素不应该再被触发了
},that.fall)
obj.f = true;
//然后将对应的控制对象放到数组之中
that.arr.push(obj);
},that.span)
//开始监控键盘敲击,然后开始打字部分的判断
$(document).keydown(function(e){
var str = e.key.toLowerCase();
var temp = that.arr.find(n=>n.f==true&&n.str==str);
if(temp){
clearTimeout(temp.t);
temp.$dom.remove();
that.score+=1;
that.draw();
temp.f = false;
}
})
},
first:function(){
//这里是初始化一些参数的
var that = this;
that.w = that.$id.width();
that.h = that.$id.height();
$(window).resize(function(){
that.w = that.$id.width();
that.h = that.$id.height();
})
},
draw:function(){
var that = this;
that.$score.text(that.score);
//做点难度限制
if(that.score<5){
that.fall = 10000;
}else if(that.score<10){
that.fall = 5000;
}else if(that.score<15){
that.fall = 3000;
}else{
that.fall = 500;
}
}
}
}
实现思路
- 拿到目标容器的宽高知道坐标系
- 然后确定一些要是用的基本参数,代码都打了注释
- 接着就是一个计时器不停的给容器丢下落的字母,字母随机产生的ascll码转的,然后把dom和字母本身结合成一个对象,存进数组里面,也不用管啥先后了,我们查的方式时候默认是查最前面的,最多加个f参数来标记这条数据是不是在查询范围内,就是说这个字母已经被敲击触发了,或者落地扣分了,这些都要更改f的状态,让他们不处于敲击触发的范围。
- 此外就是我把下落速度和出现的速度参数也分离出来处理,这样子可以随着积分的增加主键提高难度,游戏名字我都想好了,17分挑战,虽然到了15分下落字体就会贼快,但是为啥不挑战二连斩,咕嘿嘿
- 完事,碎觉