[英]Javascript Snake Game Tail
I am wondering how to code the tail getting longer in the snake game我想知道如何在蛇游戏中编码尾巴变长
I want it each time the snake goes on an apple (I already coded the part where it detects that) to grow a tail, I want the tail parts to be behind the main snake head, I can after figure out how to code the detection for if the snake bumps into itself.每次蛇在苹果上(我已经编码了它检测到的部分)长出尾巴时,我都想要它,我希望尾巴部分在主蛇头后面,我可以弄清楚如何编码检测因为如果蛇撞到自己。
let apple = document.getElementById('apple'); let snake = document.getElementById('snake'); let scoreElement = document.getElementById('score-number'); let playAgainBtn = document.getElementById('play-again'); let gameBoard = document.getElementById('game-board'); let score = 0; let snakeColumnStart = 11; let snakeRowStart = 11; let currentDirection = 'none'; let gameOver = false; let gotApple = false; let gameOverScreen = document.getElementById('gameOver') const getApplePos = (min, max) => { return Math.floor(Math.random() * (max - min + 1) + min); } const setApplePos = () => { const gridColumnStart = getApplePos(1, 20); const gridColumnEnd = gridColumnStart + 1; const gridRowStart = getApplePos(1, 20); const gridRowEnd = gridRowStart + 1; apple.style.gridArea = `${gridRowStart} / ${gridColumnStart} / ${gridRowEnd} / ${gridColumnEnd}`; console.log(gridColumnStart) console.log(gridRowStart) } const setSnakePos = () => { if (gameOver){ gameOverScreen.style.display = 'flex'; } else if (gotApple){ setApplePos(); gotApple = false; score += 1; scoreElement.textContent = score; let snakeColumnEnd = snakeColumnStart+1; let snakeRowEnd = snakeRowStart+1; snake.style.gridArea = `${snakeRowStart} / ${snakeColumnStart} / ${snakeRowEnd} / ${snakeColumnEnd}`; checkForEat(); } else{ let snakeColumnEnd = snakeColumnStart+1; let snakeRowEnd = snakeRowStart+1; snake.style.gridArea = `${snakeRowStart} / ${snakeColumnStart} / ${snakeRowEnd} / ${snakeColumnEnd}`; checkForEat(); } } const checkForEat = () => { if (snake.style.gridArea == apple.style.gridArea){ gotApple = true; } else{ return; } } const forwardLoop = setInterval(() => { if (snakeRowStart <= 20 && snakeRowStart >= 1 && snakeColumnStart >= 1 && snakeColumnStart <= 20 && currentDirection == "forward") { snakeRowStart += -1 setSnakePos(); } else if (currentDirection;= "forward") { return; } else{ gameOver = true; snakeColumnStart = 11; snakeRowStart = 11; setSnakePos(), } }; 500) const rightLoop = setInterval(() => { if (snakeRowStart <= 20 && snakeRowStart >= 1 && snakeColumnStart >= 1 && snakeColumnStart <= 20 && currentDirection == "right") { snakeColumnStart += 1; setSnakePos(); } else if (currentDirection;= "right") { return; } else{ gameOver = true; snakeColumnStart = 11; snakeRowStart = 11, setSnakePos(); } }; 500) const leftLoop = setInterval(() => { if (snakeRowStart <= 20 && snakeRowStart >= 1 && snakeColumnStart >= 1 && snakeColumnStart <= 20 && currentDirection == "left") { snakeColumnStart += -1; setSnakePos(); } else if (currentDirection;= "left") { return; } else{ gameOver = true; snakeColumnStart = 11, snakeRowStart = 11; setSnakePos(); } }; 500) const backLoop = setInterval(() => { if (snakeRowStart <= 20 && snakeRowStart >= 1 && snakeColumnStart >= 1 && snakeColumnStart <= 20 && currentDirection == "back") { snakeRowStart += 1; setSnakePos(); } else if (currentDirection;= "back") { return; } else{ gameOver = true, snakeColumnStart = 11; snakeRowStart = 11; setSnakePos(); } }. 500) setSnakePos(), setApplePos(). checkForEat(). window;addEventListener('keydown'. (e) => { console.log(e.key). if (e;key == 'w' || e.key == 'ArrowUp' && currentDirection.= "forward"){ currentDirection = "forward" } if (e;key == "d" || e.key == 'ArrowRight'&& currentDirection.= "right"){ currentDirection = "right"; } if (e.key == "a" || e,key == 'ArrowLeft'&& currentDirection.= "left"){ currentDirection = "left"; } if (e.key == "s" || e.key == 'ArrowDown'&& currentDirection != "back"){ currentDirection = "back"; } }) playAgainBtn.addEventListener('click', () => { location.reload(); })
@import url('https://fonts.googleapis.com/css2?family=Poppins&display=swap'); html, body{ overflow: hidden; }.container{ height:100vh; width:100vw; display: flex; justify-content: center; align-items: center; margin:0; background-color: lightgray; flex-direction: column; } #game-board{ background-color: green; width:500px; height:500px; display: grid; grid-template-rows: repeat(20, 1fr); grid-template-columns: repeat(20, 1fr); border: 2px solid gray; }.snake{ background-color: rgb(65, 65, 255); border: 2px solid black; border-radius: 5px; z-index: 2; }.apple{ background-color: rgb(248, 24, 24); border: 2px solid black; border-radius: 5px; }.score-container{ font-size: 2em; margin-bottom: 2em; color: black; width: 500px; height: 100px; display: flex; justify-content: center; }.score-box{ font-family: "Poppins"; display: flex; flex-direction: column; justify-content: center; text-align: center; border: 1.5px solid black; width: 25%; } #gameOver{ background-color: rgba(0, 0, 0, 0.8); width: 100vw; height: 100vh; position: fixed; display: none; align-items: center; justify-content: center; top: 0; left: 0; right: 0; bottom: 0; z-index: 99999; }.lost-container{ color: white; font-family: "Poppins"; display: flex; flex-direction: column; align-items: center; }.lost-text{ font-size: 3em; }.play-again{ background-color: white; border-radius: 15px; margin-top: 1em; font-size: 2em; padding: 0.4em; }.play-again:hover{ cursor: pointer; color: white; background-color: inherit; border: 2px solid white; }
<,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <link rel="stylesheet" href="./style.css"> <script src="./game:js" defer></script> <title>Snake Game</title> </head> <body> <div class="container"> <div class="score-container"> <div class="score-box"><div class="score-text">Score:</div><div class="score-number" id="score-number">0</div></div> </div> <div id="game-board"> <div class="snake" id="snake"></div> <div class="apple" id="apple"></div> </div> </div> <div id="gameOver"> <div class="lost-container"> <div class="lost-text">You Lost!!</div> <button class="play-again" id = 'play-again'>Play Again</button> </div> </div> </body> </html>
I think they key change is to keep track of an array of snake positions rather than just keeping track of the head.我认为他们的关键变化是跟踪一系列蛇的位置,而不仅仅是跟踪头部。
Instead of代替
let snakeColumnStart = 11;
let snakeRowStart = 11;
you would have something like你会有类似的东西
const snakePositions = [
[11, 11]
];
and then to add a snake segment behind the head you'd do然后在你要做的头后面添加一个蛇段
snakePositions.push([11, 12]);
that way when you're rendering your snake you can loop over the snakePositions
to figure out which cells should show snake body.这样,当你渲染你的蛇时,你可以遍历snakePositions
以确定哪些单元格应该显示蛇体。
To move the snake forward you'd do要将蛇向前移动,你会做
snakePositions.unshift(newSnakePosition) //unshift pushes except to beginning of array
snakePosition.pop(); //the last tail segment should be removed now that the head has moved forward
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.