84 lines
2.2 KiB
JavaScript
84 lines
2.2 KiB
JavaScript
let canvas = document.getElementById("game");
|
|
let ctx = canvas.getContext("2d");
|
|
let score = 0;
|
|
let running = false;
|
|
let ball, paddle, bricks, rows, cols, speed;
|
|
let hitSound = new Audio("hit.wav");
|
|
let loseSound = new Audio("lose.wav");
|
|
|
|
function startGame(){
|
|
score = 0;
|
|
document.getElementById("score").textContent = score;
|
|
running = true;
|
|
|
|
let diff = document.getElementById("diff").value;
|
|
if(diff === "easy"){ rows = 3; cols = 5; speed = 3; }
|
|
if(diff === "medium"){ rows = 4; cols = 7; speed = 4; }
|
|
if(diff === "hard"){ rows = 6; cols = 9; speed = 5; }
|
|
|
|
paddle = { x:200, w:80, h:10 };
|
|
ball = { x:240, y:200, dx:speed, dy:-speed, r:6 };
|
|
bricks = [];
|
|
|
|
for(let r=0;r<rows;r++){
|
|
for(let c=0;c<cols;c++){
|
|
bricks.push({ x: c*50+30, y: r*20+30, w:40, h:15, hit:false });
|
|
}
|
|
}
|
|
requestAnimationFrame(loop);
|
|
}
|
|
|
|
function loop(){
|
|
if(!running) return;
|
|
ctx.clearRect(0,0,480,320);
|
|
|
|
ctx.fillStyle = "white";
|
|
ctx.fillRect(paddle.x, 300, paddle.w, paddle.h);
|
|
|
|
ctx.beginPath();
|
|
ctx.arc(ball.x, ball.y, ball.r, 0, Math.PI*2);
|
|
ctx.fill();
|
|
|
|
ball.x += ball.dx;
|
|
ball.y += ball.dy;
|
|
|
|
if(ball.x < ball.r || ball.x > 480-ball.r) ball.dx *= -1;
|
|
if(ball.y < ball.r) ball.dy *= -1;
|
|
|
|
if(ball.y > 294 && ball.x > paddle.x && ball.x < paddle.x+paddle.w){
|
|
ball.dy *= -1;
|
|
hitSound.play();
|
|
}
|
|
|
|
bricks.forEach(b =>{
|
|
if(!b.hit && ball.x > b.x && ball.x < b.x+b.w && ball.y > b.y && ball.y < b.y+b.h){
|
|
b.hit = true;
|
|
ball.dy *= -1;
|
|
score += 10;
|
|
document.getElementById("score").textContent = score;
|
|
hitSound.play();
|
|
}
|
|
});
|
|
|
|
bricks.forEach(b =>{
|
|
if(!b.hit){ ctx.fillRect(b.x,b.y,b.w,b.h); }
|
|
});
|
|
|
|
if(ball.y > 330){
|
|
loseSound.play();
|
|
running = false;
|
|
saveScore();
|
|
alert("Game Over");
|
|
return;
|
|
}
|
|
|
|
requestAnimationFrame(loop);
|
|
}
|
|
|
|
window.addEventListener("mousemove", e =>{
|
|
paddle.x = e.clientX - canvas.offsetLeft - paddle.w/2;
|
|
});
|
|
|
|
function saveScore(){
|
|
fetch("save.php?score="+score);
|
|
} |