2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > HTML+js实现贪吃蛇小游戏(内含完整代码)

HTML+js实现贪吃蛇小游戏(内含完整代码)

时间:2023-02-07 18:36:29

相关推荐

HTML+js实现贪吃蛇小游戏(内含完整代码)

案例分析

看图拆解游戏

首先我们根据图片上的内容把这个游戏拆解成几个部分去单独看:

最外面的大盒子包裹着内容加边框限制蛇的活动范围,整个范围可以看成由许多小方格排列构成的,例如这样子的:;两个按钮,一个控制开始游戏,一个控制游戏中途的暂停继续功能;盒子里面有可以移动的蛇,最开始状态的蛇分为蛇头、蛇身、蛇尾三个部分,蛇只能走直线,通过上⬆下⬇左⬅右⬅的功能键去控制蛇的走向;还有一个随机产生在限制区域内的食物;

这个游戏是当点击开始游戏按钮才显示蛇和食物的,所以最开始我们不在结构里面书写,后面通过js构造函数来生成,但是可以先把样式写了来,由此可知:我们的结构代码可以这么去写:

<body><!-- 最外面盒子 --><div class="content"><!-- 开始按钮 --><div class="btn startBtn"><button></button></div><!-- 暂停按钮 --><div class="btn pauseBtn"><button></button></div><!-- 蛇的活动范围 --><div id="snakeWrap"></div></div></body>

CSS样式代码是这样的:

.content {width: 640px;height: 640px;margin: 35px auto;position: relative;}.btn {width: 100%;height: 100%;position: absolute;left: 0;top: 0;background-color: rgba(0, 0, 0, .3);z-index: 2;}.btn button {background: none;border: none;background-size: 100% 100%;cursor: pointer;outline: none;position: absolute;left: 50%;top: 50%;}.startBtn button {width: 200px;height: 80px;background-image: url(../images/start.gif);margin-left: -100px;margin-top: -40px;}.pauseBtn {display: none;}.pauseBtn button {width: 70px;height: 70px;background-image: url(../images/pause.png);margin-left: -35px;margin-top: -35px;}/* snakeWrap */#snakeWrap {position: relative;width: 600px;height: 600px;background-color: greenyellow;border: 20px solid green;}#snakeWrap div {width: 20px;height: 20px;}.snakeHead {background-image: url(../images/蛇头.png);background-size: cover;}.snakeBody {background-color: #808ca5;border-radius: 50%;}.food {background-image: url(../images/食物.png);background-size: cover;}

蛇的活动范围分析:

下面的代码方块构造函数就是创建一个一个的方格,给每个方格设置了宽高,这个大小是经过计算的可以正好铺满整个蛇的活动范围的地砖,就好比我准备了一整个房间需要的地砖,但是只是准备了并没有拿出来;给原型添加或删除的函数是我具备了铺地装这样子的技术;现在就是人和了,坐等天时地利的时候使用。

js代码:

var sw = 20, //一个方格的宽sh = 20, //一个方格的高tr = 30, //行数td = 30; //列数//方块构造函数function Square(x, y, classname) {//0,0 0,0//20,0 1,0//40,0 2,0this.x = x * sw;this.y = y * sh;this.class = classname;this.viewContent = document.createElement('div'); //方块对应的DOM元素this.viewContent.className = this.class; //方块所指元素this.parent = document.getElementById('snakeWrap'); //方块的父级}//单词prototype指的是原型//给原型添加Square.prototype.create = function() { //创建方块DOM,并添加到页面里this.viewContent.style.position = 'absolute';this.viewContent.style.width = sw + 'px';this.viewContent.style.height = sh + 'px';this.viewContent.style.left = this.x + 'px';this.viewContent.style.top = this.y + 'px';this.parent.appendChild(this.viewContent);};//删除Square.prototype.remove = function() {this.parent.removeChild(this.viewContent);};

创建对象——蛇的分析:

下面的代码看蛇的部分,想要蛇移动,必须先有蛇,开始的时候就说了蛇又分为三个部分蛇头、蛇身和蛇尾,蛇需要移动,蛇移动又分为上下左右四个方向,所以我们需要根据x和y的正负来判断它走的方向,当蛇转向的时候需要蛇头跟着转向,所以要添加一个rotate属性来确定蛇头的方向。

