打砖块html5手机游戏,H5 简单实现打砖块游戏

window.onload = function() {

const oDiv = document.querySelector('.div1');

const oBrick = oDiv.querySelector('.brick');

const oBall = oDiv.querySelector('.ball');

const oBatt = oDiv.querySelector('.bat');

var aBricks = oBrick.getElementsByTagName("div");

creatStone(60);

//生成砖块

function creatStone(num) {

for (var i = 0; i 

var div = document.createElement('div');

div.style.background = setColors();

oBrick.appendChild(div);

div.style.left = div.offsetLeft + 'px';

div.style.top = div.offsetTop + 'px';

}

for (var j = 0; j 

aBricks[j].style.position = 'absolute';

}

}

//设置砖块随机颜色

function setColors() {

let r = parseInt(Math.random() * 256);

let g = parseInt(Math.random() * 256);

let b = parseInt(Math.random() * 256);

return `rgb(${r},${g},${b})`;

}

//设置小球随机滚动

var speedx = parseInt(Math.random() * 4) + 3;

var speedy = parseInt(Math.random() * 3) + 4;

setInterval(function() {

oBall.style.left = oBall.offsetLeft + speedx + 'px';

oBall.style.top = oBall.offsetTop + speedy + 'px';

if (oBall.offsetLeft <= 0 || oBall.offsetLeft > oDiv.clientWidth - oBall.offsetWidth) {

speedx *= -1;

}

if (oBall.offsetTop <= 0 || oBall.offsetTop > oDiv.clientHeight - oBall.offsetHeight) {

speedy *= -1;

}

if (oBall.offsetTop == oDiv.clientHeight - oBall.offsetHeight) {

window.alert('重新开始')

window.location.reload();

}

if (knock(oBall, oBatt)) {

speedy *= -1;

}

for (var i = 0; i 

if (knock(oBall, aBricks[i])) {

speedy *= -1;

oBrick.removeChild(aBricks[i]);

}

}

}, 40);

//设置滑块的移动

oBatt.onmousedown = function(e) {

e = e || window.event;

let x = e.clientX - oBatt.offsetLeft;

document.onmousemove = function(ev) {

ev = ev || window.event;

let l = ev.clientX - x;

if (l <= 0) {

l = 0;

}

if (l >= oDiv.clientWidth - oBatt.offsetWidth) {

l = oDiv.clientWidth - oBatt.offsetWidth;

}

oBatt.style.left = l + 'px';

}

}

document.onmouseup = function() {

document.onmousemove = null;

}

}

function knock(node1, node2) {

let l1 = node1.offsetLeft;

let r1 = node1.offsetLeft + node1.offsetWidth;

let t1 = node1.offsetTop;

let b1 = node1.offsetTop + node1.offsetHeight;

let l2 = node2.offsetLeft;

let r2 = node2.offsetLeft + node2.offsetWidth;

let t2 = node2.offsetTop;

let b2 = node2.offsetTop + node2.offsetHeight;

if (l2 >= r1 || r2 <= l1 || t2 >= b1 || b2 <= t1) {

return false;

} else {

return true;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值