Javascript 如何为蛇类游戏添加分数?

Javascript 如何为蛇类游戏添加分数?,javascript,Javascript,我不知道写什么代码谁来计算分数。我试过使用score++,但我不知道我是否做得对,因为我是编程新手。 谢谢你我设法做到了这一点,但例如,你得了0分,然后你得了1分,数字0没有清除并留在后面 var score = 0; var snake = [42, 41]; var dz = 43; var fx = 1; var n; var ctx = document.getElementById("can").getContext("2d"); function draw(t, c) { ct

我不知道写什么代码谁来计算分数。我试过使用score++,但我不知道我是否做得对,因为我是编程新手。
谢谢你

我设法做到了这一点,但例如,你得了0分,然后你得了1分,数字0没有清除并留在后面

var score = 0;
var snake = [42, 41];
var dz = 43;
var fx = 1;
var n;
var ctx = document.getElementById("can").getContext("2d");

function draw(t, c) {
  ctx.fillStyle = c;
  ctx.fillRect(t % 20 * 20 + 1, ~~(t / 20) * 20 + 1, 18 , 18);
}

document.onkeydown = function (e) {
  fx = snake[1] - snake[0] == (n = [-1, -20, 1, 20][(e || event).keyCode - 37] || fx) ? fx :n
};

!function() {
   snake.unshift(n = snake[0] + fx);

   if (snake.indexOf(n, 1) > 0 || n < 0 || n > 399 || fx == 1 && n % 20 == 0 || fx == -1 && n % 20 == 19)
     return alert("GAME OVER!");

   draw(n, 'blue');
   if (n == dz) {
     while(snake.indexOf(dz = ~~(Math.random() * 400)) >= 0);
     draw(dz, 'red');                
   } else 
     draw(snake.pop(), 'black');

   setTimeout(arguments.callee, 150);                        
}();      

function drawScore() {
  ctx.font = "20px Arial";
  ctx.fillStyle = "White";
  ctx.fillText("Score: "+score, 5, 20);
}

drawScore();
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Snake Game</title>

</head>
<body>
    <style>

    </style>

    <canvas id="can" width="400" height="400" style="background: black"></canvas>

    <script>

        var score = -1
        var snake = [42, 41];
        var dz = 43;
        var fx = 1;
        var n;
        var ctx = document.getElementById("can").getContext("2d");





        function draw(t, c){
            ctx.fillStyle = c;
            ctx.fillRect(t % 20 * 20 + 1, ~~(t / 20) * 20 + 1, 18 , 18);
        }

        document.onkeydown = function (e){
            fx = snake[1] - snake[0] == (n = [-1, -20, 1, 20][(e || event).keyCode - 37] || fx) ? fx :n
        };
        !function() {
            snake.unshift(n = snake[0] + fx);

            if (snake.indexOf(n, 1) > 0 || n < 0 || n > 399 || fx == 1 && n % 20 == 0 || fx == -1 && n % 20 == 19)
                return alert("GAME OVER!");
            draw(n, 'blue');
            if(n == dz) {
                while(snake.indexOf(dz = ~~(Math.random() * 400)) >= 0);
                draw(dz, 'red');
                drawScore(); 
                score++;
            } else 
                draw(snake.pop(), 'black');
            setTimeout(arguments.callee, 150);


        }();      


    ctx.font = "20px Arial";
    ctx.fillStyle = "White";
    ctx.fillText("Score: ", 5, 20);




        function drawScore() {
    ctx.font = "20px Arial";
    ctx.fillStyle = "White";
    ctx.fillText(score,  75, 20);

        }
drawScore();





    </script>
</body>
</html>