如何在我的 javascript 游戏中添加一个计数器?

How do I add a counter in my javascript game?

我在 Javascript 中得到了这个游戏编码:

window.onload = function() {
    canv = document.getElementById("gc");
    ctx = canv.getContext("2d");
    document.addEventListener("keydown", keyPush);
    setInterval(game, 1000 / 7);
}

px = py = 10;
gs = tc = 27;
ax = ay = 15;
xv = yv = 0;
trail = [];
tail = 2;

function game () {
    px += xv;
    py += yv;
    if (px < 0) {
        px = tc - 1;
    }
    if (px > tc - 1) {
        px = 0;
    }
    if (py < 0) {
        py = tc-1;
    }
    if (py > tc - 1) {
        py = 0;
    }
    ctx.fillStyle = "black";
    ctx.fillRect(0, 0, canv.width, canv.height);
 
    ctx.fillStyle = "lime";
    for(var i = 0; i < trail.length; i++) {
        ctx.fillRect(trail[i].x * gs, trail[i].y * gs, gs - 2, gs - 2);
        if (trail[i].x == px && trail[i].y == py) {
            tail = 2;
        }
    }
    trail.push({ x: px, y: py });
    while(trail.length > tail) {
        trail.shift();
    }
 
    if (ax == px && ay == py) {
        tail++;
        ax = Math.floor(Math.random() * tc);
        ay = Math.floor(Math.random() * tc);
    }
    ctx.fillStyle = "red";
    ctx.fillRect(ax * gs, ay * gs, gs - 2, gs - 2);
}

function keyPush(evt) {
    switch(evt.keyCode) {
        case 37:
            xv = -1; yv = 0;
            break;
        case 38:
            xv = 0; yv = -1;
            break;
        case 39:
            xv = 1; yv = 0;
            break;
        case 40:
            xv = 0; yv = 1;
            break;
    }
}
<canvas id="gc" width="729" height="729"></canvas>

而且我想在页面的任意位置添加一个计数器,以便计算“尾巴”的长度。
我自己尝试了一点,但似乎没有用,我应该怎么做?

还有另一个问题...如何使用网页上的按钮或文本字段更改代码?比如改变:
setInterval(游戏,1000/7);

setInterval(游戏,1000/9);
使用按钮或文本字段,您可以在其中键入数字并将其粘贴到代码中?

要在设置间隔计时器时使用预定义值,您需要做的就是找到获取用户输入的最佳方法,例如使用 input box。然后你可以用 javascript

获取值

例如

[HTML]
<input type="number" value="500" id="num">
[JS]

let num = document.getElementById('num').value;
num = +num; //cast the value to number since its returned as a string.

