js实现贪吃蛇游戏(简易版)


Posted in Javascript onSeptember 29, 2020

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

直接开始

效果图:

js实现贪吃蛇游戏(简易版)

项目结构:图片自己找的

js实现贪吃蛇游戏(简易版)

1.html

<!DOCTYPE html>
<html>
 <head>
 <meta charset="utf-8" />
 <title></title>

 <style type="text/css">
  * {
  padding: 0;
  margin: 0;
  }
 </style>
 </head>
 <body>
 <canvas id='view' width="400" height="400" style="border:1px solid red;"></canvas>
 <button id='start'>开始</button>
 <button id='parse'>暂停</button>
 <button id='restart'>重新开始</button>
 <h4>最高分: <span id='scoreMax' style='color:red;'>0</span></h4>
 <h4>分数: <span id='score' style='color:skyblue;'>0</span></h4>
 <script src="js/config.js" type="text/javascript" charset="utf-8"></script>
 <script src="js/score.js" type="text/javascript" charset="utf-8"></script>
 <script src="js/area.js" type="text/javascript" charset="utf-8"></script>
 <script src="js/food.js" type="text/javascript" charset="utf-8"></script>
 <script src="js/snake.js" type="text/javascript" charset="utf-8"></script>
 <script src="js/move.js" type="text/javascript" charset="utf-8"></script>
 <script src="js/init.js" type="text/javascript" charset="utf-8"></script>
 <script type="text/javascript">
  var start = document.getElementById('start');
  var parse = document.getElementById('parse');
  var restart = document.getElementById('restart');
  start.onclick = function() {
  parse = false;
  }
  parse.onclick = function() {
  parse = true;
  }
  restart.onclick = function() {
  snake && snake.restart();
  parse = false;
  }
 </script>
 </body>
</html>

2.area.js

function render(x, y, color, img) {
 ctx.beginPath();
 ctx.fillStyle = color || 'red';
 if (img) {
 ctx.drawImage(img, x * w, y * h, img.width, img.height);
 } else {
 ctx.fillRect(x * w, y * h, w, h);
 }
 ctx.closePath();
 ctx.fill();
}

function clear(x, y) {
 ctx.clearRect(x * w, y * h, w, h);
}

3.config.js

var exit = [];

var parse = true;

var view = document.getElementById('view');
var ctx = view.getContext('2d');
var width = 400,
 height = 400;
var w = 20,
 h = 20;
var maxX = (width / w) - 1,
 maxY = (height / h) - 1;
var speed = 500;
var scoreMax = 0;

var imgsrcs = [
 './img/snakeheadup.png', //图片自己找
 './img/snakeheaddown.png',
 './img/snakeheadleft.png',
 './img/snakeheadright.png'
];
var imgs = [];
var length = 4;
for (var i = 0, len = imgsrcs.length; i < len; i++) {
 var img = new Image(20,20);
 img.src = imgsrcs[i];
 imgs[i] = img;
}

var food, snake, move, score;

4.food.js

function Food() {
 this.init();
}

Food.prototype = {
 init: function() {
 this.update();
 },
 update: function() {
 var food = this.makeCoordinate();
 this.food = food;
 var foodX = food[0];
 var foodY = food[1];
 this.render(foodX, foodY);
 },
 render: function(x, y) {
 render(x, y, 'blue');
 },
 makeCoordinate: function() {
 var x = this.random(0, maxX);
 var y = this.random(0, maxY);
 for (var i = 0; i < exit.length; i++) {
  if (exit[i].toString() == [x, y].toString()) {
  return this.makeCoordinate();
  }
 }
 return [x, y];
 },
 random: function(min, max) {
 return Math.floor(Math.random() * (max - min + 1)) + min;
 }
}

5.init.js

function init() {
 food = new Food();
 snake = new Snake();
 move = new Move();
 score = new Score();
 var timer = setInterval(function() {
 if (!parse) {
  snake.move();
 }
 }, speed);
}

for (var j = 0; j < imgs.length; j++) {
 imgs[j].onload = function() {
 length--;
 if (length == 0) {
  init();
 }
 }
}

6.move.js

function Move() {

}

Move.prototype = {
 up: function(s) {
 snake.move('up');
 },
 down: function(s) {
 snake.move('down');
 },
 left: function(s) {
 snake.move('left');
 },
 right: function(s) {
 snake.move('right');
 }
}


