前端贪吃蛇小游戏(HTML、CSS、JS)

这是HTML代码,用来描述贪吃蛇小游戏页面的结构和内容

<!DOCTYPE html>
<html>
<head>
	<title>贪吃蛇游戏</title>
	<link rel="stylesheet" type="text/css" href="style-tanchise.css">
</head>
<body>
	<div id="game-board">
		<div id="snake"></div>
		<div id="food"></div>
	</div>
	<script src="script-tanchishe.js"></script>
</body>
</html>	

这是CSS代码,为游戏页面的样式和布局进行描述,这里只做了简单的样式,可以根据自己的需求添加样式

#game-board {
	width: 400px;
	height: 400px;
	border: 1px solid black;
	position: relative;
}

#snake {
	width: 20px;
	height: 20px;
	background-color: green;
	position: absolute;
	left: 0;
	top: 0;
}

#food {
	width: 20px;
	height: 20px;
	background-color: red;
	position: absolute;
	left: 200px;
	top: 200px;
}

这是JS代码,用来设小蛇的动态效果和数据处理等功能,代码上有解析和注释

// 获取游戏区域和蛇、食物元素
const gameBoard = document.getElementById('game-board');
const snakeElement = document.getElementById('snake');
const foodElement = document.getElementById('food');

// 定义蛇的初始位置和移动方向
let snakeX = 0;
let snakeY = 0;
let snakeDirection = 'right';

// 定义食物的初始位置
let foodX = 200;
let foodY = 200;

// 更新蛇的位置
function updateSnake() {
	if (snakeDirection === 'right') {
		snakeX += 20;
	} else if (snakeDirection === 'left') {
		snakeX -= 20;
	} else if (snakeDirection === 'up') {
		snakeY -= 20;
	} else if (snakeDirection === 'down') {
		snakeY += 20;
	}
	snakeElement.style.left = snakeX + 'px';
	snakeElement.style.top = snakeY + 'px';
}

// 更新食物的位置
//随机数 默认1-10 包头不包围 
function updateFood() {
	foodX = Math.floor(Math.random() * 20) * 20;
	foodY = Math.floor(Math.random() * 20) * 20;
	foodElement.style.left = foodX + 'px';
	foodElement.style.top = foodY + 'px';
}

// 检查蛇是否吃到了食物
function checkFood() {
	if (snakeX === foodX && snakeY === foodY) {
		updateFood();
	}
}

// 检查蛇是否撞墙或撞到自己
function checkCollision() {
	if (snakeX < 0 || snakeX >= 400 || snakeY < 0 || snakeY >= 400) {
		clearInterval(gameLoop);
		alert('游戏结束!');
	}
}

// 处理键盘事件,改变蛇的移动方向
document.addEventListener('keydown', event => {
	if (event.key === 'ArrowRight' && snakeDirection !== 'left') {
		snakeDirection = 'right';
	} else if (event.key === 'ArrowLeft' && snakeDirection !== 'right') {
		snakeDirection = 'left';
	} else if (event.key === 'ArrowUp' && snakeDirection !== 'down') {
		snakeDirection = 'up';
	} else if (event.key === 'ArrowDown' && snakeDirection !== 'up') {
		snakeDirection = 'down';
	}
});

// 游戏循环,每隔一定时间更新蛇和食物的位置,并检查是否吃到食物或撞墙
const gameLoop = setInterval(() => {
	updateSnake();
	checkFood();
	checkCollision();
}, 100);

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

耀南.

你的鼓励将是我最最最最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值