首页 > 解决方案 > 在我的 JS 蛇游戏中,蛇不能在画布的边缘移动

问题描述

嘿伙计们,我正在用 JS 制作蛇游戏。我正在处理的最初问题是试图让游戏clearInterval(game);在蛇头与画布边缘接触后停止运行。一旦我弄清楚它就会产生一个新问题。你不能骑在画布边缘的蛇。这是一个问题,因为食物有时会在边缘生成。任何想法,我都难住了。谢谢:)

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>
		body {
			background-color: #333;
		}

		canvas {
			background-color: #4d4d4d;
			margin: auto;
			display: block;
			position: absolute;
			left: 0;
			right: 0;
			top: 0;
			bottom: 0;
			width: 750px;
			height: 500px;		
		}
	</style>
</head>
<body>
	<canvas id="canvas"></canvas>
	<script src="script.js"></script>
</body>
</html>

标签: javascript

解决方案


推荐阅读