我花了最后几分钟弄乱了一旦蛇碰到帆布墙就会停止游戏的情况。我最初的问题是,在游戏停止之前,蛇会经过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>
答案 0 :(得分:0)
这是问题所在,当蛇与屏幕边缘碰撞时,您要清除整个游戏间隔。相反,您应该通过在检测到碰撞时将其当前的x位置设置为其过去的x位置来防止玩家越过屏幕。
此外,我知道这要晚4年了,但总比没有好!
我希望这会有所帮助!