js消除小游戏(极简版)`
2021-05-13 07:27
标签:child padding 翻转 box 键盘 20px bsp and element
js小游戏极简版
(1) 基础布局
(2)简单的基础样式
* { margin: 0; padding: 0; } div.box { width: 1000px; height: 700px; border: 1px solid #008B8B; box-sizing: border-box; } p { border-radius: 50%; height: 20px; width: 20px; background-color: darkkhaki; position: absolute; top: 660px; left: 490px; z-index: 2; } span { position: absolute; width: 100px; height: 20px; background-color: sandybrown; box-sizing: border-box; border: 1px solid bisque; }
//js添加的小方块样式 .div { width: 100px; height: 20px; background-color: #ccc; position: absolute; top: 680px; left: 450px; }
(3)js部分
一, 添加五排(没排十个小方块)
for (var j = 0; j
(4)获取选择器
var aspan = document.querySelectorAll("span") var odiv = document.querySelector(".div"); var op = document.querySelector("p");
(5)小游戏中方向键的绑定效果
document.onkeydown = function(eve) { var e = eve || window.event; var code = e.keyCode || e.which; var taeget = e.target || e.srcElement; //上下左右控制移动,并设置移动的div的边界; onoff++;//开关 fn(onoff);//下面会用
//上下左右的绑定,即边界限定(不允许超过边界) switch (code) { case 37: if (odiv.offsetLeft - 20 = 1000) { //100是方块的width, odiv.style.left = 1000 - 100 + "px"; } else { odiv.style.left = odiv.offsetLeft + 20 + "px"; //20是元素的高度 } break; case 40: if (odiv.offsetTop + 20 >= 700) { odiv.style.top = 700 - 20 + "px"; } else { odiv.style.top = odiv.offsetTop + 20 + "px"; } break; }
(6)
function fn(n) { if (n == 1) { //操作5的按键事件触发 , 但是按键事件只能触发一次,所以需要借助开关计时,onoff == 1 时才可以用 var t; var lSpeed = random(4, 5)*Math.pow(-1,random(1, 2));//设置个水平方向的速度(正负表示向左向右) 随机数 封装在最后 var tSpeed = -random(4, 5); //设置个数值方向的速度(初始速度向上,所以开始时为负值) clearInterval(t); t = setInterval(function() { // 设置小球的边界 // if(op.offsetLeft + lSpeed>=980){ if (op.offsetLeft+lSpeed >= 980) { // op.style.left = 980 + "px"; lSpeed = lSpeed * (-1); //设置小球的速度方向 触碰到边界就反向 } else if (op.offsetLeft+lSpeed =odiv.offsetTop-20)&&(op.offsetTop=odiv.offsetLeft-10)&&(op.offsetLeft=690){ // 判断小球出局,游戏结束,所有数据重置 alert("结束"); clearInterval(t); op.style.left = "490px"; op.style.top = "660px"; odiv.style.top = "680px"; odiv.style.left = "450px"; for(var i=0;i= aspan[i].offsetTop)
&&(op.offsetLeft-10 >= aspan[i].offsetLeft)&&(op.offsetLeft+10{ aspan[i].style.display = "none"; //小球和方块相接触 小方块的display:none; l--; console.log(l) //测试专用 if(l == 0){ alert("游戏结束") //方块全部消失时,弹出游戏结束; } } } }, 30)
}
}
最后差点忘记
function random(m, n) { return Math.round(Math.random() * (m - n) + n) }
完整效果图如下:
:
(7)测试:
bug1:开始按键盘不能按上键, 原因:小球与灰色方块接触返回机制设置(方块的中间的水平线为小球反弹分割线,反复触碰),所以很快速度翻转
bug2:灰色方块去碰弹回来的小球时,如果是侧边接触,会发生bug1,同上
bug3:有些方块看似碰到 缺不消失, 原因,触碰小时规则的书写也许有点不当之处
js消除小游戏(极简版)`
标签:child padding 翻转 box 键盘 20px bsp and element
原文地址:https://www.cnblogs.com/xy88/p/12001808.html