JavaScript - Game Part 6

In this lesson we will add gaining points and winning the game.


Now we've gotten all the hard stuff out of the way, so we can handle gaining points and winning the game. The way I am going to code it is that once the opponent gets 10 points, the game is over, but with what you have learned, you can change the rules as you wish.

We can handle all this in the collision function, since that detects if the ball has hit the edges. Let's declare score variables for each player and set up a function that displays the score. Remember how to display text with JavaScript. Let's also call the function in the draw() function.

    let playerScore = 0;
    let opponentScore = 0;
    

...

function drawScore() { context.font = "64px Courier New"; context.textAlign = "center"; context.fillStyle = "#e0e0e0"; context.fillText(`${playerScore} ${opponentScore}`, canvas.width / 2, 60); }

...

function draw() { context.clearRect(0, 0, canvas.width, canvas.height); drawBall(); moveOpponentPaddle(); drawPaddle(playerPaddle); drawPaddle(opponentPaddle); handleCollision(); drawScore(); requestAnimationFrame(draw);

...

The large amount of whitespace between the player score and the opponent score in the string has the purpose of separating the two numbers across the canvas. The screen should look something like this now:

Now we need to update the score every time the ball hits the left or right edges by editing the collision function:

    function handleCollision() {
        ballTop = ballY - BALL_SIZE;
        ballBottom = ballY + BALL_SIZE;
    
        if (ballX < 0) {
            opponentScore++;
            reposition();
        }
        else if (ballX > canvas.width) {
            playerScore++;
            reposition();
        }
            

Now the score should update with every point gained. All we have to do now to restart the game every time the opponent gets 10 points. We can also do this in the collision function:

     function handleCollision() {
         ballTop = ballY - BALL_SIZE;
         ballBottom = ballY + BALL_SIZE;
     
         if (ballX < 0) {
             opponentScore++;
             reposition();
             if (opponentScore === 10) {
                 alert(`GAME OVER, Score:${playerScore}`);
                 document.location.reload();
             }     
         }
            

This will alert the browser with the player's score and then reload with the document.location.reload(); statement.

And that's all for this simple game. Now that you've written all this code, try to understand what each part does and how each part works, and try to tweak the game to your liking or even make your own game! If you want to make more complicated games, you can start researching using JS frameworks, like Phaser. Have fun!

Final Source Code

Link to Playable Game

< Previous