javascript - 无法在我的贪吃蛇游戏中动态显示分数

标签 javascript html css html5-canvas

嘿,伙计们,每当蛇成为食物时,我都试图在页面上显示用户得分。我有 div 类 'score' 这个 div 正在被存储 const score = document.querySelector('.score'); 作为全局。然后在运行游戏的函数中我有 //increase score 点++; score.innerText = points; 位于测试蛇是否吃掉食物的条件内。但是没有任何显示?

//declare global variables
const canvas = document.querySelector('#canvas');
const score = document.querySelector('.score');

//set canvas context
const ctx = canvas.getContext('2d');

//put canvas dimensions into variables
const cvsW = canvas.width;
const cvsH = canvas.height;

//create snake unit
const unit = 16;

//create points variable 
let points = 0;

//create snake and set starting position
let snake = [{
	x : cvsW/2,
	y : cvsH/2
}]

//create food object and set its position somewhere on board
let food = {
	//Math.floor(Math.random()*cvsW + 1)---number from 1 to 784
	//Math.floor(Math.random()*cvsW/unit + 1)---number from 1 to 79
	//Math.floor(Math.random()*cvsW/unit + 1)*unit---number from 1 to 784(but it's a multiple of unit)
	//Math.floor(Math.random()*(cvsW/unit - 1)+1)*unit---same as above but -1 keeps food inside canvas
	x : Math.floor(Math.random()*(cvsW/unit - 1)+1)*unit-unit/2,
	y : Math.floor(Math.random()*(cvsH/unit - 1)+1)*unit-unit/2
}

//create a variable to store the direction of the snake
let direction;