setInterval(game, num/nth); //nth is any value of your choice, or you can also grab from user input
```

For your first question, getting how long the tail is depends on how you want it.
you can use a variable and always increment it, each time your code condition is met.

为了在canvas中写入trail长度,我在你的代码中添加了

ctx.fillStyle = "blue";
ctx.fillText(trail.length, 100, 100);
ctx.font = "bold 20px sans-serif";
ctx.textBaseline = "bottom";

这样它会不断地在左上角打印轨迹长度。 至于你的第二个问题,我在全局范围内添加了 intervalTime 变量,这样你就可以更改它,然后下一个间隔将在你输入该变量的时间。

var intervalTime = 1000/7;

window.onload=function() {
    canv=document.getElementById("gc");
    ctx=canv.getContext("2d");
    document.addEventListener("keydown",keyPush);
    
    setInterval(game, intervalTime);
}

px=py=10;
gs=tc=27;
ax=ay=15;
xv=yv=0;
trail=[];
tail = 2;

function game() {
    px+=xv;
    py+=yv;
    if(px<0) {
        px= tc-1;
    }
    if(px>tc-1) {
        px= 0;
    }
    if(py<0) {
        py= tc-1;
    }
    if(py>tc-1) {
        py= 0;
    }
    ctx.fillStyle="black";
    ctx.fillRect(0,0,canv.width,canv.height);
    
    ctx.fillStyle = "blue";
    ctx.fillText(trail.length, 100, 100);
    ctx.font = "bold 20px sans-serif";
    ctx.textBaseline = "bottom";
 
    ctx.fillStyle="lime";
    for(var i=0;i<trail.length;i++) {
        ctx.fillRect(trail[i].x*gs,trail[i].y*gs,gs-2,gs-2);
        if(trail[i].x==px && trail[i].y==py) {
            tail = 2;
        }
    }
    trail.push({x:px,y:py});
    while(trail.length>tail) {
    trail.shift();
    }
 
    if(ax==px && ay==py) {
        tail++;
        ax=Math.floor(Math.random()*tc);
        ay=Math.floor(Math.random()*tc);
    }
    ctx.fillStyle="red";
    ctx.fillRect(ax*gs,ay*gs,gs-2,gs-2);
}

function keyPush(evt) {
    switch(evt.keyCode) {
        case 37:
            xv=-1;yv=0;
            break;
        case 38:
            xv=0;yv=-1;
            break;
        case 39:
            xv=1;yv=0;
            break;
        case 40:
            xv=0;yv=1;
            break;
    }
}
<canvas id="gc" width="729" height="729"></canvas>

And i want to add a counter anywhere on the page, so it counts how long the "tail" is. I have tried a little myself but it dosen't seem to work, any ideas how i do?

对于这个问题,你可以在页面中添加一个元素,然后在每次尾部更改长度时更新它在 javascript 中的文本(使用元素的 innerText 属性 ).

示例 html 元素:

<!-- inside the body element -->
<div>
    <span>Tail Count: </span>
    <span id="tail-counter">2</span>
</div>

和 javascript:

while (trail.length > tail) {
    trail.shift();
    document.getElementById("tail-counter").innerText = tail;
}

if (ax == px && ay == py) {
    tail++;
    document.getElementById("tail-counter").innerText = tail;
    ax = Math.floor(Math.random() * tc);
    ay = Math.floor(Math.random() * tc);
}

Also another queston... how do i change the code with a button or text field on a webpage? Like for example changing setInterval(game,1000/7); to setInterval(game,1000/9); with a button or a text field, where you can type the numbers and it gets pasted into the code?

这道题,要根据文本域更改代码,需要先将文本域添加到页面:

<div>
    <span>Set Game Speed: </span>
    <input id="game-speed" type="number" value="7" />
</div>

然后您可以使用javascript获取文本字段的值并在您的代码中使用它

game_speed = Number.parseInt(document.getElementById("game-speed").value);
interval = setInterval(game, 1000 / game_speed);

现在全部在一起(请注意,此代码允许您在玩游戏时更改游戏速度。这是通过清除您已经使用 clearInterval 设置的间隔,然后设置具有新游戏速度的新间隔来完成的)

<canvas id="gc" width="729" height="729"></canvas>

<body style="overflow-x: hidden; overflow-y: hidden;">
    <div>
        <span>Tail Count: </span>
        <span id="tail-counter">2</span>
    </div>
    <div>
        <span>Set Game Speed: </span>
        <input id="game-speed" type="number" value="7" />
    </div>

</body>
<script>
    px = py = 10;
    gs = tc = 27;
    ax = ay = 15;
    xv = yv = 0;
    trail = [];
    tail = 2;
    game_speed = 7;
    interval = {};

    window.onload = function () {
        canv = document.getElementById("gc");
        ctx = canv.getContext("2d");
        document.addEventListener("keydown", keyPush);

        game_speed = Number.parseInt(document.getElementById("game-speed").value);
        interval = setInterval(game, 1000 / game_speed);
    }

    function game() {

        let new_speed = Number.parseInt(document.getElementById("game-speed").value);
        if (new_speed !== game_speed) {
            clearInterval(interval);
            game_speed = new_speed;
            interval = setInterval(game, 1000 / game_speed);
        }

        px += xv;
        py += yv;
        if (px < 0) {
            px = tc - 1;
        }
        if (px > tc - 1) {
            px = 0;
        }
        if (py < 0) {
            py = tc - 1;
        }
        if (py > tc - 1) {
            py = 0;
        }
        ctx.fillStyle = "black";
        ctx.fillRect(0, 0, canv.width, canv.height);

        ctx.fillStyle = "lime";
        for (var i = 0; i < trail.length; i++) {
            ctx.fillRect(trail[i].x * gs, trail[i].y * gs, gs - 2, gs - 2);
            if (trail[i].x == px && trail[i].y == py) {
                tail = 2;
            }
        }
        trail.push({
            x: px,
            y: py
        });
        while (trail.length > tail) {
            trail.shift();
            document.getElementById("tail-counter").innerText = tail;
        }

        if (ax == px && ay == py) {
            tail++;
            document.getElementById("tail-counter").innerText = tail;
            ax = Math.floor(Math.random() * tc);
            ay = Math.floor(Math.random() * tc);
        }
        ctx.fillStyle = "red";
        ctx.fillRect(ax * gs, ay * gs, gs - 2, gs - 2);
    }

    function keyPush(evt) {
        switch (evt.keyCode) {
            case 37:
                xv = -1;
                yv = 0;
                break;
            case 38:
                xv = 0;
                yv = -1;
                break;
            case 39:
                xv = 1;
                yv = 0;
                break;
            case 40:
                xv = 0;
                yv = 1;
                break;
        }
    }
</script>
<html>