文章目录
(1) 游戏场景搭建
给贪吃蛇一个场地布局
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,
body {
background: aliceblue;
}
#scene {
position: relative;
margin: 50px auto;
background-color: rgba(144, 196, 118, 0.362);
width: 1000px;
height: 500px;
border: solid 1px #333;
box-shadow: #000 0 0 3px;
}
</style>
</head>
<body>
<div id="scene"></div>
</body>
</html>
效果如下:
(2) 获取标签、准备数据
① 创建贪吃蛇标签和样式
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,
body {
background: aliceblue;
}
#scene {
position: relative;
margin: 50px auto;
background-color: rgba(144, 196, 118, 0.362);
width: 1000px;
height: 500px;
border: solid 1px #333;
box-shadow: #000 0 0 3px;
}
#head {
width: 50px;
height: 50px;
border-radius: 30px;
/* background: orangered; */
position: absolute;
left: 150px;
top: 0;
}
#pause {
position: absolute;
width: 98px;
height: 62px;
background-color: rgba(86, 167, 167, 0.789);
color: white;
margin-left: 1300px;
margin-top: 34px;
font-size: 22px;
}
#pause:hover {
background-color: rgba(77, 118, 118, 0.6);
}
p{
position: absolute;
left: 0;
top: 0;
width: 50px;
height: 50px;
background: #666;
border-radius: 50%;
background-color: aquamarine;
border: solid 1px white;
}
</style>
</head>
<body>
<div id="scene">
<!-- 蛇头 -->
<div id="head" style="left: 150px; top: 0">
<img src="./img/head.png" alt="" width="50px" height="50px" />
</div>
<!-- 蛇身 -->
<p style="left: 100px; top: 0"></p>
<p style="left: 50px; top: 0"></p>
<p style="left: 0px; top: 0"></p>
</div>
</body>
</html>
② 获取标签,声明需要的变量
这里不做过多解释 代码中注释很详细
window.onload = function () {
// 封装获取DOM对象的函数
function $(selector) {
return document.querySelectorAll(selector);
}
// 闭包+自执行函数,实现贪吃蛇独立开发
!(function () {
// 声明变量,记录贪吃蛇数据
var speedX = 50; // 水平移动速度
var speedY = 0; // 垂直移动速度
var score = 0; // 积分(吃掉一个食物,增加1分)
var pauseX = 0; // 暂停时记录的X速度
var pauseY = 0; // 暂停时记录的Y速度
var pause = false; // 当前程序正在执行
var pauseBtn =