//add event to read users input then change direction
document.addEventListener('keydown', (e) => {
	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() {
	//clear canvas and redraw snake 
	ctx.clearRect(0, 0, cvsW, cvsH);
	for(let i = 0; i < snake.length; i++) {
		ctx.fillStyle = 'limegreen';
		ctx.fillRect(snake[i].x-unit/2, snake[i].y-unit/2, unit, unit);
	}
	//draw food
	ctx.fillStyle = 'red';
	ctx.fillRect(food.x-unit/2, food.y-unit/2, unit, unit);

	//grab heads position
	let headX = snake[0].x;
	let headY = snake[0].y;

	//move snake in chosen direction
	if(direction == 'left') headX -= unit;
	else if(direction == 'right') headX += unit;
	else if(direction == 'up') headY -= unit;
	else if(direction == 'down') headY += unit;

	//create new snake unit
	let newHead = {x : headX, y :headY}

	//check to see if snake has hit a wall or itself
	if(headX < 0 || headX > cvsW || headY < 0 || headY > cvsH || collision(headX, headY)) {
		clearInterval(runGame);
	}

	//check to see if snakes eaten food
	if(headX === food.x && headY === food.y) {
		//increase score
		points++;
		score.innerText = points;
		//get new food unit
		getFood();
		//create 3 new units
		for(let i = 3; i > 0; i--) {
			//add those units -without this code snake will not grow 
			snake.unshift(newHead);
		}
	} else {
		//remove tail -without this code snake will keep growing
		snake.pop();
	}
	//add new head position -without this code snake will not move
	snake.unshift(newHead);
}

let runGame = setInterval(draw, 65);

function collision(x, y) {
	for(let i = 1; i < snake.length; i++) {
		if(x == snake[i].x && y == snake[i].y) return true;
	}
	return false;
}

function getFood() {
	food = {
		x : Math.floor(Math.random()*(cvsW/unit - 1)+1)*unit-unit/2,
		y : Math.floor(Math.random()*(cvsH/unit - 1)+1)*unit-unit/2
	}
	//loop through snake to see if food generates inside snake
	for(let i = 0; i < snake.length; i++) {
		//if so call the function again
		if(food.x == snake[i].x && food.y == snake[i].y) return getFood();
	} 
	//else return new random point
	return food;
}
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Snake</title>
	<link href="https://fonts.googleapis.com/css?family=Nova+Square" rel="stylesheet">
	<style>
		body {
			background-color: #333;
		}

		#canvas {
			background-color: #4d4d4d;
			display: block;
			margin: auto;
			position: absolute;
			left: 0;
			top: 0;
			right: 0;
			bottom: 0;
		}

		.score {
			width: 80px;
			height: 80px;
			margin-left: auto;
			margin-right: auto;
			color: white;
			font-family: 'Nova Square';
			font-size: 4rem;
			display: flex;
			justify-content: center;
			align-items: center;
			margin-top: 50px;
		}
	</style>
</head>
<body>
	<div class="score"></div>
	<canvas id="canvas" width="784" height="528"></canvas>
	<script src="script.js"></script>
</body>
</html>

最佳答案

实际上 div 在那里并且也显示分数。它只是隐藏在 Canvas 后面。 enter image description here

在样式中添加一个 margin-top:-20px 我想它会再次可见。

您还可以更改 Canvas 样式中的 top 属性以将其向下拖动

//declare global variables
const canvas = document.querySelector('#canvas');
const score = document.querySelector('.score');

//set canvas context
const ctx = canvas.getContext('2d');

//put canvas dimensions into variables
const cvsW = canvas.width;
const cvsH = canvas.height;

//create snake unit
const unit = 16;

//create points variable 
let points = 0;

//create snake and set starting position
let snake = [{
	x : cvsW/2,
	y : cvsH/2
}]

//create food object and set its position somewhere on board
let food = {
	//Math.floor(Math.random()*cvsW + 1)---number from 1 to 784
	//Math.floor(Math.random()*cvsW/unit + 1)---number from 1 to 79
	//Math.floor(Math.random()*cvsW/unit + 1)*unit---number from 1 to 784(but it's a multiple of unit)
	//Math.floor(Math.random()*(cvsW/unit - 1)+1)*unit---same as above but -1 keeps food inside canvas
	x : Math.floor(Math.random()*(cvsW/unit - 1)+1)*unit-unit/2,
	y : Math.floor(Math.random()*(cvsH/unit - 1)+1)*unit-unit/2
}

//create a variable to store the direction of the snake
let direction;

//add event to read users input then change direction
document.addEventListener('keydown', (e) => {
	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() {
	//clear canvas and redraw snake 
	ctx.clearRect(0, 0, cvsW, cvsH);
	for(let i = 0; i < snake.length; i++) {
		ctx.fillStyle = 'limegreen';
		ctx.fillRect(snake[i].x-unit/2, snake[i].y-unit/2, unit, unit);
	}
	//draw food
	ctx.fillStyle = 'red';
	ctx.fillRect(food.x-unit/2, food.y-unit/2, unit, unit);

	//grab heads position
	let headX = snake[0].x;
	let headY = snake[0].y;

	//move snake in chosen direction
	if(direction == 'left') headX -= unit;
	else if(direction == 'right') headX += unit;
	else if(direction == 'up') headY -= unit;
	else if(direction == 'down') headY += unit;

	//create new snake unit
	let newHead = {x : headX, y :headY}

	//check to see if snake has hit a wall or itself
	if(headX < 0 || headX > cvsW || headY < 0 || headY > cvsH || collision(headX, headY)) {
		clearInterval(runGame);
	}

	//check to see if snakes eaten food
	if(headX === food.x && headY === food.y) {
		//increase score
		points++;
		score.innerText = points;
		//get new food unit
		getFood();
		//create 3 new units
		for(let i = 3; i > 0; i--) {
			//add those units -without this code snake will not grow 
			snake.unshift(newHead);
		}
	} else {
		//remove tail -without this code snake will keep growing
		snake.pop();
	}
	//add new head position -without this code snake will not move
	snake.unshift(newHead);
}

let runGame = setInterval(draw, 65);

function collision(x, y) {
	for(let i = 1; i < snake.length; i++) {
		if(x == snake[i].x && y == snake[i].y) return true;
	}
	return false;
}

function getFood() {
	food = {
		x : Math.floor(Math.random()*(cvsW/unit - 1)+1)*unit-unit/2,
		y : Math.floor(Math.random()*(cvsH/unit - 1)+1)*unit-unit/2
	}
	//loop through snake to see if food generates inside snake
	for(let i = 0; i < snake.length; i++) {
		//if so call the function again
		if(food.x == snake[i].x && food.y == snake[i].y) return getFood();
	} 
	//else return new random point
	return food;
}
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Snake</title>
	<link href="https://fonts.googleapis.com/css?family=Nova+Square" rel="stylesheet">
	<style>
		body {
			background-color: #333;
		}

		#canvas {
			background-color: #4d4d4d;
			display: block;
			margin: auto;
			position: absolute;
			left: 0;
			top: 40;
			right: 0;
			bottom: 0;
		}

		.score {
			width: 80px;
			height: 80px;
			margin-left: auto;
			margin-right: auto;
			color: white;
			font-family: 'Nova Square';
			font-size: 4rem;
			display: flex;
			justify-content: center;
			align-items: center;
			margin-top: 50px;
		}
	</style>
</head>
<body>
	<div class="score"></div><br><br><br>
<br><br><br>
<br><br><br>
	<canvas id="canvas" width="784" height="528"></canvas>
	<script src="script.js"></script>
</body>
</html>

关于javascript - 无法在我的贪吃蛇游戏中动态显示分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54284577/

相关文章:

javascript - 错误 : [ng:areq] Argument 'GreetingController' is not a function, 未定义

javascript - 如何在 React 中使用每个 map 上的状态?

javascript - 客户端如何使用CORS跨域?

html - IE 没有看到 body 标签。在 chrome 中工作正常

html - 内联样式导致错误

javascript - 如何从django中的日期选择器获取日期

与 Chrome 的内容安全策略一起工作的 Javascript 模板引擎

jquery - AJAX:加载 HTML、CSS 链接不起作用

html - 显示 :inline-block and display:inline Property Clarification Do what to use

html - 如何制作单列或滚动的响应式表格?