用JavaScript做一个贪吃蛇小游戏,无需网络 => 打开即可玩。
html代码:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#game{
width: 344px;
background-color: #000;
padding: 20px 8px;
margin: 100px auto;
}
#score{
color: #B7D4A8;
text-align: center;
font-size: 20px;
font-weight: bold;
margin-bottom: 10px;
}
#bg{
width: 304px;
height: 304px;
background-color: #B7D4A8;
padding: 20px;
border-radius: 5%;
}
#main{
width: 300px;
height: 300px;
/* 设置边框*/
border: 2px solid black;
position: relative;
}
#food, .part{
width: 8px;
height: 8px;
background-color: #000;
border: 1px solid #B7D4A8;
position: absolute;
top: 0;
left: 0;
}
#food{
top: 50px;
left: 100px;
}
</style>
<script>
/*
1.页面的布局
- 注意事项:
背景颜色 #B7D4A8
窗口大小(10的倍数)
蛇的大小 10px(可见框)
食物的大小 10px(可见框)
2.随机设置食物的位置
修改食物的top和left值(范围0-290)
并且必须是10的倍数
3.设置蛇的移动
蛇的速度 10px
检查蛇是否吃到食物(蛇头的坐标和食物一致)
记分
4.吃到食物蛇的身体要增加