So far I am making a dxball game. It works very well. I have one thing I would like to add. Here is what the game does so far:
- a ball and a bar
- when ball hits bar you score 1 point
- every time the ball hits the bar, the ball goes slightly faster
- game over if you miss the ball
Whenever you hit 10 score points, the ball duplicates.
I have tried multiple ways to get this right but I failed everytime.
Code as follow:
// Define variables for the canvas and drawing context
var canvas = document.getElementById(“myCanvas”);
var ctx = canvas.getContext(“2d”);
// Define variables for the ball and its starting position and speed
var ballRadius = 10;
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 2;
var dy = -2;
var ballSpeed = 2;
var points = 0;
// Define variables for the bar and its starting position and size
var barHeight = 10;
var barWidth = 75;
var barX = (canvas.width-barWidth)/2;
// Define a variable for the score
var score = 0;
// Define a function to draw the ball on the canvas
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI*2);
ctx.fillStyle = “#0095DD”;
ctx.fill();
ctx.closePath();
}
// Define a function to draw the bar on the canvas
function drawBar() {
ctx.beginPath();
ctx.rect(barX, canvas.height-barHeight, barWidth, barHeight);
ctx.fillStyle = “#0095DD”;
ctx.fill();
ctx.closePath();
}
// Define a function to move the ball and detect collisions with the walls and the bar
function moveBall() {
x += dx * ballSpeed;
y += dy * ballSpeed;
if (x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
dx = -dx;
}
if (y + dy < ballRadius) {
dy = -dy;
} else if (y + dy > canvas.height-ballRadius) {
if (x > barX && x < barX + barWidth) {
dy = -dy;
ballSpeed += 0.1;
score++;
} else {
alert("GAME OVER");
document.location.reload();
}
}
if (rightPressed && barX < canvas.width-barWidth) {
barX += 7;
} else if (leftPressed && barX > 0) {
barX -= 7;
}
}
// Define functions to handle user input
var rightPressed = false;
var leftPressed = false;
function keyDownHandler(event) {
if (event.keyCode == 39) {
rightPressed = true;
} else if (event.keyCode == 37) {
leftPressed = true;
}
}
function keyUpHandler(event) {
if (event.keyCode == 39) {
rightPressed = false;
} else if (event.keyCode == 37) {
leftPressed = false;
}
}
// Add event listeners for keyboard input
document.addEventListener(“keydown”, keyDownHandler, false);
document.addEventListener(“keyup”, keyUpHandler, false);
// Define a function to update the game state and draw the game elements on the canvas
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
drawBar();
moveBall();
drawScore();
requestAnimationFrame(draw);
}
// Define a function to draw the score on the canvas
function drawScore() {
ctx.font = “16px Arial”;
ctx.fillStyle = “#0095DD”;
ctx.fillText("Score: " + score, 8, 20);
}
// Start the game loop
draw();