Pong Session 3 of 3

Level: Intermediate (11+) Duration: 3 × 1 Hour

Power Moves

To implement a power move, we're going to create two functions. One to start the power move, and another to stop it.

Part 6A: Start Power Move 30 minutes

First, give your power move a cool name. In our first example, we'll double the speed of the ball and change its color to red. We'll call it The Fire Ball.

The exact code for your power move will depend on the move itself. See the Kid.js framework reference for commands and properties you can use on the ball or paddles.

function startFireBall() { ball.speed = ball.speed * 2 ball.color = 'red' }

Next, we attach the start function to a keyboard key. We'll use "f" for Fire Ball. Depending on which player the power move is intended for, you might want to choose a key on their side of the keyboard.

function startFireBall() { ball.speed = ball.speed * 2 ball.color = 'red' } on('f', startFireBall)

Part 6B: End Power Move 15 minutes

Now write a function to undo everything the start function did.

function endFireBall() { ball.speed = ball.speed / 2 ball.color = 'default' }


Next, we'll set up the end function to run a few seconds after the start function. JavaScript has a function called setTimeout() to do just this. It takes two parameters. The first is the function to run, the second is the number of milliseconds to wait before running it.

We'll add this to the end of our start function. For the move to last 2 seconds, we use 2000 for the number of milliseconds to wait.

function startFireBall() { ball.speed = ball.speed * 2 ball.color = 'red' setTimeout(endFireBall, 2000) }

Another Example

Let's look at another example. This power move, called The Extender, will temporarily increase the length of the player's paddle.

function startExtender() { player1.height = 200 setTimeout(endExtender, 5000) } function endExtender() { player1.height = 100 } on('q', startExtender)

Part 6C: Limit Power Moves 15 minutes

To prevent complete mayham, let's put a limit on the number of power moves each player can use. We'll create two new varibles to keep track of the number of power moves remaining for each player, and start them off at 2.

let player1PowerMoves = 2 let player2PowerMoves = 2

In the code for a player's power move, we need to first check that they have moves remaining. If they do, we'll start the move and decrease the number remaining.

function startExtender() { if (player1PowerMoves > 0) { player1.height = 200 setTimeout(endExtender, 5000) player1PowerMoves = player1PowerMoves - 1 } }

It may be helpful to display the number of moves remaning for each player next to their score.

display(150, 50, player1PowerMoves) display(width - 150, 50, player2PowerMoves)

To be fair, we'll want to set up similar functions for Player 2. Advance to the next page to view the complete game.