Snake game |
In my memory, when I was young, I often used my grandparents’ mobile phones to play snake, sokoban and other games secretly when my parents were not at home. This is a game in my childhood memory. Now I haven't played this game in ages, but! ! ! Immediately you can have a unique snake that belongs to you. Come and design this simple snake game with bloggers.
prerequisite preparation |
Game area : a big box. The width and height of bigBox are 640px (you can set it according to your own ideas).
Food : attributes include width: 20px, height: 20px
snake head : attributes: width: 20px, height: 20px, direction (the direction of the snake head) : right (initial direction)
snake body : property: width: 20px, height: 20px
start button : property: width: 200px, height: 150px
stop button : property: width: 70px, height: 70px (need to be hidden at the beginning)
style As shown below:
![](https://img-blog.csdnimg.cn/5efe215a4cf2485d99e3009b75bcc879.png)
![](https://img-blog.csdnimg.cn/3228cba2754c482080380f3c3d123fff.png)
![](https://img-blog.csdnimg.cn/ed8063778f6c4da9aeb9d21747ca9400.png)
needs to be fulfilled |
1. Start game function
When the user enters the main interface of the game, the "**start" button can be found at a conspicuous position at the bottom of the interface. After clicking it, the user can start a new game.
2. Motor function
- Default movement function
When the user clicks the "Start Game" button, the direction of the snake moves from left to right by default . - Keyboard control direction movement function (emphasis) The user can control the moving direction of the snake
by using the up, down, left, and right arrow keys on the keyboard , and the snake will move forward in a straight line in the controlled direction.
3. Eat food function
When food appears anywhere on the interface, the user uses the direction keys to control the snake to move around the food. When the snake's head touches the food, it means that the greedy snake has eaten the food. The next food will appear on the interface, and the user controls the snake again. Eat this food.
When the snake eats food, it will add a node
Death Judgment Function
When the snake head hits the wall in the forward direction or the snake head eats the snake body , a death judgment is given, and a pop-up box gives the user the game score .
Pause/resume game function
When the user uses the software and needs to suspend the game process due to personal reasons, the user can click the game interface to "pause" the game in time. At this time, a "game pause" button will appear. When the "pause" button is clicked again, the previous game will continue.
code part |
html part
<!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>
<<link rel="stylesheet" href="css/index.css">
<script src="js/snake.js"></script>
</head>
<body>
<div class="bigBox">
<div class="start">
<img src="images/btn1.gif" alt="">
</div>
<div class="stop">
<img src="images/btn4.png" alt="">
</div>
<div class="con">
</div>
</div>
</body>
</html>
css part
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.bigBox {
position: relative;
width: 640px;
height: 640px;
margin: 50px auto;
background-color: #fce4ec;
border: 20px solid #f8bbd0;
box-sizing: border-box;
}
.start {
width: 200px;
height: 150px;
}
.start,
.stop {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.stop {
display: none;
width: 70px;
height: 70px;
}
img {
width: 100%;
height: 100%;
}
js part
window.addEventListener('load', function () {
var bigBox = this.document.querySelector('.bigBox');
var start = this.document.querySelector('.start');
var stop = this.document.querySelector('.stop');
var con = this.document.querySelector('.con');
function Snake() {
//设置蛇的宽、高、方向
this.width = 20;
this.height = 20;
this.direction = 'right';
//设置初始状态 一个头加两个身体
this.body = [
{
x: 2, y: 0 }, //蛇头
{
x: 1, y: 0 }, //蛇身
{
x: 0, y: 0 } //蛇身
]
//将贪吃蛇显示在游戏区域内
this.display = function () {
for (var i = 0; i < this.body.length; i++) {
if (this.body[i].x != null) {
var s = document.createElement('div');
this.body[i].flag = s;
s.style.height = this.height + 'px';
s.style.width = this.width + 'px';
s.style.borderRadius = '10px';
//通过蛇头的方向,对舌头进行旋转,确保蛇头的方向和行走的方向一致
if (i == 0) {
if (this.direction == 'up') {
s.style.transform = 'rotate(-90deg)';
}
if (this.direction == 'down') {
s.style.transform = 'rotate(90deg)';
}
if (this.direction == 'left') {
s.style.transform = 'rotate(-180deg)';
}
if (this.direction == 'right') {
s.style.transform = 'rotate(0deg)';
}
s.style.backgroundImage = 'url(./images/snake.png)';
s.style.backgroundSize = '25px 20px ';
s.style.backgroundPosition = 'center center';
} else {
s.style.backgroundColor = '#9ccc65';
}
s.style.position = 'absolute';
s.style.left = this.body[i].x * this.width + 'px';
s.style.top = this.body[i].y * this.height + 'px';
con.appendChild(s);
}
}
}
//蛇移动,后一个元素到前一个元素的位置
this.run = function () {
//蛇头另外根据方向处理,所以 i 不等于0
for (var i = this.body.length - 1; i > 0; i--) {
this.body[i].x = this.body[i - 1].x;
this.body[i].y = this.body[i - 1].y;
}
//根据方向处理蛇头的转向
switch (this.direction) {
case 'left': this.body[0].x -= 1;
break;
case 'right': this.body[0].x += 1;
break;
case 'up': this.body[0].y -= 1;
break;
case 'down': this.body[0].y += 1;
break;
}
//判断是否出界
if (this.body[0].x < 0 || this.body[0].x > 29 || this.body[0].y < 0 || this.body[0].y > 29) {
clearInterval(timer);//清除定时器
alert('你的得分是:' + score);
//删除旧的贪吃蛇
for (var i = 0; i < this.body.length; i++) {
if (this.body[i].flag != null) {
con.removeChild(this.body[i].flag);
}
}
//初始化
this.body = [
{
x: 2, y: 0 }, //蛇头,第一个点
{
x: 1, y: 0 }, //蛇身
{
x: 0, y: 0 } //蛇身
];
this.direction = 'right';
score = 0;
start.style.display = 'block'; //结束显示开始按键
con.removeChild(food.flag);
return false;
}
//蛇头吃到食物 xy的坐标相等
if (this.body[0].x == food.x && this.body[0].y == food.y) {
//蛇加一节 因为根据最后节点定,下面display时会更新
this.body.push({
x: null, y: null, flag: null });
score++;
//清除食物再重新生成食物
con.removeChild(food.flag);
food.display();
}
//吃到自己死亡,从第五个开始判断
for (var i = 4; i < this.body.length; i++) {
if (this.body[0].x == this.body[i].x && this.body[0].y == this.body[i].y) {
clearInterval(timer);
alert('你的得分是:' + score);
//删除旧的贪吃蛇
for (var i = 0; i < this.body.length; i++) {
if (this.body[i].flag != null) {
con.removeChild(this.body[i].flag);
}
}
//初始化
this.body = [
{
x: 2, y: 0 }, //蛇头,第一个点
{
x: 1, y: 0 }, //蛇身
{
x: 0, y: 0 } //蛇身
];
this.direction = 'right';
score = 0;
btn.style.display = 'block'; //结束显示开始按键
con.removeChild(food.flag);
// this.display();
return false;//结束
}
}
//先删除旧的蛇再显示新蛇
for (var i = 0; i < this.body.length; i++) {
if (this.body[i].flag != null) {
//当吃到食物时, flag等于 null,且不能删除
con.removeChild(this.body[i].flag);
}
}
this.display();
}
}
//构造食物 并设置食物出现的位置
function Food() {
this.width = 20;
this.height = 20;
this.name = 'zhangsan';
this.display = function () {
var f = document.createElement('div');
this.flag = f;
f.style.width = this.width + 'px';
f.style.height = this.height + 'px';
f.style.backgroundImage = 'url(./images/food2.png)';
f.style.backgroundSize = '100% 100%';
f.style.position = 'absolute';
this.x = Math.floor(Math.random() * 30);
this.y = Math.floor(Math.random() * 30);
f.style.left = this.x * this.width + 'px';
f.style.top = this.y * this.height + 'px';
console.log(this.x);
console.log(this.y);
con.appendChild(f);
}
}
//调用函数,游戏开始
var timer = null;
var flag = false;
var score = 0;
var snake = new Snake();
var food = new Food();
var flag1 = false;
start.addEventListener('click', function (e) {
e.stopPropagation();
start.style.display = 'none';
snake.display();
food.display();
timer = setInterval(function () {
snake.run();
}, 200)
//键盘按键事件
document.addEventListener('keydown', function (e) {
switch (e.keyCode) {
case 38:
if (snake.direction != 'down') {
snake.direction = 'up';
}
break;
case 40:
if (snake.direction != 'up') {
snake.direction = 'down';
}
break;
case 37:
if (snake.direction != 'right') {
snake.direction = 'left';
}
break;
case 39:
if (snake.direction != 'left') {
snake.direction = 'right';
}
break;
}
})
flag1 = true;
flag = true;
})
// 游戏开始后,点击游戏界面可以暂停游戏,再点击继续游戏
bigBox.addEventListener('click', function () {
console.log('+++++' + flag1);
console.log('====' + flag);
if (flag1) {
if (flag) {
clearInterval(timer);
stop.style.display = 'block';
flag = false;
} else {
clearInterval(timer);
timer = setInterval(function () {
snake.run();
}, 200)
stop.style.display = 'none';
flag = true;
}
}
})
})
end |
Go and try it out, I believe this will be a piece of cake for you