Making a mini-game: Step 3 Getting the problem


We left off last time having created a form, written HTML and CSS, initializing the variables and selecting two random integers within a range we specified.

Our next step is to put those numbers into a problem. That function is shown below.

// CREATING A PROBLEM 
    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;
    }

Here is what this function does. First, it shows the form with the ID mathform. The $ in front is referencing jquery. Remember those libraries we linked in last time? We’re going to make quite a bit of use of them.

Although the math form is shown when the page first loads, throughout the game, it is hidden each time a player answers a problem correctly, then he or she gets to play with the dog for a while. After that, we get a new problem.

So … each time we get a problem, we show the math form and hide the two canvas elements. The canvas elements are two layers of graphics, a grassy background, and whatever goes on top of it, but we’ll get into detail on that later. As you’ve probably guessed, hide() is a second javascript function that hides an element.

background

Next, we set the answer field in the math form to blank – basically, we clear the answer the player had entered for the last question.

Then, we focus on the answer element. In other words, when the form loads, your cursor is going to be placed in the answer field where we want you to type your answer.

Now it’s time to put numbers in the form to create a math problem for the player to answer.

We create a new variable, choose1 and call the randnum function we created in the last post, to give us a a random integer between 2 and 12.

We repeat this step, creating a new variable, choose2, that is a second number between 2 and 12.

document.math.firstnum.value = choose1 ;

Puts our first random number in the first number field in the math form.

Then we do the same thing for our second number field.

Finally, we create a variable named rightanswer which is the product of our two random integers, choose1 and choose2 . Probably the best way to do this would have been in the initialization step but, hey, I didn’t!

Because I did not use the ‘var’ keyword, rightanswer is going to be created as a global variable, available for use outside of this function, which is exactly what I want.

So, now we have our page all set up and our math problem showing numbers and ready to be answered. Once you click on that ANSWER button, a new function will be called that not only checks your answer but lets you play with your dog. That function is the subject of the next post.


++++ 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 ;


    // 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();
        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 *