使用JavaScript实现贪吃蛇游戏


Posted in Javascript onSeptember 29, 2020

本文实例为大家分享了JavaScript实现贪吃蛇游戏的具体代码,供大家参考,具体内容如下

index.html代码如下

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title>贪吃蛇</title>
 <link rel="stylesheet" href="css/index.css" >
</head>
<body>
<div id="map">

</div>


<script src="js/tool.js"></script>
<script src="js/food.js"></script>
<script src="js/snake.js"></script>
<script src="js/game.js"></script>
<script src="js/main.js"></script>
</body>
</html>

index.css代码如下

#map {
 width: 600px;
 height: 400px;
 background-color: #ccc;
 position: relative;
}

food.js代码如下

//自调函数 开启一个新的作用域,避免命名冲突
(function () {
 //局部作用域

//记录上一次创建的食物,为删除做准备
 var elements=[];
 var position = 'absolute';
//构造函数Food
 function Food(options) {
 options = options || {};
 this.color = options.color || 'green';

 this.width = options.width || 20;
 this.height = options.height || 20;
 //食物的位置
 this.x = options.x || 0;
 this.y = options.y || 0;
 }

//把食物渲染到map上
// prototype,每个函数都具有一个子对象prototype,prototype表示了该函数的原型
// prototype表示一个类属性的集合。通过new来生成一个类的对象时,prototype对象的属性就会变成实例化对象的属性
 Food.prototype.render = function (map) {
 //删除之前创建的食物
 remove();

 //动态创建div,显示页面上的食物
 var div = document.createElement('div');
 map.appendChild(div);

 elements.push(div);
 //随机生成食物
 this.x = Tool.getRandom(0,map.offsetWidth/this.width - 1)*this.width;
 this.y = Tool.getRandom(0,map.offsetHeight/this.height - 1)*this.height;

 //设置div样式
 div.style.position = position; //脱离文档流
 div.style.background = this.color;
 div.style.width = this.width + 'px';
 div.style.height = this.height + 'px';
 div.style.left = this.x + 'px';
 div.style.top = this.y + 'px';
 };

 function remove() {
 for (var i = elements.length-1;i >= 0;i-- ){
 //删除div
 elements[i].parentNode.removeChild(elements[i]);
 //删除数组元素
 elements.splice(i,1); //第一个参数,从哪个元素开始 第二个参数,删除几个元素
 }
 }
 //把Food构造函数 让外部可以访问
 window.Food = Food;
})()
//测试
// var map = document.getElementById('map');
// var food = new Food(); //这里的Food就是window.Food
// food.render(map);

snake.js代码如下

(function () {
 var position = 'absolute';
 //记录之前创建的蛇
 var elements = [];
 function Snake(options) {
 options = options || {};
 //蛇节的大小
 this.width = options.width || 20;
 this.height = options.height || 20;
 //蛇移动的方向
 this.direction = options.direction || 'right';
 //蛇身体(蛇节) 第一个元素是蛇头
 this.body = [
 {x: 5, y: 2, color: 'red'},
 {x: 4, y: 2, color: 'blue'},
 {x: 3, y: 2, color: 'blue'},
 {x: 2, y: 2, color: 'blue'},
 {x: 1, y: 2, color: 'blue'}
 ];
 }
 Snake.prototype.render = function (map) {
 //删除之前创建的蛇
 remove();
 //把每一蛇节渲染到地图上
 for (var i = 0,len = this.body.length; i<len; i++){
 //蛇节
 var object = this.body[i];
 var div = document.createElement('div');
 map.appendChild(div);

 //记录当前蛇
 elements.push(div);
 //设置样式
 div.style.position = position;
 div.style.width = this.width + 'px';
 div.style.height = this.height + 'px';
 div.style.left = object.x * this.width + 'px';
 div.style.top = object.y * this.height + 'px';
 div.style.backgroundColor = object.color;
 }
 }
 //控制蛇移动的方法
 Snake.prototype.move = function (food,map) {
 //控制蛇的身体移动 (当前蛇节 到 上一蛇节的位置)
 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;
 }
 //控制蛇头的移动
 //判断蛇移动的方向
 var head = this.body[0];
 switch (this.direction){
 case 'right':
 head.x += 1;
 break;
 case 'left':
 head.x -=1;
 break;
 case 'top':
 head.y -=1;
 break;
 case 'bottom':
 head.y +=1;
 }


 //2.4判断蛇头是否和食物重合
 var headX = head.x * this.width;
 var headY = head.y * this.height;
 if (headX === food.x && headY === food.y){
 //让蛇增加一节
 //获取蛇的最后一节
 var last = this.body[this.body.length - 1];
 this.body.push({
 x:last.x,
 y:last.y,
 color:last.color
 })
 //随机在地图上重新生成食物
 food.render(map);
 }
 }

 function remove() {
 for (var i = elements.length -1;i>= 0;i--){
 //删除div
 elements[i].parentNode.removeChild(elements[i]);
 //删除数组中的元素
 elements.splice(i,1);
 }
 }
 //暴露构造函数给外部
 window.Snake = Snake;
})()

