Breakout with OOP - Lesson
Collaboration Excersise: Breakout Feature Changes
This notebook will explain the modifications we made to “Functional Breakout”.
Color Changes
The game keeps track of colors using variables. Since these can be easily changed, we deciced to modify some color values:
%%js
// Drawing functions
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
ctx.fillStyle = "rgba(0, 255, 0, 1)"; //Color value here
ctx.fill();
ctx.closePath();
}
function drawPaddle() {
ctx.beginPath();
ctx.rect(paddleX, canvas.height - paddleHeight, paddleWidth, paddleHeight);
ctx.fillStyle = "rgb(0, 127, 0)"; // And another color value here!
ctx.fill();
ctx.closePath();
}
Here, we simply changed the color values in the “ctx.fillStyle” lines.
Ball Speed
Along with out aesthetic changes, we also made some changes to the game mechanics. One of these changes was increasing the ball’s speed every time the ball collides with a block. This adds some extra difficulty to the game. Here’s how we did it:
%%js
function collisionDetection() {
for (let c = 0; c < brickColumnCount; c++) {
for (let r = 0; r < brickRowCount; r++) {
let b = bricks[c][r];
if (b.status === 1) {
if (
x > b.x &&
x < b.x + brickWidth &&
y > b.y &&
y < b.y + brickHeight
) {
//this is the part we are focusing on //
dy = Math.sign(dx)*-0.1 - dy //
dx = Math.sign(dx)*0.1 + dx //
b.status = 0;////////////////////////
score++;
if (b.powerUp) {
powerUps.push({ x: b.x + brickWidth / 2, y: b.y, active: true });
poweredUp = true
}
}
}
}
}
}
The “0.1” and “-0.1” is the key here. These slightly increase the speed every single time a collision between a block occurs.
Changing number of lives and power-up duration
Another thing we decided to change was the number of lives and duration of the built-in powerups. This involved some more simple variable changes:
%%js
// Game loop implementation not shown
x += dx * (activePowerUp == null? 1:2);
y += dy * (activePowerUp == null? 1:2);
This is an interesting piece of code, as it demonstrates a unique feature of Javascript called a ternary operator. The ternary operator is inside of the parentheses, and has three parts (hence the name ternary). The first part is the condition, which simplifies to being either true or false. The “?” tells the interpreter that this is a ternary operator condition. The second value is the value to choose if the condition is true, and the third value after the “:” is the value chosen if the condition is false. What this code does is check if there is no powerup active, and if that is true then the speed is multiplied by one. Otherwise, it is multiplied by two.