|
|
我下面这个js文件里面,哪部分是关于检测蛇吃食物的?@AI
// script.js
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
canvas.width = 400;
canvas.height = 400;
const box = 20;
let snake;
let food;
let d;
let score;
let game;
// 初始化游戏
function initGame() {
snake = [
{ x: 9 * box, y: 10 * box }
];
food = {
x: Math.floor(Math.random() * 19 + 1) * box,
y: Math.floor(Math.random() * 19 + 1) * box
};
score = 0;
d = null;
}
// 启动游戏
function startGame() {
document.getElementById("gameOver").style.display = "none";
initGame();
if (game) clearInterval(game);
game = setInterval(draw, 500); // 设置游戏速度为500毫秒
}
// 监听键盘事件
document.addEventListener("keydown", direction);
function direction(event) {
if (event.keyCode == 37 && d != "RIGHT") {
d = "LEFT";
} else if (event.keyCode == 38 && d != "DOWN") {
d = "UP";
} else if (event.keyCode == 39 && d != "LEFT") {
d = "RIGHT";
} else if (event.keyCode == 40 && d != "UP") {
d = "DOWN";
}
}
function collision(newHead, array) {
for (let i = 0; i < array.length; i++) {
if (newHead.x === array[i].x && newHead.y === array[i].y) {
return true;
}
}
return false;
}
// 绘制游戏
function draw() {
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = (i === 0) ? "green" : "white";
ctx.fillRect(snake[i].x, snake[i].y, box, box);
ctx.strokeStyle = "red";
ctx.strokeRect(snake[i].x, snake[i].y, box, box);
}
ctx.fillStyle = "red";
ctx.fillRect(food.x, food.y, box, box);
let snakeX = snake[0].x;
let snakeY = snake[0].y;
if (d === "LEFT") snakeX -= box;
if (d === "UP") snakeY -= box;
if (d === "RIGHT") snakeX += box;
if (d === "DOWN") snakeY += box;
if (snakeX === food.x && snakeY === food.y) {
score += 1; // 每次吃到食物时分数增加1
food = {
x: Math.floor(Math.random() * 19 + 1) * box,
y: Math.floor(Math.random() * 19 + 1) * box
};
} else {
snake.pop();
}
let newHead = { x: snakeX, y: snakeY };
if (snakeX < 0 || snakeY < 0 || snakeX >= canvas.width || snakeY >= canvas.height || collision(newHead, snake)) {
clearInterval(game);
document.getElementById("score").innerText = score;
document.getElementById("gameOver").style.display = "block";
return;
}
snake.unshift(newHead);
ctx.fillStyle = "white";
ctx.font = "45px Changa one";
ctx.fillText(score, 2 * box, 1.6 * box);
}
// 开始游戏
initGame();
startGame(); |
|