帆布游戏计时器

时间:2013-04-27 15:38:03

标签: html5 canvas timer clock

我正在制作一个带有围绕画布移动的矩形的HTML5 Canvas游戏。目标是尽可能长时间避开多个球在画布上移动。但是当球击中矩形时,我很难让计时器显示你的时间/分数。 (通过向上,向下,向左和向右键移动矩形)。任何有这方面知识的人都会非常感谢,谢谢。

2 个答案:

答案 0 :(得分:2)

以下是将计时器集成到游戏中的方法:

在开始游戏自动收报机之前设置startingTime:

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

每当调用playGame时绘制经过的时间:

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

最后,在游戏结束时绘制最终得分:

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

另外,我注意到即使在游戏结束后你就离开游戏滚动条。以下是关闭代码的方法:

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

// turn off the ticker
clearInterval(theInterval);

并且......查看新的requestAnimationFrame自动收报机。它比旧的setInterval股票代码更有效,更有资源。以下是requestAnimationFrame的链接:http://paulirish.com/2011/requestanimationframe-for-smart-animating/

这是代码和小提琴: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>

答案 1 :(得分: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