//测试
// var map =document.getElementById('map');
// var sanke = new Snake();
// sanke.render(map);

game.js代码如下

//使用自调函数,创建一个新的局部作用域,防止命名冲突
(function () {
 function Game(map) {
 this.food = new Food();
 this.snake = new Snake();
 this.map = map;
 that=this;
 }
 Game.prototype.start = function () {
 //1.把蛇和食物对象渲染到地图上
 this.food.render(this.map);
 this.snake.render(this.map);
 //2.开始游戏逻辑
 //2.1 让蛇移动起来
 //2.2当蛇遇到边界游戏结束
 runSnake();
 //2.3通过键盘控制蛇移动的方向
 bindKey();
 //2.4当蛇遇到食物 做相应的处理
 }

 function bindKey() {
 document.onkeydown = function (e) {
 switch (e.keyCode){
 case 37:
 if (that.snake.direction === 'right') return;
 that.snake.direction = 'left';
 break;
 case 38:
 if (that.snake.direction === 'bottom') return;
 that.snake.direction = 'top';
 break;
 case 39:
 if (that.snake.direction === 'left') return;
 that.snake.direction = 'right';
 break;
 case 40:
 if (that.snake.direction === 'top') return;
 that.snake.direction = 'bottom';
 break;
 }
 }
 }

 //
 function runSnake() {
 var timerId = setInterval(function () {
 //让蛇走一格
 //在定时器中的function中this是指向window对象的
 that.snake.move(that.food,that.map);
 that.snake.render(that.map);

 //2.2当蛇遇到边界游戏结束

 var maxX = that.map.offsetWidth / that.snake.width;
 var maxY = that.map.offsetHeight / that.snake.height;
 //获取蛇头的坐标
 var headX = that.snake.body[0].x;
 var headY = that.snake.body[0].y;

 if (headX <0 || headX>=maxX){
 alert('Game Over');
 clearInterval(timerId);
 }
 if (headY <0 || headY >= maxY){
 alert('Game Over');
 clearInterval(timerId);
 }
 for (var i = that.snake.body.length - 1;i > 0;i--){
 if (headX == that.snake.body[i].x && headY == that.snake.body[i].y){
 alert('Game Over');
 clearInterval(timerId);
 break;
 }
 }
 },300)
 }


 //暴露构造函数给外部
 window.Game = Game;
})()

// //测试
// var map =document.getElementById('map');
// var game = new Game(map);
// game.start();

main.js代码如下

(function () {
 var map =document.getElementById('map');
 var game = new Game(map);
 game.start();
})()

Tool.js代码如下

// 工具对象

