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();
我不知道该写什么代码来计算得分。我尝试了score ++,但是我不知道我是否做得正确,因为我是编程新手。 谢谢
答案 0 :(得分:0)
我设法进行了比赛得分计算,但是例如您获得0分,然后您获得1分,数字0并不能清除并停留在后面。
<!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>