assets/paddle-game-template.md · 24000
inPath(); ctx.rect(brickX, brickY, brickWidth, brickHeight); ctx.fillStyle = "#0095DD"; ctx.fill(); ctx.closePath(); } } } }
### Calling collisionDetection() in the Game Loop
Add the call in your `draw()` function, after drawing all elements:
```javascript
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBricks();
drawBall();
drawPaddle();
collisionDetection();
// ... rest of draw function
}
Step 8: Track the Score and Win
We add a score counter that increments each time a brick is destroyed, and a win condition that triggers when all bricks are gone.
Initializing the Score
let score = 0;
The drawScore() Function
Display the current score on the canvas using text rendering:
function drawScore() {
ctx.font = "16px Arial";
ctx.fillStyle = "#0095DD";
ctx.fillText(`Score: ${score}`, 8, 20);
}
ctx.fontsets the font size and family (like CSS).ctx.fillText(text, x, y)renders text at the given coordinates.- Position
(8, 20)places the score in the top-left corner.
Incrementing the Score
In the collisionDetection() function, increment the score when a brick is hit:
dy = -dy;
b.status = 0;
score++;
Adding the Win Condition
After incrementing the score, check if the player has destroyed all bricks:
score++;
if (score === brickRowCount * brickColumnCount) {
alert("YOU WIN, CONGRATULATIONS!");
document.location.reload();
clearInterval(interval);
}
The total number of bricks is brickRowCount * brickColumnCount. When the score reaches that number, every brick has been destroyed.
Complete collisionDetection() with Score and Win
function collisionDetection() {
for (let c = 0; c < brickColumnCount; c++) {
for (let r = 0; r < brickRowCount; r++) {
const b = bricks[c][r];
if (b.status === 1) {
if (
x > b.x &&
x < b.x + brickWidth &&
y > b.y &&
y < b.y + brickHeight
) {
dy = -dy;
b.status = 0;
score++;
if (score === brickRowCount * brickColumnCount) {
alert("YOU WIN, CONGRATULATIONS!");
document.location.reload();
clearInterval(interval);
}
}
}
}
}
}
Calling drawScore() in the Game Loop
Add the call in your draw() function:
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBricks();
drawBall();
drawPaddle();
drawScore();
collisionDetection();
// ... rest of draw function
}
Canvas Text Methods Reference
| Method/Property | Purpose |
|-----------------|---------|
| ctx.font | Set font size and family |
| ctx.fillStyle | Set text color |
| ctx.fillText(text, x, y) | Draw filled text at coordinates |
Step 9: Mouse Controls
In addition to keyboard controls, we add mouse support so the player can move the paddle by moving the mouse.
Adding the mousemove Event Listener
Register the handler alongside the existing keyboard listeners:
document.addEventListener("mousemove", mouseMoveHandler);
The mouseMoveHandler Function
Calculate the mouse's horizontal position relative to the canvas and update the paddle position:
function mouseMoveHandler(e) {
const relativeX = e.clientX - canvas.offsetLeft;
if (relativeX > 0 && relativeX < canvas.width) {
paddleX = relativeX - paddleWidth / 2;
}
}
How it works:
e.clientX-- the mouse's horizontal position in the browser viewport.canvas.offsetLeft-- the distance from the canvas's left edge to the viewport's left edge.relativeX-- the mouse position relative to the canvas (not the viewport).- The boundary check (
relativeX > 0 && relativeX < canvas.width) ensures the paddle only moves when the mouse is over the canvas. paddleX = relativeX - paddleWidth / 2centers the paddle under the mouse cursor by subtracting half the paddle width.
Complete Event Listener Setup (Keyboard + Mouse)
document.addEventListener("keydown", keyDownHandler);
document.addEventListener("keyup", keyUpHandler);
document.addEventListener("mousemove", mouseMoveHandler);
Both control methods work simultaneously. The player can use arrow keys or mouse -- or switch between them at any time.
Step 10: Finishing Up
The final step adds a lives system (so the player gets multiple chances) and upgrades the game loop from setInterval to requestAnimationFrame for smoother rendering.
Adding the Lives Variable
let lives = 3;
The drawLives() Function
Display the remaining lives in the top-right corner:
function drawLives() {
ctx.font = "16px Arial";
ctx.fillStyle = "#0095DD";
ctx.fillText(`Lives: ${lives}`, canvas.width - 65, 20);
}
Implementing the Lives System
Replace the immediate game-over logic with a lives-based system. When the ball misses the paddle:
if (y + dy < ballRadius) {
dy = -dy;
} else if (y + dy > canvas.height - ballRadius) {
if (x > paddleX && x < paddleX + paddleWidth) {
dy = -dy;
} else {
lives--;
if (!lives) {
alert("GAME OVER");
document.location.reload();
} else {
// Reset ball and paddle positions
x = canvas.width / 2;
y = canvas.height - 30;
dx = 2;
dy = -2;
paddleX = (canvas.width - paddleWidth) / 2;
}
}
}
What happens when a life is lost:
lives--decrements the lives counter.- If
livesreaches0, the game ends with an alert and page reload. - Otherwise, the ball resets to center-bottom, velocity resets, and the paddle resets to center.
Upgrading to requestAnimationFrame
Replace setInterval with requestAnimationFrame for a smoother, browser-optimized game loop:
Old approach (remove):
interval = setInterval(draw, 10);
New approach:
Add requestAnimationFrame(draw) at the end of the draw() function:
function draw() {
// ... all drawing and logic ...
requestAnimationFrame(draw);
}
// Start the game by calling draw() once:
draw();
requestAnimationFrame lets the browser schedule rendering at the optimal frame rate (typically 60fps), which is more efficient than a fixed 10ms interval.
Calling drawLives() in the Game Loop
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBricks();
drawBall();
drawPaddle();
drawScore();
drawLives();
collisionDetection();
// ... rest of logic ...
requestAnimationFrame(draw);
}
Complete Final Game Code
Below is the entire game in a single, self-contained HTML file. This is the final product of all 10 steps combined.
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>2D Breakout Game</title>
<style>
* {
padding: 0;
margin: 0;
}
canvas {
background: #eeeeee;
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="480" height="320"></canvas>
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// --- Ball ---
const ballRadius = 10;
let x = canvas.width / 2;
let y = canvas.height - 30;
let dx = 2;
let dy = -2;
// --- Paddle ---
const paddleHeight = 10;
const paddleWidth = 75;
let paddleX = (canvas.width - paddleWidth) / 2;
// --- Controls ---
let rightPressed = false;
let leftPressed = false;
// --- Bricks ---
const brickRowCount = 3;
const brickColumnCount = 5;
const brickWidth = 75;
const brickHeight = 20;
const brickPadding = 10;
const brickOffsetTop = 30;
const brickOffsetLeft = 30;
const bricks = [];
for (let c = 0; c < brickColumnCount; c++) {
bricks[c] = [];
for (let r = 0; r < brickRowCount; r++) {
bricks[c][r] = { x: 0, y: 0, status: 1 };
}
}
// --- Score and Lives ---
let score = 0;
let lives = 3;
// =====================
// Event Listeners
// =====================
document.addEventListener("keydown", keyDownHandler);
document.addEventListener("keyup", keyUpHandler);
document.addEventListener("mousemove", mouseMoveHandler);
function keyDownHandler(e) {
if (e.key === "Right" || e.key === "ArrowRight") {
rightPressed = true;
} else if (e.key === "Left" || e.key === "ArrowLeft") {
leftPressed = true;
}
}
function keyUpHandler(e) {
if (e.key === "Right" || e.key === "ArrowRight") {
rightPressed = false;
} else if (e.key === "Left" || e.key === "ArrowLeft") {
leftPressed = false;
}
}
function mouseMoveHandler(e) {
const relativeX = e.clientX - canvas.offsetLeft;
if (relativeX > 0 && relativeX < canvas.width) {
paddleX = relativeX - paddleWidth / 2;
}
}
// =====================
// Collision Detection
// =====================
function collisionDetection() {
for (let c = 0; c < brickColumnCount; c++) {
for (let r = 0; r < brickRowCount; r++) {
const b = bricks[c][r];
if (b.status === 1) {
if (
x > b.x &&
x < b.x + brickWidth &&
y > b.y &&
y < b.y + brickHeight
) {
dy = -dy;
b.status = 0;
score++;
if (score === brickRowCount * brickColumnCount) {
alert("YOU WIN, CONGRATULATIONS!");
document.location.reload();
}
}
}
}
}
}
// =====================
// Drawing Functions
// =====================
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
function drawPaddle() {
ctx.beginPath();
ctx.rect(
paddleX,
canvas.height - paddleHeight,
paddleWidth,
paddleHeight
);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
function drawBricks() {
for (let c = 0; c < brickColumnCount; c++) {
for (let r = 0; r < brickRowCount; r++) {
if (bricks[c][r].status === 1) {
const brickX =
c * (brickWidth + brickPadding) + brickOffsetLeft;
const brickY =
r * (brickHeight + brickPadding) + brickOffsetTop;
bricks[c][r].x = brickX;
bricks[c][r].y = brickY;
ctx.beginPath();
ctx.rect(brickX, brickY, brickWidth, brickHeight);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
}
}
}
function drawScore() {
ctx.font = "16px Arial";
ctx.fillStyle = "#0095DD";
ctx.fillText(`Score: ${score}`, 8, 20);
}
function drawLives() {
ctx.font = "16px Arial";
ctx.fillStyle = "#0095DD";
ctx.fillText(`Lives: ${lives}`, canvas.width - 65, 20);
}
// =====================
// Main Game Loop
// =====================
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBricks();
drawBall();
drawPaddle();
drawScore();
drawLives();
collisionDetection();
// Left and right wall collision
if (
x + dx > canvas.width - ballRadius ||
x + dx < ballRadius
) {
dx = -dx;
}
// Top wall collision
if (y + dy < ballRadius) {
dy = -dy;
} else if (y + dy > canvas.height - ballRadius) {
// Bottom edge: paddle collision or lose a life
if (x > paddleX && x < paddleX + paddleWidth) {
dy = -dy;
} else {
lives--;
if (!lives) {
alert("GAME OVER");
document.location.reload();
} else {
x = canvas.width / 2;
y = canvas.height - 30;
dx = 2;
dy = -2;
paddleX = (canvas.width - paddleWidth) / 2;
}
}
}
// Paddle movement (keyboard)
if (rightPressed) {
paddleX = Math.min(
paddleX + 7,
canvas.width - paddleWidth
);
} else if (leftPressed) {
paddleX = Math.max(paddleX - 7, 0);
}
x += dx;
y += dy;
requestAnimationFrame(draw);
}
draw();
</script>
</body>
</html>
Quick Reference: All Game Variables
| Variable | Type | Purpose |
|----------|------|---------|
| canvas | const | Reference to the HTML canvas element |
| ctx | const | 2D rendering context |
| ballRadius | const | Radius of the ball (10) |
| x, y | let | Current ball position |
| dx, dy | let | Ball velocity (pixels per frame) |
| paddleHeight | const | Height of the paddle (10) |
| paddleWidth | const | Width of the paddle (75) |
| paddleX | let | Current horizontal position of the paddle |
| rightPressed | let | Whether the right arrow key is held down |
| leftPressed | let | Whether the left arrow key is held down |
| brickRowCount | const | Number of brick rows (3) |
| brickColumnCount | const | Number of brick columns (5) |
| brickWidth | const | Width of each brick (75) |
| brickHeight | const | Height of each brick (20) |
| brickPadding | const | Space between bricks (10) |
| brickOffsetTop | const | Distance from top of canvas to first brick row (30) |
| brickOffsetLeft | const | Distance from left of canvas to first brick column (30) |
| bricks | const | 2D array holding all brick objects |
| score | let | Current player score |
| lives | let | Remaining lives (starts at 3) |
Quick Reference: All Functions
| Function | Purpose |
|----------|---------|
| keyDownHandler(e) | Sets rightPressed or leftPressed to true on key press |
| keyUpHandler(e) | Sets rightPressed or leftPressed to false on key release |
| mouseMoveHandler(e) | Moves paddle to follow mouse horizontal position |
| collisionDetection() | Checks ball against all active bricks; destroys hit bricks, increments score, checks win |
| drawBall() | Renders the ball at current (x, y) position |
| drawPaddle() | Renders the paddle at current paddleX position |
| drawBricks() | Renders all bricks with status === 1 |
| drawScore() | Renders the score text in the top-left corner |
| drawLives() | Renders the lives text in the top-right corner |
| draw() | Main game loop: clears canvas, draws everything, handles collisions, updates positions |