js代码:

//蛇var snake = null;function Snake() {this.head = null; //存一下蛇头信息this.tail = null; //存一下蛇尾信息this.pos = []; //存蛇身上每一个方块的位置this.directionNum = { //存储蛇走的方向,用一个对象来表示left: {x: -1,y: 0,rotate: 180 // 蛇头在不同方向中应该进行旋转},right: {x: 1,y: 0},up: {x: 0,y: -1,rotate: -90},down: {x: 0,y: 1,rotate: 90}}}

初始化对象分析:

蛇有了,我们现在需要把蛇放到最开始的位置,设置坐标,这时候就初始化蛇,这里有个新的知识点就是链表关系,如下图,相当于在已知关系中确定各自的相对位置。

js代码:

//单词init指的是初始化Snake.prototype.init = function() {//创建一个蛇头var snakeHead = new Square(2, 0, 'snakeHead');snakeHead.create();this.head = snakeHead; //存储蛇头信息this.pos.push([2, 0]); //把蛇头的位置存起来//创建蛇身体1var snakeBody1 = new Square(1, 0, 'snakeBody');snakeBody1.create();this.pos.push([1, 0]); //把蛇身1的坐标也存起来//创建蛇身体2var snakeBody2 = new Square(0, 0, 'snakeBody');snakeBody2.create();this.tail = snakeBody2; //把蛇尾信息存起来this.pos.push([0, 0]); //把蛇身2的坐标也存起来//形成链表关系snakeHead.last = null;snakeHead.next = snakeBody1;snakeBody1.last = snakeHead;snakeBody1.next = snakeBody2;snakeBody2.last = snakeBody1;snakeBody2.next = null;//给蛇添加一个属性,用来表示蛇走的方向this.direction = this.directionNum.right; //默认让蛇往右走};

创建食物以及生成新的食物:

首先定义一个食物实例,食物的产生是随机的所以会用到随机数,但是食物产生的位置是有范围的,一是只能在一定区域内,所以需要设置参数使他不能超过边界;二是食物不能出现在蛇的身上,所以就需要判断是否在蛇身上,如果食物的位置与蛇身上的每一个身体部分的坐标不重合,就代表没有在蛇身上。

新的食物的生成条件是当蛇吃了食物(就代表场上没有食物了),才会生成新的食物。食物的消失条件就是去判断蛇头的下一个位置是否和食物的位置重合,如果重合就让食物消失。

js代码:

//创建食物var food = null,//食物的实例function createFood() {//食物小方块的随机坐标var x = null;var y = null;var include = true; //循环跳出的条件,true表示随机生成食物的坐标在蛇身上(需要继续循环);false表示食物坐标不在蛇身上(不循环了)while (include) {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 * sw + 'px';foodDom.style.top = y * sh + 'px';} else {food.create();}}

判断蛇头下一步的位置分析:

蛇头下一步又分成4种情况:一是撞到自己的身体了,游戏结束;二是撞到围墙了,游戏结束;三是碰到食物了,吃掉食物;四是前面方格子什么也没有,继续走;每一种情况都对应一种结果。

js代码:

//这个方法用来获取蛇头下一个位置对应的元素,要根据元素做不同的事情Snake.prototype.getNextPos = function() {var nextPos = [this.head.x / sw + this.direction.x,this.head.y / sh + this.direction.y]//单词forEach代表遍历数组//(1)下个点是自己,代表撞到了自己,游戏结束var selfCollied = false; //是否撞到自己this.pos.forEach(function(value) {if (value[0] == nextPos[0] && value[1] == nextPos[1]) {//如果数组中两个数据都相等,说明下一个点在蛇身体里面能找到自己了selfCollied = true;}});if (selfCollied) {this.strategies.die.call(this);return;}//(2)下个点是围墙,代表撞到了围墙,游戏结束if (nextPos[0] < 0 || nextPos[1] < 0 || nextPos[0] > td - 1 || nextPos[1] > tr - 1) {this.strategies.die.call(this);return;}//(3)下个点是食物,吃if (food && food.pos[0] == nextPos[0] && food.pos[1] == nextPos[1]) {//如果这个条件成立,说明蛇头要走的下一个点是食物this.strategies.eat.call(this);return;}//(4)下个点什么都不是,走this.strategies.move.call(this); //call作用调用,也可以传参};

