簡體   English   中英

不能在JS蛇游戲中將蛇繞在畫布邊框周圍

[英]can't ride snake around canvas border in JS snake game

我花了最后幾分鍾來弄明白一旦蛇碰到帆布牆就會停止游戲的情況。 我最初的問題是,在游戲停止之前,蛇會經過1個單位越過邊界,這是一個問題,因為您看不到蛇撞到了牆。 在if條件下與關系運算符弄亂之后,我能夠在蛇撞到邊界后立即停止游戲。 現在,一旦蛇進入最后一個進入的單元,游戲便停止了,因此蛇無法騎在畫布的邊緣。 我知道我可以在條件內擴展長度和高度,但這只是使我回到第一個問題。 任何幫助將不勝感激:)

 const canvas = document.querySelector('#canvas'); const ctx = canvas.getContext('2d'); //set canvas dimension equal to css dimension canvas.width = 768; canvas.height = 512; //now put those dimensions into variables const cvsW = canvas.width; const cvsH = canvas.height; //create snake unit const unit = 16; //create snake array let snake = [{x: cvsW/2, y: cvsH/2}]; //delcare global variable to hold users direction let direction; //create food object let food = { x : Math.floor(Math.random()*((cvsW/unit)-1)+1)*unit, y : Math.floor(Math.random()*((cvsH/unit)-1)+1)*unit } //read user's direction document.addEventListener('keydown', changeDirection); function changeDirection(e) { //set direction if (e.keyCode == 37 && direction != 'right') direction = 'left'; else if (e.keyCode == 38 && direction != 'down') direction = 'up'; else if (e.keyCode == 39 && direction != 'left') direction = 'right'; else if (e.keyCode == 40 && direction != 'up') direction = 'down'; } function draw() { //refresh canvas ctx.clearRect(0, 0, cvsW, cvsH); //draw snake for(let i = 0; i < snake.length; i++) { ctx.fillStyle = 'limegreen'; ctx.fillRect(snake[i].x, snake[i].y, unit, unit); } //grab head position let headX = snake[0].x; let headY = snake[0].y; //check if snake hit wall if(headX <= 0 || headY <= 0 || headX >= (cvsW-unit) || headY >= (cvsH-unit)) { clearInterval(runGame); } //posistion food on board ctx.fillStyle = 'red'; ctx.fillRect(food.x, food.y, unit, unit); //send the snake in chosen direction if(direction == 'left') headX -= unit; else if(direction == 'up') headY -= unit; else if(direction == 'right') headX += unit; else if(direction == 'down') headY += unit; //create new head let newHead = {x: headX, y: headY} if(headX == food.x && headY == food.y) { //create new food position food = { x : Math.floor(Math.random()*((cvsW/unit)-1)+1)*unit, y : Math.floor(Math.random()*((cvsH/unit)-1)+1)*unit } //add 3 units to the snake snake.unshift(newHead); snake.unshift(newHead); snake.unshift(newHead); } else { //remove tail snake.pop(); } //add head to snake snake.unshift(newHead); } //run game engine let runGame = setInterval(draw, 70); 
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Snake Game</title> <style> #canvas { background-color: #000; } </style> </head> <body> <canvas id="canvas" width="250px" height="250px"></canvas> <script src="script.js"></script> </body> </html> 

問題是,當蛇與屏幕邊緣碰撞時,您要清除整個游戲間隔。 相反,您應該通過在檢測到碰撞時將其當前x位置設置為其過去的x位置來防止播放器越過屏幕。

另外,我知道這晚了大約4年,但總比沒有好!

我希望這有幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM