贪吃蛇游戏
游戏规则
- 撞墙、自己,游戏结束
- 吃到食物,分数+1
- 控制方向: ← ↑ ↓ →
- 游戏暂停: 空格、点击暂停按钮
预览
代码实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>贪吃蛇</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<div class="bg">
<div class="bar">
<span class="rulesBtn">规则</span>
<span class="stopBtn">暂停</span>
<span class="startBtn">开始</span>
<div class="score">0</div>
</div>
<div class="game"></div>
<div class="gameRules">
<h3>游戏规则</h3>
<p>
1.撞墙、自己,游戏结束<br>
2.吃到食物,分数+1<br>
3.控制方向: ↑ ↓ ← →<br>
4.游戏暂停: 空格、点击暂停按钮
</p>
<span>×</span>
</div>
<div class="gameStart gameBtn">开始游戏</div>
<div class="gameStop gameBtn">游戏暂停</div>
<div class="gameRestart gameBtn">重新开始</div>
</div>
<script src="index.js"></script>
</body>
</html>
.bg{
width: 500px;
height: 550px;
background:rgba(0,0,0,0.7);
margin: 0 auto;
position: relative;
}
.bar{
width: 500px;
height: 49px;
border-bottom: 1px solid rgba(255,255,255,0.5);
}
.bar span{
display: inline-block;
width: 40px;
height: 40px;
margin-top: 5px;
background:rgba(255,255,255,0.7);
border-radius: 20px;
text-align: center;
line-height: 40px;
cursor: pointer;
box-shadow: 0 3px rgba(220, 220, 220, 0.7);
user-select: none;
}
.bar span:hover{
background: rgba(220, 220, 220, 0.7);
}
.bar span:active{
background-color: rgba(220, 220, 220, 0.7);
transform: translateY(2px);
}
.bar .rulesBtn{
position: absolute;
left: 0;
top: 0;
}
.bar .startBtn{
position: absolute;
left: 50px;
top: 0;
display: none;
}
.bar .stopBtn{
position: absolute;
left: 50px;
top: 0;
display: none;
}
.bar .score{
position: absolute;
left: 170px;
top: 0;
width: 150px;
height: 40px;
margin-top: 5px;
background:rgba(255,255,255,0.7);
border-radius: 20px;
box-shadow: 1px 3px rgba(220, 220, 220, 0.7);
text-align: center;
line-height: 40px;
font-size: 20px;
user-select: none;
}
.game{
width: 500px;
height: 500px;
position: relative;
}
.game div{
width: 20px;
height: 20px;
border-radius: 10px;
}
.snakeHead{
background-color: lightpink;
}
.snakeBody{
background-color: lightblue;
}
.food{
background: url("food.png");
background-size: cover;
}
.gameRules{
width: 250px;
height: 300px;
background:rgba(255,255,255,0.7);
position: absolute;
top: 125px;
left: 125px;
text-align: center;
display: none;
z-index: 2;
user-select: none;
}
.gameRules p{
width: 230px;
height: 200px;
margin: 0 auto;
padding: 10px;
text-align: left;
line-height: 40px;
}
.gameRules span{
position: absolute;
right: 0;
top: 0;
width: 30px;
height: 30px;
font-size: 30px;
line-height: 30px;
cursor: pointer;
}
.gameBtn{
position: absolute;
top: 250px;
left: 200px;
width: 100px;
height: 50px;
background:rgba(255,255,255,0.7);
cursor: pointer;
line-height: 50px;
text-align: center;
border-radius: 15px;
box-shadow: 0 5px rgba(220, 220, 220, 0.7);
user-select: none;
}
.gameBtn:hover{
background-color: rgba(220, 220, 220, 0.7);
}
.gameBtn:active{
background-color: rgba(220, 220, 220, 0.7);
transform: translateY(2px);
}
.gameStop{
display: none;
}
.gameRestart{
display: none;
}
var rulesBtn = document.querySelector('.rulesBtn'); //顶部的规则按钮
var stopBtn = document.querySelector('.stopBtn'); //顶部的暂停按钮
var startBtn = document.querySelector('.startBtn'); //顶部的开始按钮
var gameRules = document.querySelector('.gameRules'); //游戏规则界面
var closeGameRules = document.querySelector('.gameRules span'); //游戏规则界面关闭按钮
var gameStart = document.querySelector('.gameStart'); //开始游戏(在游戏画面中)
var gameStop = document.querySelector('.gameStop'); //游戏暂停(在游戏画面中)
var gameRestart = document.querySelector('.gameRestart'); //重新开始(在游戏画面中)
var score = document.querySelector('.score'); //顶部的游戏分数
var squareWidth = 20, squareHeight = 20; //方块的宽和高
var tr = 25, td = 25; //游戏界面的行和列
var snake, food, game; //实例
//方块
function Square(x, y, classname) {
this.x = x * squareWidth;
this.y = y * squareHeight;
this.class = classname;
this.parent = document.querySelector('.game'); //方块的父级
}
Square.prototype.create = function () { //创建方块并放到游戏界面中
this.newSquare = document.createElement('div');
this.newSquare.style.position = 'absolute';
this.newSquare.style.top = this.y + 'px';
this.newSquare.style.left = this.x + 'px';
this.newSquare.className = this.class;
this.parent.appendChild(this.newSquare);
};
Square.prototype.remove = function () { //从界面中移除指定方块
this.parent.removeChild(this.newSquare);
};
//蛇
function Snake() {
this.head = null; //储存蛇头信息
this.tail = null; //储存蛇尾信息
this.pos = []; //储存蛇(每一个方块)的定位
this.directionNum = { //蛇往指定的方向前进一步
left: {x: -1, y: 0},
up: {x: 0, y: -1},
right: {x: 1, y: 0},
down: {x: 0, y: 1}
};
}
//初始化蛇
Snake.prototype.init = function () {
//创建蛇头,并更新信息
var newHead = new Square(2, 0 ,'snakeHead');
newHead.create();
this.head = newHead; //更新蛇头信息
this.pos.push([2,0]); //添加定位信息
//创建蛇身1,并更新信息
var newBody1 = new Square(1, 0, 'snakeBody');
newBody1.create();
this.pos.push([1,0]); //添加定位信息
//创建蛇身2,并更新信息
var newBody2 = new Square(0, 0, 'snakeBody');
newBody2.create();
this.tail = newBody2; //更新蛇尾信息
this.pos.push([0,0]); //添加定位信息
//创建链表关系 让蛇整体移动
newHead.last = null;
newHead.next = newBody1;
newBody1.last = newHead;
newBody1.next = newBody2;
newBody2.last = newBody1;
newBody2.next = null;
//设置蛇的默认方向为右
this.direction = this.directionNum.right;
};
//获取蛇往前走一步会遇到的方块,根据遇到的不同方块做不同的事情
Snake.prototype.getNextPos = function () {
//获取蛇的下一步
var nextPos = [
this.head.x/squareWidth + this.direction.x,
this.head.y/squareHeight + this.direction.y
];
//下一步是墙
if (nextPos[0]<0 || nextPos[1]<0 || nextPos[0]>td-1 || nextPos[1]>tr-1){
this.stragetic.die.call(this);
return;
}
//下一步是自己
var self = false; // false:下一步不是自己 true:下一步是自己
this.pos.forEach(function (value) { //遍历蛇的定位信息
if (value[0]==nextPos[0] && value[1]==nextPos[1]){ //条件成立说明下一步是自己,改值为true
self = true;
}
});
if (self){ //self=true则执行
this.stragetic.die.call(this);
return;
}
//下一步是食物
if (food && food.pos[0]==nextPos[0] && food.pos[1]==nextPos[1]){
this.stragetic.eat.call(this, true);
return;
}
//下一步什么都没有 以上三种情况后面加上return,若都没有发生(即什么也没遇到),则执行这一步
this.stragetic.move.call(this);
};
//处理蛇碰撞方块后的事情
Snake.prototype.stragetic = {
move: function (food) { //food参数用来决定要不要移除蛇尾
/*蛇移动的方法: (!!!每一步都要更新蛇的head、tail、pos信息,链表信息)
1.创建新蛇身在原来蛇头位置,移除原来蛇头
2.创建新蛇头在新蛇身前一步
3.移除原来蛇尾
*/
//新建一个蛇身(蛇头的定位),更新信息和链表关系,移除蛇头
var newBody = new Square(this.head.x/squareWidth, this.head.y/squareHeight, 'snakeBody');
newBody.last = null;
newBody.next = this.head.next;
newBody.next.last = newBody;
this.head.remove();
newBody.create();
//新建一个蛇头(新蛇身的前一步),更新信息和链表关系
var newHead = new Square(newBody.x/squareWidth + this.direction.x, newBody.y/squareHeight + this.direction.y, 'snakeHead');
newHead.create();
this.head = newHead;
this.pos.splice(0, 0, [newBody.x/squareWidth + this.direction.x, newBody.y/squareHeight + this.direction.y]);
newHead.last = null;
newHead.next = newBody;
newBody.last = newHead;
//移除蛇尾
if (!food){ /* 吃到食物不移除,没吃到移除
若传进了true参数(代表遇到食物)则if(!food)=false,不移除蛇尾;
若没传参数(代表没遇到食物,food=undefined)则if(!food)=false,移除蛇尾*/
this.tail.remove();
this.tail = this.tail.last;
this.pos.pop();
}
},
eat: function () {
this.stragetic.move.call(this, true);//传进true参数代表吃到食物
creatFood(); //创建食物
game.score++; //分数加一
score.innerHTML = game.score; //分数在界面上显示
},
die: function () {
game.over(); //游戏结束
}
}
//食物
function creatFood() {
var x = null;
var y = null;
var include = true; //判断食物在不在蛇身上 true为在,继续循环创建随机数 false为不在,跳出循环
while (include){//食物不能生成在蛇的身上
//创建随机数 0~25
x = Math.round(Math.random() * (td-1));
y = Math.round(Math.random() * (tr-1));
snake.pos.forEach(function (value) { //遍历蛇的定位信息
if (x!=value[0] && y!=value[1]){ //条件成立说明食物不在蛇身上
include = false;
}
});
}
food = new Square(x, y, 'food');
food.pos = [x, y]; //保存食物的定位信息,用来判断蛇有没有吃到食物
var foodDom = document.querySelector('.food'); //找到页面上的食物
//用循环来确保页面中只有一个食物
if (foodDom){//如果界面上有食物,则把新的随机坐标给它
foodDom.style.left = x * squareWidth + 'px';
foodDom.style.top = y * squareHeight + 'px';
}else {//如果没有找到,则创建食物
food.create();
}
}
//游戏
function Game() {
this.score = 0;
this.timer = null;
}
//初始化游戏
Game.prototype.init = function () {
snake.init();
creatFood();
score.innerHTML = 0; //界面上分数清空为0
document.onkeydown = function (ev) {
//方向键上下左右改变蛇的方向
if (ev.keyCode==37 && snake.direction!=snake.directionNum.right){
snake.direction = snake.directionNum.left;
}else if (ev.keyCode==38 && snake.direction!=snake.directionNum.down){
snake.direction = snake.directionNum.up;
}else if (ev.keyCode==39 && snake.direction!=snake.directionNum.left){
snake.direction = snake.directionNum.right;
}else if (ev.keyCode==40 && snake.direction!=snake.directionNum.up){
snake.direction = snake.directionNum.down;
}
//空格暂停
if (ev.keyCode == 32){
console.log('kongge');
if (stopBtn.style.display == 'block'){
game.pause();
stopBtn.style.display = 'none';
startBtn.style.display = 'block';
gameStop.style.display = 'block';
}else if (startBtn.style.display == 'block'){
game.start();
startBtn.style.display = 'none';
stopBtn.style.display = 'block';
gameStop.style.display = 'none';
}
}
}
this.start();
};
//游戏开始:设置定时器
Game.prototype.start = function () {
clearInterval(this.timer);
this.timer = setInterval(function () {
snake.getNextPos();
}, 200);
};
//游戏暂停:关闭定时器
Game.prototype.pause = function () {
clearInterval(this.timer);
};
//游戏结束
Game.prototype.over = function () {
clearInterval(this.timer);
var gameInnerHtml = document.querySelector('.game');
gameInnerHtml.innerHTML = ''; //回到游戏初始状态
snake = new Snake();
game = new Game();
rulesBtn.style.display = 'block';
gameRestart.style.display = 'block';
stopBtn.style.display = 'none';
};
snake = new Snake();
game = new Game();
//查看规则和关闭规则
rulesBtn.onclick = function () {
gameRules.style.display = 'block';
}
closeGameRules.onclick = function () {
gameRules.style.display = 'none';
}
//开始游戏
gameStart.onclick = function () {
rulesBtn.style.display = 'none';
this.style.display = 'none';
stopBtn.style.display = 'block';
game.init();
}
//暂停、继续游戏
stopBtn.onclick = function () {
this.style.display = 'none';
startBtn.style.display = 'block';
gameStop.style.display = 'block';
game.pause();
}
startBtn.onclick = function () {
this.style.display = 'none';
stopBtn.style.display = 'block';
gameStop.style.display = 'none';
game.start();
}
//重新开始
gameRestart.onclick = function () {
this.style.display = 'none';
gameStart.onclick();
}