碰撞后要做的事情分析:

碰撞后要做的三件事:eat(吃)、die(死亡)、move(走)。

(一)eat很简单,调用一下创建食物的函数,食物被吃掉和产生新的食物;

(二)die也很简单,结束游戏,弹出得分对话框;

(三)move可能有点复杂,这里涉及到一个链表重新链接的情况。这个时候又要分为两种情况了:第一种:还没吃到食物的情况下,保持长度不变,每走一步就需要往前面一个方格里增加一个新身体,更新蛇头和蛇尾;第二种:吃到食物的情况,增加蛇身长度,继续更新蛇头位置并且在蛇头后的位置增加一个蛇身,原先的身上位置不改。可能文字看了还不懂,为此博主做了图示让大家能更好的理解。

图示:一句话概括,第一种情况如图第三步:新头是新头,旧头是新身,旧身是新尾;第二种情况如图第二步:新头是新头,旧头是新身,旧身还是旧身,旧尾还是旧尾。

第一步:newBody.next = this.head.next;新身体的next指向现在旧蛇头;

第二步:newBody.next.last = newBody;旧蛇头的上一个就指向现在的新蛇头了;

第三步:newBody.last = null;让新蛇头指向null,this.head.remove();删除旧蛇头,新身体替代旧蛇头的位置,除了吃食物增加身体长度外,其他的移动的情况都是this.tail.remove(); this.tail = this.tail.last;。每次移动都要创建一个新蛇头,更新一下链表关系:newHead.next = newBody;newHead.last = null;newBody.last = newHead; 并且根据移动方向调整一下头的方向。

js代码:

//处理碰撞后要做的事Snake.prototype.strategies = {move: function(format) { //括号内参数用于决定要不要删除最后一个方块(蛇尾),当传来参数就表示要做的事情是吃//创建新身体(在旧蛇头的位置)var newBody = new Square(this.head.x / sw, this.head.y / sh, 'snakeBody');//更新链表关系newBody.next = this.head.next;newBody.next.last = newBody;newBody.last = null;this.head.remove(); //把旧蛇头从原来的位置删除newBody.create();//创建一个新蛇头(蛇头下一个要走到的点nextPos)var newHead = new Square(this.head.x / sw + this.direction.x, this.head.y / sh + this.direction.y, 'snakeHead');//更新链表关系newHead.next = newBody;newHead.last = null;newBody.last = newHead;newHead.viewContent.style.transform = 'rotate(' + this.direction.rotate + 'deg)';newHead.create();//蛇身上的每一个方块的坐标也要更新this.pos.splice(0, 0, [this.head.x / sw + this.direction.x, this.head.y / sh + this.direction.y])this.head = newHead; //还要把this.head的信息更新一下if (!format) { //如果format的值为false,表示需要删除(除了吃之外的操作)this.tail.remove();this.tail = this.tail.last;this.pos.pop();}},eat: function() {this.strategies.move.call(this, true);createFood();game.score++;},die: function() {// console.log('die');game.over();}}snake = new Snake();

游戏逻辑

开启游戏和暂停游戏,通过点击按钮的方法控制,游戏过程中通过功能键的which值去判断玩家按下的是上下左右哪个键来移动蛇。当蛇正在往左走的时候,⬅➡这两个键按下去就没有反应,只能按其他两个个键⬆⬇,同理可得,其他的也是一样。食物的生成需要通过一个定时器去控制它的自动出现。

js代码:

