window.onload = init;
function
init(){
var
gameArea = document.getElementsByClassName(
"game"
)[0];
var
rows = 5;
var
cols = 11;
var
b_width = 50;
var
b_height = 20;
var
bricks = [];
var
speedX = 5;
var
speedY = -5;
var
interId =
null
;
var
lf = 0;
var
tp = 0;
var
flap
var
ball;
var
n = 0;
var
st = document.getElementById(
"start"
);
var
rt = document.getElementById(
"reset"
);
var
score = document.getElementById(
"score"
);
score.innerHTML =
"得分:"
+ n;
renderDom();
bindDom();
function
renderDom(){
getBrick();
function
getBrick(){
for
(
var
i = 0; i < rows; i++) {
var
tp = i * b_height;
var
brick =
null
;
for
(
var
j = 0; j < cols; j++) {
var
lf = j * b_width;
brick = document.createElement(
"div"
);
brick.className =
"brick"
;
brick.setAttribute(
"style"
,
"top:"
+ tp +
"px;left:"
+ lf +
"px;"
);
brick.style.backgroundColor = getColor();
bricks.push(brick);
gameArea.appendChild(brick);
}
}
}
var
flap = document.createElement(
"div"
);
flap.className =
"flap"
;
gameArea.appendChild(flap);
var
ball = document.createElement(
"div"
);
ball.className =
"ball"
;
gameArea.appendChild(ball);
}
function
bindDom(){
flap = document.getElementsByClassName(
"flap"
)[0];
window.onkeydown =
function
(e){
var
ev = e || window.event;
var
lf =
null
;
if
(e.keyCode == 37) {
lf = flap.offsetLeft - 10;
if
(lf < 0) {
lf = 0;
}
flap.style.left = lf +
"px"
;
}
else
if
(e.keyCode == 39) {
lf = flap.offsetLeft + 10;
if
(lf >= gameArea.offsetWidth - flap.offsetWidth) {
lf = gameArea.offsetWidth - flap.offsetWidth
}
flap.style.left = lf +
"px"
;
}
}
st.onclick =
function
(){
ballMove();
st.onclick =
null
;
}
rt.onclick =
function
(){
window.location.reload();
}
}
function
getColor(){
var
r = Math.floor(Math.random()*256);
var
g = Math.floor(Math.random()*256);
var
b = Math.floor(Math.random()*256);
return
"rgb("
+ r +
","
+ g +
","
+ b +
")"
;
}
function
ballMove(){
ball = document.getElementsByClassName(
"ball"
)[0];
interId = setInterval(
function
(){
lf = ball.offsetLeft + speedX;
tp = ball.offsetTop + speedY;
for
(
var
i = 0; i < bricks.length; i++) {
var
bk = bricks[i];
if
((lf + ball.offsetWidth/2) >= bk.offsetLeft
&& (lf + ball.offsetWidth/2) <= (bk.offsetLeft + bk.offsetWidth)
&& (bk.offsetTop + bk.offsetHeight) >= ball.offsetTop
) {
bk.style.display =
"none"
;
speedY = 5;
n++;
score.innerHTML =
"得分:"
+n;
}
}
if
(lf < 0) {
speedX = -speedX;
}
if
(lf >= (gameArea.offsetWidth - ball.offsetWidth)){
speedX = -speedX;
}
if
(tp <= 0) {
speedY = 5;
}
else
if
((ball.offsetTop + ball.offsetHeight) >= flap.offsetTop
&& (ball.offsetLeft + ball.offsetWidth/2) >= flap.offsetLeft
&& (ball.offsetLeft + ball.offsetWidth/2) <= (flap.offsetLeft + flap.offsetWidth)
){
speedY = -5;
}
else
if
(ball.offsetTop >= flap.offsetTop){
gameOver();
}
ball.style.left = lf +
'px'
;
ball.style.top = tp +
"px"
;
},20)
}
function
gameOver(){
alert(
"game over"
+
"\n"
+
"您的得分是"
+ score.innerHTML);
clearInterval(interId);
}
}