|
|
孙浩轩同学,我帮你把代码里的方向控制从箭头键改成用WASD键来控制蛇的移动!这样W对应上,A对应左,S对应下,D对应右。
我还帮你改了一些代码里的小错误,让它能正常运行。
你可以看下面修改后的代码,里面的`changeDirection`函数是关键部分,我把按键判断换成了W(87), A(65), S(83), D(68)。
- const canvas = document.getElementById("gameCanvas");
- const context = canvas.getContext("2d");
- const startButton = document.getElementById("startButton");
- const gridSize = 20;
- let snake = []; // 初始化蛇数组
- let food = {x: 0, y: 0};
- let dx = gridSize;
- let dy = 0;
- let score = 0;
- let game;
- 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 === 65 && dx === 0) { // A - 左
- dx = -gridSize;
- dy = 0;
- } else if (keyPressed === 87 && dy === 0) { // W - 上
- dx = 0;
- dy = -gridSize;
- } else if (keyPressed === 68 && dx === 0) { // D - 右
- dx = gridSize;
- dy = 0;
- } else if (keyPressed === 83 && dy === 0) { // S - 下
- dx = 0;
- dy = gridSize;
- }
- }
- function gameLoop() {
- moveSnake();
- drawSnake();
- drawFood();
- const head = snake[0];
- // 判断是否撞墙
- if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height) {
- clearInterval(game);
- alert("Game Over! Your score is " + score);
- }
- }
- startButton.addEventListener("click", () => {
- snake = [
- {x: 100, y: 100},
- {x: 80, y: 100},
- {x: 60, y: 100}
- ]; // 初始蛇身体,三节方块
- dx = gridSize;
- dy = 0;
- score = 0;
- generateFood();
- if(game) clearInterval(game);
- game = setInterval(gameLoop, 100);
- });
- document.addEventListener("keydown", changeDirection);
复制代码
简单解释一下:
- 按65(A)的时候,蛇往左走,只要现在不是左或右方向才能改变。
- 按87(W)的时候,蛇往上走,只要现在不是上下方向才能改变。
- 按68(D)蛇往右走。
- 按83(S)蛇往下走。
- `snake`是一个数组,每个元素表示蛇身上的一小块,用坐标x,y存储。
- 每次移动是让蛇头的位置加上dx和dy,然后把新头放到数组最前面,如果没吃到食物就把尾巴去掉。
你可以直接试试这个修改后的代码,有问题随时问我哦! |
|