// 畫食物 ctx.fillStyle = "red"; ctx.fillRect(food.x, food.y, box, box); // 更新分數 ctx.fillStyle = "black"; ctx.font = "20px Arial"; ctx.fillText("Score: " + score, box, box); // 移動蛇 let snakeX = snake[0].x; let snakeY = snake[0].y; if (direction == "LEFT") snakeX -= box; if (direction == "UP") snakeY -= box; if (direction == "RIGHT") snakeX += box; if (direction == "DOWN") snakeY += box; // 如果蛇吃到食物 if (snakeX == food.x && snakeY == food.y) { score++; food = { x: Math.floor(Math.random() * 19 + 1) * box, y: Math.floor(Math.random() * 19 + 1) * box }; } else { snake.pop(); } // 創建新的蛇頭 const newHead = { x: snakeX, y: snakeY }; // 遊戲結束條件:撞牆或撞到自己 if ( snakeX < 0 || snakeX >= canvasSize || snakeY < 0 || snakeY >= canvasSize || collision(newHead, snake) ) { clearInterval(game); // 遊戲結束 } snake.unshift(newHead); } // 檢查蛇是否撞到自己 function collision(head, array) { for (let i = 0; i < array.length; i++) { if (head.x == array[i].x && head.y == array[i].y) { return true; } } return false; } // 每100毫秒更新一次遊戲 let game = setInterval(draw, 100);