//创建游戏逻辑function Game() {this.timer = null;this.score = 0;}Game.prototype.init = function() {snake.init();createFood();document.onkeydown = function(ev) {if (ev.which == 37 && snake.direction != snake.directionNum.right) { //用户按下左键时,这条蛇不能是正在往右走snake.direction = snake.directionNum.left;} else if (ev.which == 38 && snake.direction != snake.directionNum.down) {snake.direction = snake.directionNum.up;} else if (ev.which == 39 && snake.direction != snake.directionNum.left) {snake.direction = snake.directionNum.right;} else if (ev.which == 40 && snake.direction != snake.directionNum.up) {snake.direction = snake.directionNum.down;}}this.start();}Game.prototype.start = function() { //开始游戏this.timer = setInterval(function() {snake.getNextPos();}, 200);}Game.prototype.pause = function() {clearInterval(this.timer);}Game.prototype.over = function() {clearInterval(this.timer);alert('你的得分为' + this.score);//游戏回到最初始的状态var snakeWrap = document.getElementById('snakeWrap');snakeWrap.innerHTML = '';snake = new Snake();game = new Game();var startBtnWrap = document.querySelector('.startBtn');startBtnWrap.style.display = 'block';}//开启游戏game = new Game();var startBtn = document.querySelector('.startBtn button');startBtn.onclick = function() {startBtn.parentNode.style.display = 'none';game.init();};//暂停游戏var snakeWrap = document.getElementById('snakeWrap');var pauseBtn = document.querySelector('.pauseBtn button');snakeWrap.onclick = function() {game.pause();pauseBtn.parentNode.style.display = 'block';};pauseBtn.onclick = function() {game.start();pauseBtn.parentNode.style.display = 'none';}})

完整js代码

JavaScript:

