Making a Mini-Game Step 2: Setting it up 2


Note: This is a step-by-step example of how to go about creating a mini-game. In this example, you get an animated pet dog. For every multiplication problem you solve, you and your dog get to do more activities.

To see the first post in the series, Game Design, click here.

I pasted all of the javascript code at the bottom of  this post, but right now I want to go through it line by line and explain what I’m doing and why.

But first, more HTML

First, if I’m going to have a math problem that they do before the animation, I’m going to need to add that to the HTML.

At the top of the HTML, right under the div with the ID of container, I’m going to add this:

<form name="math" id="mathform">
    <table>
        <tr >
            <td  align="right"><p>&nbsp;</p>
                <p><strong>WHAT IS</strong><input type="text" name="firstnum" size="4"></p>
           </td>
       <td align="center"><p> </p>
                <p>X</p>
        </td>
            <td align="left"><p></p>
                <p>
                    <input type="text" name="secondnum" size="4"> ?
                </p></td>
        </tr>
        <tr ><td colspan="3" align="center"><hr>
                <h3><em>Type in your answer and click on the <strong>ANSWER</strong> button.</em></h3><p>
                 <input type="text" name="answer" size="5" id="answer">
             <input type="button" value="ANSWER" onClick="answerit();">
                </p>
      <p class="hidden" id="nullans">  Put Your Answer In The Box Above and click the ANSWER button!'</p>
            </td>
        </tr>
    </table>
</form>

It will create a form that looks like this:

form for math problem

A few things to note:

  1. A function named answerit is called when you click on the button.
  2. There is a paragraph tag with an Id of null and a class of hidden. This will be hidden when the page loads, but if you click the submit button without having entered an answer, this paragraph will be shown with the message that you need to put in an answer.
  3. There are two input text boxes with the names firstnum and secondnum . They have no values now, but they will in a minute. The form is named math. All of those names will be used in the script below so if they don’t match the html, there will be an error.

A  look at the javascript for setting up the math problem

<link rel="stylesheet" href="javascript/jquery-ui-1/development-bundle/themes/ui-lightness/jquery.ui.all.css" />
<script type="text/javascript" src="javascript/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="javascript/jquery-ui.min.js"></script><script type="text/javascript" src="scripts/CanvasInput.js"></script>


First, we link to jquery and CanvasInput libraries. These are super-useful libraries and I’m a big fan of not re-inventing the wheel. We’ll see how these are used in the next post. You might wonder why I don’t link to the Google hosted libraries. The reason is that our games are used in many remote communities where Internet access is unreliable, so we have some components of our games that can be played off-line and this is one of those.

Next, we start with our own code.

<script type= “text/javascript” >

window.addEventListener(‘load’, eventWindowLoaded, false);

This keeps the window from loading until all of the images are available so that you don’t see the images showing up one a time or half an image and then the rest appearing.

var puppy = new Image() ;
puppy.src = "images/dog_idle2.png";
var counter = 0 ;
var animationFrames =[1,2,3,4,5,6,7,8];
var frameIndex = 0 ;
var dx = 0 ;
var dy = 0;
var x = 150;
var y= 150 ;
var theCanvas;
var context ;
var context2 ;
var canvas2 ;
var message ;

 

 

All of this just creates the variables I will be using.  It’s important to note that puppy is a new Image() . That is our game character.

The src file for puppy is originally set to the idle sprite sheet. This will change at different points in the game.

You can see that animationFrames is an array, and it has 8 members, which are just going to be the numbers in a sequence. The animation starts at 0, in the first frame of the sprite sheet.  Originally, dx (the change in x) and dy (the change in y) are set at 0, as the puppy doesn’t move in the first scene. The x and y variables set the initial location of our puppy on the canvas.

The rest of the variables I want available globally, so they can be used in multiple functions are also defined here. These are the two canvases and associated contexts, a message and a problem number.

Getting our first problem

First, we have a function to create a random number between whatever two values are specified in our call to it. This is a delightful little function we can use over and over, whether we want numbers between 1 and 20 or -56,078 and 1,000,000. It can be used whether regardless of what we are going to do with the number – multiply, divide, add, display. Because the javascript random function returns a number between 0 and 1, i need to multiply it by the difference between the minimum and the maximum to get a number larger than one, and then round it so our player is not asked to multiple 1.178 by 4.375.

Do the math 

 var num=Math.round(Math.random()*(max-min))+min;

