为我的游戏设置计时器

时间:2014-10-05 23:21:16

标签: javascript html5 canvas timer html5-canvas

我目前正忙着让计时器在我的迷宫游戏上工作。我基本上希望计时器能够立即开始,一旦你到达终点,计时器就会停止。

这是我目前的代码,我没有包含任何与时间有关的代码,因为我正在撕扯我的头发。任何帮助都会非常有帮助!

var canvas;
var ctx;

var mazeWidth = 510;
var mazeHeight = 510;

var y = 300;
var x = 120;

var maze = new Image();

var collision = 0;

var time = 0

function init() 
{
canvas = document.getElementById('canvasMaze');
ctx = canvas.getContext("2d");
maze.src = "maze.png";
return setInterval(draw, 10);
}

function draw() 
{
clear();
ctx.fillStyle = "Red";
rect(x, y, 15,15);

ctx.fillText(time + " seconds",10,50);

if (x <= 15)
{
    var restart = confirm("It took you " + time + " seconds to complete the maze!");
    if (restart == true)
    {
        x = 250;
        y = 250;
        time = 0;           
    }
}
}

function clear() 
{
ctx.clearRect(0, 0, mazeWidth, mazeHeight);
ctx.drawImage(maze, 1, 1);
}

function rect(x,y,w,h) 
{
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
}

function doKeyDown(e)
{
switch (e.keyCode) 
{
    case 38:
    case 87:
    if (y - 6 > 10)
    {
        y -= 6;
        clear();
        collisionCheck();
        if (collision == 1)
        {
            y += 6;
            collision = 0;
        }
    }
    break;
    case 40: 
    case 83:
    if (y + 6 < 466 )
    {
        y += 6;
        clear();
        collisionCheck();
        if (collision == 1)
        {
            y -= 6;
            collision = 0;
        }
    }
    break;
    case 37:
    case 65:
    if (x - 6 > 0)
    {
        x -= 6;
        clear();
        collisionCheck();
        if (collision == 1)
        {
            x += 6;
            collision = 0;
        }
    }
    break;
    case 39:
    case 68:
    if (x + 6 < 468)
    {
        x += 6;
        clear();
        collisionCheck();
        if (collision == 1)
        {
            x -= 6;
            collision = 0;
        }
    }
    break;
}
}

function collisionCheck()
{
var imageData = ctx.getImageData(x, y, 18, 18);
var pix = imageData.data;
for (var i = 0; n = pix.length, i < n; i += 4) 
{
    if (pix[i] == 0) 
    {
        collision = 1;
    }
}
}

init();
window.addEventListener('keydown',doKeyDown,true);

1 个答案:

答案 0 :(得分:2)

您可能希望在页面加载或初始化时获取当前时间,并可能将其存储在全局变量中。然后,每次调用绘图功能时,您都可以确定从初始时间减去当前时间所经过的时间。

var initialTime = new Date();
var lastUpdate = new Date();
var minTime = 100;
function draw()
{
    ...
    var currentTime = new Date();

    //Don't update if enough time has not passed
    if(currentTime - lastUpdate < minTime)
    {
        //Don't update the timer
    }
    else
    {
        //Update the timer
    }

    var timeTaken = currentTime - initialTime;



    if(x <= 15)
    {
        var restart = confirm("It took you " + timeTaken + " seconds to complete the maze!");
    }
    ...
    lastUpdate = Date.Now();
}

}