javascript - 如何为蛇游戏添加分数?
问题描述
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 分,然后你得到 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>
推荐阅读
- php - 将数据颤动应用程序发布到 postgresql db php
- swift - 有没有办法检查信息面板当前是否在 AVPlayerViewController 中切换?
- certificate - 一个 rfc5280 证书中可以有多个相同的 CHOICE 字段吗?
- python-3.x - 如何删除在 python3 字符串对象中显示为 `\uxxx` 的特殊字符?
- python - 仅在选择列的 Pandas 数据框中添加一行
- c# - Arkit Scene (Xamarin) 中的 PanGesture 和对象翻译问题
- webassembly - 是否可以在 Web 应用程序中将本地 SQLite3 文件与 FileSystemAPI 和 WebAssembly 一起使用?
- .net - .Net 或 VB6 - 拦截假脱机文件并在正确密码后释放
- android - 更改路径以外的画布颜色
- javascript - 在 Phaser 3 中设置快照的位置