2

我正在制作一个带有在画布周围移动的矩形的 HTML5 画布游戏。目标是尽可能长时间地躲避在画布上移动的多个球。但是当球击中矩形时,我正在努力放置一个计时器来显示您的时间/得分。(矩形由向上、向下、向左和向右键移动)。任何有这方面知识的人可以帮助我,将不胜感激,谢谢。

4

2 回答 2

3

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

在您开始游戏代码之前设置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>
于 2013-04-27T17:51:19.117 回答
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
于 2013-04-28T13:13:05.093 回答