document.onkeydown = function(e) {
 var key = e.keyCode;
 if(!parse){
 switch (key) {
  case 37:
  case 65:
  move.left(snake);
  break;
  case 38:
  case 87:
  move.up(snake);
  break;
  case 39:
  case 68:
  move.right(snake);
  break;
  case 40:
  case 83:
  move.down(snake);
  break;
  default:
  break;
 }
 }
};

7.score.js

var scoreDom = document.getElementById('score');
var scoreMaxDom = document.getElementById('scoreMax');

function Score() {
 this.score = 0;
}

Score.prototype = {
 scoreAdd: function() {
 this.score += 1;
 scoreDom.innerHTML = this.score;
 },
 scoreClear: function() {
 this.score = 0;
 scoreDom.innerHTML = 0;
 },
 highScore: function() {
 scoreMax = scoreMax > this.score ? scoreMax : this.score;
 scoreMaxDom.innerHTML = scoreMax;
 }
}

8.snake.js

function Snake() {
 this.head = [0, 5, imgs[1]]; // x,y坐标,头
 this.body = []; // 二维数组,身体
 this.snake = []; //完整的蛇
 this.init(6);
 this.direction = 'down'; // 默认向下运动
}

Snake.prototype = {
 init: function(len) {
 len = len ? len > 10 ? 10 : len : 5;
 var head = this.head = [0, len, imgs[1]];
 var body = this.body;
 for (var i = 0; i < len; i++) {
  body.push([0, i]);
 }
 this.getSnake();
 },
 restart: function() {
 ctx.clearRect(0, 0, width, height);
 this.head = [0, 5, imgs[1]]; // x,y坐标,头
 this.body = []; // 二维数组,身体
 this.snake = []; //完整的蛇
 exit = [];
 this.direction = 'down'; // 默认向下运动
 this.init(6);
 food.update();
 score.scoreClear();
 },
 eat: function() {
 var head = [this.head[0], this.head[1]];
 var body = this.body;
 if (food.food.toString() == head.toString()) {
  food.update();
  score.scoreAdd();
  return true;
 }
 return false;
 },
 update: function(direction) {
 var oldDirection = this.direction;
 this.direction = direction || this.direction;
 if ((this.direction == 'down' && oldDirection == 'up') ||
  (this.direction == 'up' && oldDirection == 'down') ||
  (this.direction == 'left' && oldDirection == 'right') ||
  (this.direction == 'right' && oldDirection == 'left')) {
  this.direction = oldDirection;
 }
 if (this.direction == 'left' && oldDirection != 'right') {
  this.head[0] -= 1;
  this.head[2] = imgs[2];
 } else if (this.direction == 'right' && oldDirection != 'left') {
  this.head[0] += 1;
  this.head[2] = imgs[3];
 } else if (this.direction == 'up' && oldDirection != 'down') {
  this.head[1] -= 1;
  this.head[2] = imgs[0];
 } else if (this.direction == 'down' && oldDirection != 'up') {
  this.head[1] += 1;
  this.head[2] = imgs[1];
 }
 this.die();
 },
 gameOver: function() {
 alert('game over!')
 console.log('game over!');
 parse = true;
 score.highScore();
 },
 die: function() {
 var head = this.head;
 var x = head[0],
  y = head[1];
 if (x < 0 || x > maxX || y < 0 || y > maxY) {
  this.gameOver();
 }
 var body = this.body;
 for (var i = 0; i < body.length; i++) {
  if (body[i].toString() == [x, y].toString()) {
  this.gameOver();
  }
 }
 },
 render: function() {
 var snake = this.snake;
 for (var i = 0, len = snake.length; i < len; i++) {
  var item = snake[i];
  render(item[0], item[1], 'green', item[2]);
 }
 },
 move: function(direction) {
 var head = this.head;
 var headCopy = head.slice(); //之前的头
 var body = this.body;
 body.push([headCopy[0], headCopy[1]]);
 this.update(direction);
 var eat = this.eat();
 if (!eat) {
  var del = body.shift();
  clear(del[0], del[1]);
 }
 this.getSnake();
 },
 getSnake: function() {
 var head = this.head;
 var body = this.body;
 var snake = this.snake = [];
 for (var i = 0, l = body.length; i < l; i++) {
  snake.push(body[i]);
 }
 snake.push(head);
 exit = [];
 for (var i = 0; i < snake.length; i++) {
  exit.push(snake[i]);
 }
 this.render();
 }
}

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