window.addEventListener('load', function() {var sw = 20, //一个方格的宽sh = 20, //一个方格的高tr = 30, //行数td = 30; //列数var snake = null, //蛇的实例food = null, //食物的实例game = null; //游戏的实例//方块构造函数function Square(x, y, classname) {//0,0 0,0//20,0 1,0//40,0 2,0this.x = x * sw;this.y = y * sh;this.class = classname;this.viewContent = document.createElement('div'); //方块对应的DOM元素this.viewContent.className = this.class; //方块所指元素this.parent = document.getElementById('snakeWrap'); //方块的父级}//原型prototype//给原型添加Square.prototype.create = function() { //创建方块DOM,并添加到页面里this.viewContent.style.position = 'absolute';this.viewContent.style.width = sw + 'px';this.viewContent.style.height = sh + 'px';this.viewContent.style.left = this.x + 'px';this.viewContent.style.top = this.y + 'px';this.parent.appendChild(this.viewContent);};//删除Square.prototype.remove = function() {this.parent.removeChild(this.viewContent);};//蛇function Snake() {this.head = null; //存一下蛇头信息this.tail = null; //存一下蛇尾信息this.pos = []; //存蛇身上每一个方块的位置this.directionNum = { //存储蛇走的方向,用一个对象来表示left: {x: -1,y: 0,rotate: 180 // 蛇头在不同方向中应该进行旋转},right: {x: 1,y: 0},up: {x: 0,y: -1,rotate: -90},down: {x: 0,y: 1,rotate: 90}}}//init初始化Snake.prototype.init = function() {//创建一个蛇头var snakeHead = new Square(2, 0, 'snakeHead');snakeHead.create();this.head = snakeHead; //存储蛇头信息this.pos.push([2, 0]); //把蛇头的位置存起来//创建蛇身体1var snakeBody1 = new Square(1, 0, 'snakeBody');snakeBody1.create();this.pos.push([1, 0]); //把蛇身1的坐标也存起来//创建蛇身体2var snakeBody2 = new Square(0, 0, 'snakeBody');snakeBody2.create();this.tail = snakeBody2; //把蛇尾信息存起来this.pos.push([0, 0]); //把蛇身2的坐标也存起来//形成链表关系//蛇头snakeHead.last = null;snakeHead.next = snakeBody1;//蛇身snakeBody1.last = snakeHead;snakeBody1.next = snakeBody2;//蛇尾snakeBody2.last = snakeBody1;snakeBody2.next = null;//给蛇添加一个属性,用来表示蛇走的方向this.direction = this.directionNum.right; //默认让蛇往右走};//这个方法用来获取蛇头下一个位置对应的元素,要根据元素做不同的事情Snake.prototype.getNextPos = function() {var nextPos = [this.head.x / sw + this.direction.x,this.head.y / sh + this.direction.y]//forEach代词代表遍历数组//下个点是自己,代表撞到了自己,游戏结束var selfCollied = false; //是否撞到自己this.pos.forEach(function(value) {if (value[0] == nextPos[0] && value[1] == nextPos[1]) {//如果数组中两个数据都相等,说明下一个点在蛇身体里面能找到自己了selfCollied = true;}});if (selfCollied) {this.strategies.die.call(this);return;}//下个点是围墙,代表撞到了围墙,游戏结束if (nextPos[0] < 0 || nextPos[1] < 0 || nextPos[0] > td - 1 || nextPos[1] > tr - 1) {this.strategies.die.call(this);return;}//下个点是食物,吃if (food && food.pos[0] == nextPos[0] && food.pos[1] == nextPos[1]) {//如果这个条件成立,说明蛇头要走的下一个点是食物this.strategies.eat.call(this);return;}//下个点什么都不是,走this.strategies.move.call(this); //call作用调用,也可以传参};//处理碰撞后要做的事Snake.prototype.strategies = {move: function(format) { //括号内参数用于决定要不要删除最后一个方块(蛇尾),当传来参数就表示要做的事情是吃//创建新身体(在旧蛇头的位置)var newBody = new Square(this.head.x / sw, this.head.y / sh, 'snakeBody');//更新链表关系newBody.next = this.head.next;newBody.next.last = newBody;newBody.last = null;this.head.remove(); //把旧蛇头从原来的位置删除newBody.create();//创建一个新蛇头(蛇头下一个要走到的点nextPos)var newHead = new Square(this.head.x / sw + this.direction.x, this.head.y / sh + this.direction.y, 'snakeHead');//更新链表关系newHead.next = newBody;newHead.last = null;newBody.last = newHead;newHead.viewContent.style.transform = 'rotate(' + this.direction.rotate + 'deg)';newHead.create();//蛇身上的每一个方块的坐标也要更新this.pos.splice(0, 0, [this.head.x / sw + this.direction.x, this.head.y / sh + this.direction.y])this.head = newHead; //还要把this.head的信息更新一下if (!format) { //如果format的值为false,表示需要删除(除了吃之外的操作)this.tail.remove();this.tail = this.tail.last;this.pos.pop();}},eat: function() {this.strategies.move.call(this, true);createFood();game.score++;},die: function() {// console.log('die');game.over();}}snake = new Snake();//创建食物function createFood() {//食物小方块的随机坐标var x = null;var y = null;var include = true; //循环跳出的条件,true表示随机生成食物的坐标在蛇身上(需要继续循环);false表示食物坐标不在蛇身上(不循环了)while (include) {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 * sw + 'px';foodDom.style.top = y * sh + 'px';} else {food.create();}}//创建游戏逻辑function Game() {this.timer = null;this.score = 0;}Game.prototype.init = function() {snake.init();createFood();document.onkeydown = function(ev) {if (ev.which == 37 && snake.direction != snake.directionNum.right) { //用户按下左键时,这条蛇不能是正在往右走snake.direction = snake.directionNum.left;} else if (ev.which == 38 && snake.direction != snake.directionNum.down) {snake.direction = snake.directionNum.up;} else if (ev.which == 39 && snake.direction != snake.directionNum.left) {snake.direction = snake.directionNum.right;} else if (ev.which == 40 && snake.direction != snake.directionNum.up) {snake.direction = snake.directionNum.down;}}this.start();}Game.prototype.start = function() { //开始游戏this.timer = setInterval(function() {snake.getNextPos();}, 200);}Game.prototype.pause = function() {clearInterval(this.timer);}Game.prototype.over = function() {clearInterval(this.timer);alert('你的得分为' + this.score);//游戏回到最初始的状态var snakeWrap = document.getElementById('snakeWrap');snakeWrap.innerHTML = '';snake = new Snake();game = new Game();var startBtnWrap = document.querySelector('.startBtn');startBtnWrap.style.display = 'block';}//开启游戏game = new Game();var startBtn = document.querySelector('.startBtn button');startBtn.onclick = function() {startBtn.parentNode.style.display = 'none';game.init();};//暂停游戏var snakeWrap = document.getElementById('snakeWrap');var pauseBtn = document.querySelector('.pauseBtn button');snakeWrap.onclick = function() {game.pause();pauseBtn.parentNode.style.display = 'block';};pauseBtn.onclick = function() {game.start();pauseBtn.parentNode.style.display = 'none';}})

案例素材

喜欢就拿去试试吧,不能嫌弃蛇头丑,找不到素材,没得审美的博主自己用PS软件画的蛇头,以后教你如何画简单的图片,这样就再也不担心找不到素材了,敬请期待吧。

游戏效果展示

动图上传仅限5M以内,咱就不讲究了😥,将就看吧

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。