(function () {
 var Tool = {
 getRandom: function (min, max) {
 min = Math.ceil(min);
 max = Math.floor(max);
 return Math.floor(Math.random() * (max - min + 1)) + min;
 }
 }
 window.Tool = Tool;
})()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
Javascript异步表单提交,图片上传,兼容异步模拟ajax技术
May 10 Javascript
JavaScript去掉空格的方法集合
Dec 28 Javascript
js函数调用常用方法详解
Dec 03 Javascript
详解addEventListener的三个参数之useCapture
Mar 16 Javascript
javascript实现的多个层切换效果通用函数实例
Jul 06 Javascript
基于jQuery日历插件制作日历
Mar 11 Javascript
js实现可输入可选择的select下拉框
Dec 21 Javascript
React 使用recharts实现散点地图的示例代码
Dec 07 Javascript
js实现旋转的星空效果
Nov 01 Javascript
javascript实现移动端上传图片功能
Aug 18 Javascript
vue router-link 默认a标签去除下划线的实现
Nov 06 Javascript
vue如何实现关闭对话框后刷新列表
Apr 08 Vue.js
解决idea开发遇到javascript动态添加html元素时中文乱码的问题
Sep 29 #Javascript
Openlayers3实现车辆轨迹回放功能
Sep 29 #Javascript
vue 验证两次输入的密码是否一致的方法示例
Sep 29 #Javascript
JS中队列和双端队列实现及应用详解
Sep 29 #Javascript
js实现贪吃蛇游戏(简易版)
Sep 29 #Javascript
js实现星星海特效的示例
Sep 28 #Javascript
vue中重定向redirect:‘/index‘,不显示问题、跳转出错的完美解决
Sep 28 #Javascript
You might like
PHP中return 和 exit 、break和contiue 区别与用法
2012/04/09 PHP
php模拟js函数unescape的函数代码
2012/10/20 PHP
Laravel框架数据库CURD操作、连贯操作总结
2014/09/03 PHP
PHP获取指定月份第一天和最后一天的方法
2015/07/18 PHP
CI框架的安全性分析
2016/05/18 PHP
发两个小东西,ASP/PHP 学习工具。 用JavaScript写的
2007/04/12 Javascript
简单选项卡 js和jquery制作方法分享
2014/02/26 Javascript
JS调试必备的5个debug技巧
2014/03/07 Javascript
使用jquery+CSS实现控制打印样式
2014/12/31 Javascript
Jquery全选与反选点击执行一次的解决方案
2015/08/14 Javascript
使用CSS+JavaScript或纯js实现半透明遮罩效果的实例分享
2016/05/09 Javascript
js仿手机页面文件下拉刷新效果
2016/10/14 Javascript
vue组件如何被其他项目引用
2017/04/13 Javascript
详谈javascript精度问题与调整
2017/07/08 Javascript
js图片上传的封装代码
2017/08/01 Javascript
vue实现表格过滤功能
2019/09/27 Javascript
解决vue项目运行提示Warnings while compiling.警告的问题
2020/09/18 Javascript
Vue+Element自定义纵向表格表头教程
2020/10/26 Javascript
javascript实现放大镜功能
2020/12/09 Javascript
[04:45]DOTA2上海特级锦标赛主赛事第四日RECAP
2016/03/06 DOTA
跟老齐学Python之正规地说一句话
2014/09/28 Python
python打开网页和暂停实例
2014/09/30 Python
使用Python操作excel文件的实例代码
2017/10/15 Python
python利用rsa库做公钥解密的方法教程
2017/12/10 Python
详解Python传入参数的几种方法
2019/05/16 Python
python字符串常用方法及文件简单读写的操作方法
2020/03/04 Python
python为什么要安装到c盘
2020/07/20 Python
CSS3制作皮卡丘动画壁纸的示例
2020/11/02 HTML / CSS
PHP使用Redis队列执行定时任务实例讲解
2021/03/24 PHP
学生抄袭作业的检讨书
2014/10/02 职场文书
工资收入证明
2014/10/07 职场文书
2015年度保密工作总结
2015/04/24 职场文书
2015年乡镇残联工作总结
2015/05/13 职场文书
王亚平太空授课观后感
2015/06/12 职场文书
初中生入团申请书范文(五篇)
2019/10/16 职场文书
Redis字典实现、Hash键冲突及渐进式rehash详解
2021/09/04 Redis