Let’s say, we want to generate a number between 2 and 12. The difference between max and min, or 12- 2, = 10. Our Math.random() function gives us a random number of .6012.   Multiplied by 10, we get 6.012.   The Math.round function is going to round that number to 6.

Wait a minute, though. What about when we get a number like .0011 ? Multiplied and rounded, that would give us 0, and we don’t want that. We want numbers between 2 and 12. That’s why we add the minimum number (min) back on at the end.

The statement

return num;

will return the random number generated.

  // SECTION TO CREATE PROBLEMS ;
    function randnum(min,max)   {
        var num=Math.round(Math.random()*(max-min))+min;
        return num;
    }

Okay, that’s enough for today. I’m sick with some  cold/ flu bug so I’m alternating between blogging and lying in bed drinking nasty-tasting medicine.  I’ll explain the using the random numbers to display as a problem tomorrow. Once you’ve got this set up, it’s pretty easy.

 

++++ ALL OF THE CODE +++++++++

<script type="text/javascript">
    window.addEventListener('load',eventWindowLoaded, false);
    dogname = "";
    pts = 0;
    var dog = new Image();
    var puppy = new Image() ;
    var bone = new Image();
    dog.src ="images/dog_mom.png";
    puppy.src = "images/dog_idle2.png";
    var counter = 0 ;
    var animationFrames =[1,2,3,4,5,6];
    var frameIndex = 0 ;
    var dx = 0 ;
    var dy = 0;
    var x = 150;
    var y= 150 ;
    var theCanvas;
    var context ;
    var context2 ;
    var canvas2 ;
    var message ;
    var probnum ;

    // SECTION TO CREATE PROBLEMS ;
    function randnum(min,max)   {
        var num=Math.round(Math.random()*(max-min))+min;
        return num;
    }
    function getProb()
    {
        $('#mathform').show();
        $('#canvas').hide();
        $('#canvas2').hide();
        probnum++ ;
        document.math.answer.value= "";
        document.getElementById('answer').focus();
        var choose1=randnum(2,12);
        var choose2=randnum(2,12) ;
        document.math.firstnum.value=choose1;
        document.math.secondnum.value=choose2;
        rightanswer=choose1 * choose2;


    }
    /* SECTION TO SCORE MATH PROBLEMS  */

    function answerit()
    {
        var theiranswer=eval(document.math.answer.value);
        var   wrongans = document.getElementById('theAnswer') ;
        if (theiranswer==null) {
            $('#nullans').show() ;
            document.math.answer.select();
        }
        else {
            if (theiranswer == rightanswer) {
                $('#mathform').hide();
                pts++ ;
                wrongans.innerHTML = "<h2>"  + rightanswer + " is correct! </h2>"  ;

                setTimeout(function(){
                    $('#theAnswer').hide();
                    switch (pts) {
                        case 1:
                            playGame1() ;
                            break;
                        case 2:
                            playGame2() ;
                            break;
                        case 3:
                            playGame3() ;
                            break;
                    }

                },1500) ;

            }
            else {
                $('#mathform').hide();
                wrongans.innerHTML = "<h2>" + theiranswer + " is wrong!nn" + rightanswer + " is correct! " + " Try another problem.</h2>"  ;
                wrongans.innerHTML += '<video  autoplay width = "480" height="300" tabindex="0"> <source type="video/webm" src="images/wrong_howl.webm"></video>' ;
                $('#theAnswer').show() ;

                setTimeout(function(){
                    $('#theAnswer').hide() ;
                    getProb() ;
                },9500) ;
            }

        }

    }



    // Creates input form on canvas ;
    function one(){
        var input = new CanvasInput({
            canvas: document.getElementById('canvas2'),
            fontSize: 18,
            fontFamily: 'Arial',
            fontColor: '#212121',
            fontWeight: 'bold',
            y: 100 ,
            x:50,
            width: 200,
            padding: 8,
            borderWidth: 1,
            borderColor: '#000',
            borderRadius: 3,
            boxShadow: '1px 1px 0px #fff',
            innerShadow: '0px 0px 5px rgba(0, 0, 0, 0.5)',
            placeHolder: 'Enter name. Hit Enter.'
        });
        canvas2 = document.getElementById("canvas2");
        context2 = canvas2.getContext("2d");
        context2.fillStyle="white";
        context2.fillRect(5,60,530,30) ;
        context2.fillStyle="black";
        context2.font = "bold 18pt sans-serif" ;
        context2.fillText("Hello! I'm your dog. Please give me a name.",15,80) ;


        input.onsubmit(function()
        {
            dogname = input.value();
            $("#canvas2").hide() ;
            setTimeout(getProb(),2000);
        });

    }


    function eventWindowLoaded() {
        $('#mathform').hide();
        getProb() ;
    }



    function drawScreen(){
        theCanvas = document.getElementById("canvas");
        context = theCanvas.getContext("2d");
        context.clearRect(0, 0, 900, 540);
        context.drawImage(puppy,0,0, 300,300, x,y,300,300) ;
    }
    function playGame1(){
        $('#mathform').hide();
        $('#canvas').show();
        $('#canvas2').show() ;
        drawScreen();
        one() ;
    }

    function playGame2(){
        $('#mathform').hide();
        $('#canvas').show();
        var startTime = new Date().getTime();
        var interval = setInterval(function(){
            if(new Date().getTime() - startTime > 9000){
                document.getElementById("audio1").src = "";
                document.getElementById("audio2").src = "";
                clearInterval(interval);
                return getProb();
            }
            drawScreen2();
        }, 100);
        document.getElementById("audio1").src = "sounds/dogbark.ogg";
        document.getElementById("audio2").src = "sounds/dogbark.mp3";
    }

    function drawScreen2() {
        theCanvas = document.getElementById("canvas");
        puppy.src = "images/dog_run.png";
        context = theCanvas.getContext("2d");
        dx = 10;
        x = x + dx;
        context.clearRect(0, 0, 900, 540);
        context.fillStyle = "white";
        context.fillRect(5, 60, 530, 30);
        context.fillStyle = "black";
        context.font = "bold 18pt sans-serif";
        message = "Hi! It's me, your dog, " + dogname + ". Feed me!"
        context.fillText(message, 15, 80);
        var sourceX = Math.floor(animationFrames[frameIndex] % 6) * 317;
        var sourceY = Math.floor(animationFrames[frameIndex] / 6) * 317;
        context.drawImage(puppy, sourceX, sourceY, 317, 300, x, y, 317, 300);
        frameIndex++;
        if (frameIndex == animationFrames.length) {
            frameIndex = 0;
        }
    }
    function playGame3(){
        $('#mathform').hide();
        $('#canvas').show();
        $("#canvas2").show();
        var startTime = new Date().getTime();
        x=600 ;
        var interval = setInterval(function(){
            if(new Date().getTime() - startTime > 9000){
                document.getElementById("audio1").src = "";
                document.getElementById("audio2").src = "";
                clearInterval(interval);
                return getProb();
            }
            drawScreen3();
            three() ;
        }, 100);
        document.getElementById("audio1").src = "sounds/dogbark.ogg";
        document.getElementById("audio2").src = "sounds/dogbark.mp3";
    }
    function three(){
        canvas2 = document.getElementById("canvas2");
        context2 = canvas2.getContext("2d");
        context2.clearRect(0, 0, 900, 540);
        context2.fillStyle="white";
        context2.fillRect(5,60,530,30) ;
        context2.fillStyle="black";
        context2.font = "bold 18pt sans-serif" ;
        context2.fillText("Thanks for the bone.",65,80) ;



        if (x >= 100) {
            bone.src = "images/bone.png";
            context2.drawImage(bone, 0, 380);
        }
        else if (x < 100) { context2.clearRect(0, 0, 900, 540);
            bone.src = "";}




    }

    function drawScreen3() {
        theCanvas = document.getElementById("canvas");
        puppy.src = "images/dog_run_left.png";

        // Draws dog ;
        context = theCanvas.getContext("2d");
        dx = 10;
        x = x - dx;
        context.clearRect(0, 0, 900, 540);
        var sourceX = Math.floor(animationFrames[frameIndex] % 6) * 317;
        var sourceY = Math.floor(animationFrames[frameIndex] / 6) * 317;
        context.drawImage(puppy, sourceX, sourceY, 317, 300, x, y, 317, 300);
        frameIndex++;
        if (frameIndex == animationFrames.length) {
            frameIndex = 0;
        }

    }

</script>

</body>
</html>


                                      

Leave a comment

Your email address will not be published. Required fields are marked *

2 thoughts on “Making a Mini-Game Step 2: Setting it up