Canvas Game Timer

前端 未结 2 1454
情歌与酒
情歌与酒 2021-01-22 10:43

I\'m making a HTML5 Canvas Game with a rectangle that moves around the canvas. The objective is to dodge multiple Balls moving across the canvas for as long as possible. But i\'

相关标签:
2条回答
  • 2021-01-22 11:09

    Here’s how to integrate a timer into your game:

    Set the startingTime just before you start the game ticker:

    /* Do the function, call every 20 milliseconds*/
    startTime=new Date();
    

    Draw the elapsed time whenever playGame is called:

    /* MAIN GAME */
    function playGame()
    {
        g.clearRect(0, 0, canvas.width, canvas.height);  //Clear canvas at start.
        player.draw();
         for (var i = 0; i < 8; i++)
        {
            ball[i].move();
            ball[i].draw();
        }
    
        // draw the score
        drawElapsedTime();
    }
    

    And finally, draw the final score when the game is over:

    drawFinalScore();
    alert("GAME OVER");
    

    Also, I noticed you left the game ticker running even after the game ended. Here’s how to turn off the ticker:

    // turn on the ticker and get a reference to the object
    var theInterval=setInterval(playGame, 20);
    
    // turn off the ticker
    clearInterval(theInterval);
    

    And…check out the new requestAnimationFrame ticker. It’s much more efficient and resource friendly than the older setInterval ticker. Here’s a link for requestAnimationFrame: http://paulirish.com/2011/requestanimationframe-for-smart-animating/

    Here is code and a Fiddle: http://jsfiddle.net/m1erickson/8qKht/

    <!DOCTYPE html>
    <html>
    <head>
    
    <style>
    body
    {
        background-color:green;
    }
    #simpleCanvas
    {
        position: absolute;
        top: 20%;
        left: 30%;
        border:2px solid blue;
        width:500px;
        height:500px;
        background-color: yellow;
    }
    </style>
    <script>
    
        /* Ball Array */
        var ball = new Array();
        ball[0] = new Ball(150, 150);   // x location of target, y location of target
        ball[1] = new Ball(200, 350);
        ball[2] = new Ball(400, 350);
        ball[3] = new Ball(320, 250);
        ball[4] = new Ball(440, 190);
        ball[5] = new Ball(100, 350);
        ball[6] = new Ball(80, 120);
        ball[7] = new Ball(130, 240);
    
    
        /* Player */
        var player = new Player();
    
        var score;
    
        /* PLAYER OBJECT */
        function Player()
        {
           /* private member variables */
           var x = 10;
           var y = 10;      
           var playerColour = "red";
           var width = 25;
           var height = 30; 
           var speed = 10;
    
           /* public methods */ 
           this.draw = draw;
           function draw()
           {
             g.fillStyle = playerColour;
             g.fillRect(x, y, width, height);   
             this.isHit();
           }
    
           this.setX = setX;
           function setX(newX)
           {
              x = newX;
           }
    
           this.getX = getX;
           function getX()
           {
              return x;
           }   
    
           this.setY = setY;
           function setY(newY)
           {
              y = newY;
           }
    
           this.getY = getY;
           function getY()
           {
              return y;
           } 
    
           this.getSpeed = getSpeed;
           function getSpeed()
           {
              return speed;
           }
    
           this.getW = getW;
           function getW()
           {
              return width;
           }   
    
           this.getH = getH;
           function getH()
           {
              return height;
           }   
    
           this.isHit = isHit;
           function isHit()
           {
              for (var i = 0; i < ball.length; i++)
              {
                    if (((x + width) >= ball[i].getX()) && ((x + width) <= (ball[i].getX() + (ball[i].getRadius() * 2)))
                    && ((y + height) >= ball[i].getY()) && ((y + height) <= (ball[i].getY() + (ball[i].getRadius() * 2))))
                    {
                        clearInterval(theInterval);
                        drawFinalScore();
                        //alert("GAME OVER");
                        console.log("game over");
                    }
              }
           }
    
        }
    
        /* BALL OBJECT */
        function Ball(newX, newY)
        {
           var x = newX;
           var y = newY;
           var dx = 2;
           var dy = 4;
           var radius = 10;
           var targetColour = "blue";
    
           /* public methods */
           this.draw = draw;
           function draw()
           {      
            g.beginPath();
            g.fillStyle = targetColour;
            g.arc(x, y, radius, 0, Math.PI * 2);
            g.fill();
            g.closePath();
            }
    
    
           this.setX = setX;
           function setX(newX)
           {
              x = newX;
           }
    
           this.getX = getX;
           function getX()
           {
              return x;
           }   
    
           this.setY = setY;
           function setY(newY)
           {
              y = newY;
           }
    
           this.getY = getY;
           function getY()
           {
              return y;
           } 
    
           this.getRadius = getRadius;
           function getRadius()
           {
              return radius;
           }   
    
           this.move = move;
           function move()
           {
              x += dx;
              y += dy;
    
            // Bounce on a left or right edge.
            if (x + dx > canvas.width - radius || x + dx < radius)
            {
                dx = -dx;
            }
            // If ball hits the top, bounce it. 
            else if (y + dy < radius)
            {   
                dy = -dy;
            }
            //If the ball hits the bottom, check see if it hits a paddle.
            else if (y + dy > canvas.height - radius) 
            {
                dy = -dy;
            }
           }
    
        }
    
    
    
    
        /* MAIN GAME */
        function playGame()
        {
            g.clearRect(0, 0, canvas.width, canvas.height);  //Clear canvas at start.
            player.draw();
    
            for (var i = 0; i < 8; i++)
            {
                ball[i].move();
                ball[i].draw();
            }
    
            // draw the score
            drawElapsedTime();
    
        }
        /* SCORE */
        var startTime;
        // ending elapsed time in seconds
        var score;
    
        function drawElapsedTime(){
            var elapsed=parseInt((new Date() - startTime)/1000);
            g.save();
            g.beginPath();
            g.fillStyle="red";
            g.font="14px Verdana"
            // draw the running time at half opacity
            g.globalAlpha=0.50;
            g.fillText(elapsed+" secs",canvas.width-75,25);
            g.restore();
        }
        function drawFinalScore(){
            // set the final score just once
            if(score==null){ score=parseInt((new Date() - startTime)/1000); }
            g.save();
            g.beginPath();
            g.fillStyle="red";
            g.font="30px Verdana"
            g.fillText("Game Over: "+score+" secs",50,35);
            g.restore();
        }
    
    
        function arrowKeyDown(e) 
        {
           var stepSize = 10; //Increase size
    
            if (e.keyCode == 37)  // left
            {
               player.setX(player.getX() - player.getSpeed());
               if (player.getX() < 0)
               {
                player.setX(0);
               }
            }
           else if(e.keyCode == 38) // up
            {
               player.setY(player.getY() - player.getSpeed());
               if (player.getY() < 0)
               {
                player.setY(0);
               }
            }
           else if(e.keyCode == 39) // right
            {
               player.setX(player.getX() + player.getSpeed());  
              if ((player.getX() + player.getW()) > canvas.width)
              { 
                player.setX(canvas.width - player.getW());
              }  
            }
           else if(e.keyCode == 40) // down
            {
               player.setY(player.getY() + player.getSpeed());
              if ((player.getY() + player.getH()) > canvas.height)
              { 
                player.setY(canvas.height - player.getH());
              } 
            }      
        }
    
        document.addEventListener('keydown',arrowKeyDown);  
    
    </script>
    </head>
    <body>
    
        <h1>A  V  O  I  D</h1>
    
        <canvas id="simpleCanvas"></canvas>
    
    <script>
    
        /* Get the canvas id */
        var canvas = document.getElementById("simpleCanvas");
    
        /* Give the canvas a width and height */
        /* The width and height are in canvas logical units */
        canvas.width = 500;
        canvas.height = 500;
    
        /* Assign a graphics context to the canvas, so that we can draw on it */
        var g = canvas.getContext("2d");
    
        /* Do the function, call every 20 milliseconds*/
        startTime=new Date();
        var theInterval=setInterval(playGame, 20);
    
    </script>
    <audio src="intense.mp3" autoplay loop></audio>
    </body>
    </html>
    
    0 讨论(0)
  • <!DOCTYPE html>
    <html>
    <head>
    
    
    
    <h1>
    A  V  O  I  D
    </h1>
    
    
    
    <style>
    body
    {
    
        background-color:green;
    
    }
    #simpleCanvas
    {
        position: absolute;
        top: 20%;
        left: 30%;
        border:2px solid blue;
        width:500px;
        height:500px;
        background-color: yellow;
    }
     }
    
    
    </style>
    <script>
    
    
    
    
    
    
    
    
    /* Ball Array */
    enter code here`var ball = new Array();
    ball[0] = new Ball(150, 150);   // x location of target, y location of target
    ball[1] = new Ball(200, 350);
    ball[2] = new Ball(400, 350);
    ball[3] = new Ball(320, 250);
    ball[4] = new Ball(440, 190);
    ball[5] = new Ball(100, 350);
    ball[6] = new Ball(80, 120);
    ball[7] = new Ball(130, 240);
    
    
    /* Player */
    var player = new Player();
    
    var score;
    
    /* PLAYER OBJECT */
    function Player()
    {
       /* private member variables */
       var x = 10;
       var y = 10;      
       var playerColour = "red";
       var width = 25;
       var height = 30; 
       var speed = 10;
    
       /* public methods */ 
       this.draw = draw;
       function draw()
       {
         g.fillStyle = playerColour;
         g.fillRect(x, y, width, height);   
         this.isHit();
       }
    
       this.setX = setX;
       function setX(newX)
       {
          x = newX;
       }
    
       this.getX = getX;
       function getX()
       {
          return x;
       }   
    
       this.setY = setY;
       function setY(newY)
       {
          y = newY;
       }
    
       this.getY = getY;
       function getY()
       {
          return y;
       } 
    
       this.getSpeed = getSpeed;
       function getSpeed()
       {
          return speed;
       }
    
       this.getW = getW;
       function getW()
       {
          return width;
       }   
    
       this.getH = getH;
       function getH()
       {
          return height;
       }   
    
       this.isHit = isHit;
       function isHit()
       {
          for (var i = 0; i < ball.length; i++)
          {
                if (((x + width) >= ball[i].getX()) && ((x + width) <= (ball[i].getX() + (ball[i].getRadius() * 2)))
                && ((y + height) >= ball[i].getY()) && ((y + height) <= (ball[i].getY() + (ball[i].getRadius() * 2))))
                {
                    alert("GAME OVER");
                }
          }
       }
    
    }
    
    /* BALL OBJECT */
    function Ball(newX, newY)
    {
       var x = newX;
       var y = newY;
       var dx = 2;
       var dy = 4;
       var radius = 10;
       var targetColour = "blue";
    
       /* public methods */
       this.draw = draw;
       function draw()
       {      
        g.beginPath();
        g.fillStyle = targetColour;
        g.arc(x, y, radius, 0, Math.PI * 2);
        g.fill();
        g.closePath();
        }
    
    
       this.setX = setX;
       function setX(newX)
       {
          x = newX;
       }
    
       this.getX = getX;
       function getX()
       {
          return x;
       }   
    
       this.setY = setY;
       function setY(newY)
       {
          y = newY;
       }
    
       this.getY = getY;
       function getY()
       {
          return y;
       } 
    
       this.getRadius = getRadius;
       function getRadius()
       {
          return radius;
       }   
    
       this.move = move;
       function move()
       {
          x += dx;
          y += dy;
    
        // Bounce on a left or right edge.
        if (x + dx > canvas.width - radius || x + dx < radius)
        {
            dx = -dx;
        }
        // If ball hits the top, bounce it. 
        else if (y + dy < radius)
        {   
            dy = -dy;
        }
        //If the ball hits the bottom, check see if it hits a paddle.
        else if (y + dy > canvas.height - radius) 
        {
            dy = -dy;
        }
       }
    
    }
    
    
    
    
    /* MAIN GAME */
    function playGame()
    {
        g.clearRect(0, 0, canvas.width, canvas.height);  //Clear canvas at start.
        player.draw();
    
        for (var i = 0; i < 8; i++)
        {
            ball[i].move();
            ball[i].draw();
        }
    
    
    }
    /* SCORE */
    var isGameOver=false;
    var startTime;
    // ending elapsed time in seconds
    var score;
    
    function drawElapsedTime(){
        var elapsed=parseInt((new Date() - startTime)/1000);
        ctx.save();
        ctx.beginPath();
        ctx.fillStyle="red";
        ctx.font="14px Verdana"
        // draw the running time at half opacity
        ctx.globalAlpha=0.50;
        ctx.fillText(elapsed+" secs",canvas.width-75,25);
        ctx.restore();
    }
    function drawFinalScore(){
        // set the final score just once
        if(score==null){ score=parseInt((new Date() - startTime)/1000); }
        ctx.save();
        ctx.beginPath();
        ctx.fillStyle="red";
        ctx.font="18px Verdana"
        ctx.fillText("Game Over: "+score+" secs",20,25);
        ctx.restore();
    }
    
    
    function arrowKeyDown(e) 
    {
       var stepSize = 10; //Increase size
    
        if (e.keyCode == 37)  // left
        {
           player.setX(player.getX() - player.getSpeed());
           if (player.getX() < 0)
           {
            player.setX(0);
           }
        }
       else if(e.keyCode == 38) // up
        {
           player.setY(player.getY() - player.getSpeed());
           if (player.getY() < 0)
           {
            player.setY(0);
           }
        }
       else if(e.keyCode == 39) // right
        {
           player.setX(player.getX() + player.getSpeed());  
          if ((player.getX() + player.getW()) > canvas.width)
          { 
            player.setX(canvas.width - player.getW());
          }  
        }
       else if(e.keyCode == 40) // down
        {
           player.setY(player.getY() + player.getSpeed());
          if ((player.getY() + player.getH()) > canvas.height)
          { 
            player.setY(canvas.height - player.getH());
          } 
        }      
    }
    
    document.addEventListener('keydown',arrowKeyDown);  
    
    </script>
    </head>
    <body>
    
    
    <canvas id="simpleCanvas">
    Your browser does not support the HTML5 <canvas> tag.
    </canvas>
    
    
    <script>
    /* Get the canvas id */
    var canvas = document.getElementById("simpleCanvas");
    
    /* Give the canvas a width and height */
    /* The width and height are in canvas logical units */
    canvas.width = 500;
    canvas.height = 500;
    
    /* Assign a graphics context to the canvas, so that we can draw on it */
    var g = canvas.getContext("2d");
    
    /* Do the function, call every 20 milliseconds*/
    setInterval(playGame, 20);
    
    </script>
    <audio src="intense.mp3" autoplay loop></audio>
    </body>
    </html>
    
    
    
    /*This is my code and i tryed adding it in and making it function but it would not work ? Dont know what im doing wrong ? Thanks for the reply
    
    0 讨论(0)
提交回复
热议问题