Quantcast
Channel: Allstate NI Blogs » Mark B
Viewing all articles
Browse latest Browse all 12

HTML5 Pong Game Tutorial – Part 4

$
0
0

In part 3 of the tutorial we finished off the mechanics of our simple HTML5 pong game. In this final part we are going to add finishing touches to the game and add a couple of nice to haves. By the end of this tutorial we will have:

  • Added logic to keep score
  • Added labels to display who won the point
  • Added a button to start a new game once one has finished
  • Added logic to alternate who receives the service depending on who won the last point
  • Added sound to numerous aspects of the game

By the end of this tutorial you should have something that is similar to this – http://jsbin.com/ulowiy/11/

The HTML

We need to add another div to hold our replay button that will allow the user to click to start a new game, let’s place it just below the closing </canvas> tag.

<div id = "replay">
      <button type="button" onClick="location.reload();">Play Again</button>
</div>

Give the div an id of “replay” and add your button in that div. Give the button a class of “button” and onClick make a small JavaScript call that will reload the page.

The CSS

Let’s give our new div and button some CSS so that it they blend in with the rest of the game.

#replay
 {
    display: none;
 }

.button
 {
    font-family: 'Rambla', sans-serif;
    font-size:28px;
    color: #717073;
 }

Here we are hiding the replay div (and thus the button) when the page loads. We will show it when we need it using JavaScript later in the tutorial. The button css sets the font, font size and font color of our “Play Again” button.

The JavaScript

The first thing we want to do is add the logic that will keep the score of each game, let’s make the winner of our game the first person to five points. To do this we will need two more global variables, one for the player score and one for the computer score.

//scores
var playerScore = 0;
var compScore = 0;

We will also need a new function that will update our scoreboard. We can place this function at the bottom just before the init() call.

//this function updates the scoreboard
function updateScore()
{
    $('#playerScore').html(playerScore);
    $('#compScore').html(compScore);
}

All this function does is update the spans we created for the scoreboard in the first tutorial with the values stored in the global variables we just created. Now we need to add our calls to this function and also write the code that will increment the correct variable depending on who won the point. In the drawGame() function find the two places where we clear the interval and add the following lines just before the clearInterval(refreshStage) line.

//increase players score variable by one
playerScore++;
//update the scoreboard
updateScore();

 

//increase the computers score by one
compScore++;
//update the scoreboard
updateScore();

If you play the game now you will notice that the scores increase depending on who scores the point. If we create another global variable to hold the value of who the last winner was then we can alternate who receives the service dependant on who won the last point. Create a new global variable called lastwinner and set it to “comp” so that the computer always receives the first serve.

var lastWinner = "comp";

We will set this variable just after the clearInterval(refreshStage) lines that we identified above and we are also going to relocate the logic that waits three seconds before starting a new game to a new function called checkScore() that we will call after the lastWinner variable is set.

lastWinner = "player";
//check if either player has won the overall game by getting
//5 points or if a new game needs to be spawned
checkScore();

 

lastWinner = "comp";
//check if either player has won the overall game by getting
//5 points or if a new game needs to be spawned
checkScore();

The check Score() function will also check if either player has made it to five points yet, display messages and toggle the replay div to show/hide. Let’s define it at the bottom just before our init() function.

//this function checks if either player has won the overall game by getting
//5 points or if another game needs to be played.

function checkScore()
{
    //if both players scores are less than 5
    if (playerScore < 5 && compScore < 5)
    {
        //play another game after 3 second (3000ms) delay
        var wait = setTimeout(init, 3000);
        //show a message to the player stating the game is restarting
        ctx.fillStyle = "#717073";
        ctx.font = "48px 'Rambla', sans-serif";
        if (lastWinner == "comp")
        {
            ctx.fillText("Computer +1", 275, 400);
        }
        else
        {
            ctx.fillText("You +1", 310, 400);
        }

    }
    //if the players score equals 5
    else if (playerScore == 5)
    {
        //show a message to the player stating they won
        ctx.fillStyle = "#EE3424";
        ctx.font = "48px 'Rambla', sans-serif";
        ctx.fillText("You win!", 315, 400);
        //display button for playing a new overall game
        $('#replay').css('display', 'block');

    }
    //if the computers score equals 5
    else if (compScore == 5)
    {
        //show a message to the player stating they lost
        ctx.fillStyle = "#EE8722";
        ctx.font = "48px 'Rambla', sans-serif";
        ctx.fillText("You lose!", 305, 400);
        //display button for playing a new overall game
        $('#replay').css('display', 'block');
    }
}

The function above checks if either player has score five points, if not a message is shown telling the user who scored the point and another game is started after a three second pause. If either the comp or the player has scored 5 points then the interval is cleared, a message is displayed to say who won the game and the div that holds the button is shown to allow the user to play another game.

Now let’s add the logic that alternates who receives the service depending on who won the last point. In the init() function locate where you are setting the directionX value and change the code to the following:

//once the game begins, the ball will move 6 pixels right every
//time the game stage is redrawn. A minus number would send the
//ball left
if (lastWinner == "comp")
{
    directionX = 6;
}
else
{
    directionX = -4;
}

The above code will send the ball to the right if the computer won the last point or send the ball to the left if the player won the last point. Again feel free to experiment with these numbers until you find a pace that suits you. Now when you play the game if you win a point the ball will be served towards you first, so be prepared.

The final touch to our game is to add some sound effects – Luckily HTML5 makes this a doodle to add. All we need to do is add global variables for each of the sounds we want:

//sounds
var paddleBeep = new Audio("http://cd.textfiles.com/10000soundssongs/WAV/POP.WAV");
var sideBeep = new Audio("http://cd.textfiles.com/10000soundssongs/WAV/BTN3_22.WAV");
var scoreBeep = new Audio("http://cd.textfiles.com/10000soundssongs/WAV/BEAM.WAV");
var overBeep = new Audio("http://cd.textfiles.com/10000soundssongs/WAV/BUZZER.WAV");

Then when you want the sound to play you simply call variableName.play(). We will need to add paddleBeep.play() in two places where the ball impacts either paddle. We will add sideBeep.play() when the ball hits either sideline. When the ball makes it past either paddle then we will add scoreBeep.play() and when the game is won by someone getting to 5 points we will add overBeep.play(). By now you should be familiar enough with the code to find those places yourself, but if you are struggling you can always check the complete code for this tutorial here: http://jsbin.com/ulowiy/11/edit

Hopefully you now have a working pong game like the one in the above example. I hope you have enjoyed these short tutorials and more importantly have learnt a thing or two along the way.

Mark


Tagged: Allstate NI, Allstate Northern Ireland, Belfast, Canvas, CSS, Game, HTML5, IT, JavaScript, JQuery, Mark B, Northern Ireland, Pong, Software Developer, Software Development

Viewing all articles
Browse latest Browse all 12

Latest Images

Trending Articles





Latest Images