gpt4 book ai didi

javascript - 为我的游戏设置计时器

转载 作者:行者123 更新时间:2023-12-02 16:55:34 25 4
gpt4 key购买 nike

我目前一直在寻找一个计时器来完成我的迷宫游戏。我基本上希望计时器立即开始,一旦到达终点,计时器就会停止。

这是我当前的代码,我没有包含任何与时间有关的代码,因为我一直在为它烦恼。任何帮助都会非常有帮助!

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

最佳答案

您可能希望在页面加载或初始化时获取当前时间,并可能将其存储在全局变量中。然后每次调用draw函数时,就可以通过初始时间减去当前时间来确定所耗时。

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

}

关于javascript - 为我的游戏设置计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26208250/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com