将下面的一段代码中的js部分中的操作按键改成w a s d
[td]const canvas = document.getElementById("gameCanvas"); | const context = canvas.getContext("2d"); | const startButton = document.getElementById("startButton"); |
| const gridSize = 20; | let snake = [{x: 200, y: 200}];\\1 | let food = {x: 0, y: 0}; | let dx = gridSize; | let dy = 0; | let score = 0; |
| \\....2 | function drawSnake() { | context.clearRect(0, 0, canvas.width, canvas.height); | snake.forEach(part => { | context.fillStyle = "green"; | context.fillRect(part.x, part.y, gridSize, gridSize); | }); | } |
| function generateFood() { | food.x = Math.floor(Math.random() * canvas.width / gridSize) * gridSize; | food.y = Math.floor(Math.random() * canvas.height / gridSize) * gridSize; | } |
| function drawFood() { | context.fillStyle = "red"; | context.fillRect(food.x, food.y, gridSize, gridSize); | } |
| function moveSnake() { | const head = {x: snake[0].x + dx, y: snake[0].y + dy}; | snake.unshift(head); | if (head.x === food.x && head.y === food.y) { | score++; | generateFood(); | } else { | snake.pop(); | } | } |
| function changeDirection(event) { | const keyPressed = event.keyCode; | if (keyPressed === 37 && dx === 0) { | dx = -gridSize; | dy = 0; | } | if (keyPressed === 38 && dy === 0) { | dx = 0; | dy = -gridSize; | } | if (keyPressed === 39 && dx === 0) { | dx = gridSize; | dy = 0; | } | if (keyPressed === 40 && dy === 0) { | dx = 0; | dy = gridSize; | } | } |
| function gameLoop() { | moveSnake(); | drawSnake(); | drawFood(); | if (snake[0].x < 0 || snake[0].x >= canvas.width || snake[0].y < 0 || snake[0].y >= canvas.height) { | clearInterval(game); | alert("Game Over! Your score is " + score); | } | } |
| startButton.addEventListener("click", () => { | snake = [{x: 200, y: 200}]; | dx = gridSize; | dy = 0; | score = 0; | generateFood(); | game = setInterval(gameLoop, 100); | }); |
| document.addEventListener("keydown", changeDirection);
[/td] |