用JavaScript做一个贪吃蛇游戏,小时候的玩过的小游戏原来是这样做出来的,一起来看看吧!
1.创建HTML和css文件
2.创建js文件实现功能
创建页面
html文件
<body>
<div class="content">
<div class="btn startBtn">
<button></button>
</div>
<div class="btn pauseBtn">
<button></button>
</div>
<div id="snakeWrap"></div>
</div>
<script src="../js/index.js"></script>
</body>
css文件
* {
margin: 0;
padding: 0;
outline: none;
border: none;
}
.content {
position: relative;
width: 640px;
height: 640px;
margin: 50px auto;
}
.btn {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 2;
}
.btn button {
border: none;
background-size: 100% 100%;
cursor: pointer;
outline: none;
background-color: #FCE4EC;
position: absolute;
left: 50%;
top: 50%;
}
.startBtn button {
margin-top: -75px;
margin-left: -100px;
width: 200px;
height: 150px;
background-size: 200px 150px;
background-image: url(../img/an.gif);
}
.pauseBtn {
display: none;
}
.pauseBtn button {
margin-top: -35px;
margin-left: -35px;
width: 70px;
height: 70px;
background-size: 100% 100%;
background-image: url(../img/zt.png);
}
/* 设置蛇的范围和样式 */
#snakeWrap {
position: relative;
width: 600px;
height: 600px;
background: #FCE4EC;
border: 20px solid #F8BBD0;
}
.snakeHead {
background-image: url(../img/st.png);
background-size: cover;
}
.snakeBody {
background-color: #9CCC65;
border-radius: 50%;
}
.food {
background-size: cover;
background-image: url(../img/sw.png);
background-position: 0 -3px;
}
创建js文件
创建方格
// 创建方块
var sw = 20, //宽
sh = 20,