使用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实现的分页函数
Dec 22 Javascript
用javascript动态调整iframe高度的代码
Apr 10 Javascript
让回调函数 showResponse 也带上参数的代码
Aug 13 Javascript
javascript 拖放效果实现代码
Jan 22 Javascript
JavaScript中的比较操作符&gt;、=、
Dec 31 Javascript
js+html5获取用户地理位置信息并在Google地图上显示的方法
Jun 05 Javascript
jquery通过扩展select控件实现支持enter或focus选择的方法
Nov 19 Javascript
认识Knockout及如何使用Knockout绑定上下文
Dec 25 Javascript
JavaScript中的Reflect对象详解(ES6新特性)
Jul 22 Javascript
浅谈Koa服务限流方法实践
Oct 23 Javascript
Vue 页面状态保持页面间数据传输的一种方法(推荐)
Nov 01 Javascript
js 使用ajax设置和获取自定义header信息的方法小结
Mar 12 Javascript
解决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 基本语法格式
2009/12/15 PHP
smarty内置函数section的用法
2015/01/22 PHP
php实现统计网站在线人数的方法
2015/05/12 PHP
laravel实现按时间日期进行分组统计方法示例
2019/03/23 PHP
发现的以前不知道的函数
2006/09/19 Javascript
jquery操作 iframe的方法
2014/12/03 Javascript
jQuery实现鼠标经过弹出提示信息的地图热点效果
2015/08/07 Javascript
一波JavaScript日期判断脚本分享
2016/03/06 Javascript
JS简单循环遍历json数组的方法
2016/04/22 Javascript
基于JS实现网页中的选项卡(两种方法)
2017/06/16 Javascript
浏览器调试动态js脚本的方法(图解)
2018/01/19 Javascript
浅谈vue项目4rs vue-router上线后history模式遇到的坑
2018/09/27 Javascript
vscode 开发Vue项目的方法步骤
2018/11/25 Javascript
Vue事件修饰符native、self示例详解
2019/07/09 Javascript
vuex存储复杂参数(如对象数组等)刷新数据丢失的解决方法
2019/11/05 Javascript
[02:28]DOTA2亚洲邀请赛 LGD战队巡礼
2015/02/03 DOTA
python通过exifread模块获得图片exif信息的方法
2015/03/16 Python
Python新手入门最容易犯的错误总结
2017/04/24 Python
Python输出带颜色的字符串实例
2017/10/10 Python
TensorFlow高效读取数据的方法示例
2018/02/06 Python
python数据分析数据标准化及离散化详解
2018/02/26 Python
Python实现注册、登录小程序功能
2018/09/21 Python
Python 串口读写的实现方法
2019/06/12 Python
Python如何实现动态数组
2019/11/02 Python
python数据库操作mysql:pymysql、sqlalchemy常见用法详解
2020/03/30 Python
Python tempfile模块生成临时文件和临时目录
2020/09/30 Python
python爬虫scrapy框架之增量式爬虫的示例代码
2021/02/26 Python
设计模式的基本要素是什么
2014/04/21 面试题
大四自我鉴定范文
2013/10/06 职场文书
中学教师管理制度
2014/01/14 职场文书
团队精神口号
2014/06/06 职场文书
整改落实情况汇报材料
2014/10/29 职场文书
领导干部群众路线对照检查材料
2014/11/05 职场文书
2016年中学植树节活动总结
2016/03/16 职场文书
python glom模块的使用简介
2021/04/13 Python
Java 写一个简单的图书管理系统
2022/04/26 Java/Android