Javascript 相关文章推荐
Javascript 读书笔记索引贴
Jan 11 Javascript
javascript 获取页面的高度及滚动条的位置的代码
May 06 Javascript
JS跨域代码片段
Aug 30 Javascript
node在两个div之间移动,用ztree实现
Mar 06 Javascript
ie9 提示'console' 未定义问题的解决方法
Mar 20 Javascript
jQuery使用append在html元素后同时添加多项内容的方法
Mar 26 Javascript
Angularjs中UI Router的使用方法
May 14 Javascript
jQuery实现简单的网页换肤效果示例
Sep 18 Javascript
JavaScript代码判断输入的字符串是否含有特殊字符和表情代码实例
Aug 17 Javascript
vue-resource请求实现http登录拦截或者路由拦截的方法
Jul 11 Javascript
JavaScript原生数组函数实例汇总
Oct 14 Javascript
Vue vee-validate插件的简单使用
Jun 22 Vue.js
js实现星星海特效的示例
Sep 28 #Javascript
vue中重定向redirect:‘/index‘,不显示问题、跳转出错的完美解决
Sep 28 #Javascript
Openlayers绘制聚合标注
Sep 28 #Javascript
Openlayers绘制地图标注
Sep 28 #Javascript
Openlayers实现图形绘制
Sep 28 #Javascript
Openlayers显示瓦片网格信息的方法
Sep 28 #Javascript
Openlayers实现地图全屏显示
Sep 28 #Javascript
You might like
Windows 下的 PHP-PEAR 安装方法
2010/11/20 PHP
php中时间轴开发(刚刚、5分钟前、昨天10:23等)
2011/10/03 PHP
PHPExcel读取Excel文件的实现代码
2011/12/06 PHP
php获取远程图片体积大小的实例
2013/11/12 PHP
php打乱数组二维数组多维数组的简单实例
2016/06/17 PHP
thinkphp5.1框架容器与依赖注入实例分析
2019/07/23 PHP
php array 转json及java 转换 json数据格式操作示例
2019/11/13 PHP
LBS blog sql注射漏洞[All version]-官方已有补丁
2007/08/26 Javascript
jQuery Pagination Ajax分页插件(分页切换时无刷新与延迟)中文翻译版
2013/01/11 Javascript
JavaScript对象学习经验整理
2013/10/12 Javascript
jquery简单实现鼠标经过导航条改变背景图
2013/12/17 Javascript
JS实现漂亮的窗口拖拽效果(可改变大小、最大化、最小化、关闭)
2015/10/10 Javascript
使用jQuery Mobile框架开发移动端Web App的入门教程
2016/05/17 Javascript
canvas基础绘制-绚丽倒计时的实例
2017/09/17 Javascript
angularjs中$http异步上传Excel文件方法
2018/02/23 Javascript
微信小程序前端promise封装代码实例
2019/08/24 Javascript
Python3基础之基本数据类型概述
2014/08/13 Python
简单介绍Python中的try和finally和with方法
2015/05/05 Python
python脚本设置超时机制系统时间的方法
2016/02/21 Python
python使用matplotlib模块绘制多条折线图、散点图
2020/04/26 Python
Python基于OpenCV实现人脸检测并保存
2019/07/23 Python
python实现按首字母分类查找功能
2019/10/31 Python
Python必须了解的35个关键词
2020/07/16 Python
CSS3 please 跨浏览器的CSS3产生器
2010/03/14 HTML / CSS
世界上最大的字体市场:MyFonts
2020/01/10 全球购物
什么是唯一索引
2015/07/05 面试题
大学四年职业生涯规划书范文
2014/01/02 职场文书
幼儿园教师请假制度
2014/01/16 职场文书
校园奶茶店创业计划书
2014/01/23 职场文书
《蒲公英》教学反思
2014/02/28 职场文书
项目申报专员岗位职责
2014/07/09 职场文书
工作时间擅自离岗检讨书
2014/10/24 职场文书
担保书怎么写 ?
2019/04/22 职场文书
导游词之嵊泗列岛
2019/10/30 职场文书
Oracle 区块链表创建过程详解
2021/05/15 Oracle
Unicode中的CJK(中日韩统一表意文字)字符小结
2021/12/06 HTML / CSS