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 相关文章推荐
让mayfish支持mysqli数据库驱动的实现方法
May 22 Javascript
JavaScript使用过程中需要注意的地方和一些基本语法
Aug 26 Javascript
jQuery中绑定事件的命名空间详解
Apr 05 Javascript
JavaScript精炼之构造函数 Constructor及Constructor属性详解
Nov 05 Javascript
SpringMVC框架下JQuery传递并解析Json格式的数据是如何实现的
Dec 10 Javascript
Node.js中常规的文件操作总结
Oct 13 Javascript
JS实现滑动门效果的方法详解
Dec 19 Javascript
Express下采用bcryptjs进行密码加密的方法
Feb 07 Javascript
微信小程序之分享页面如何返回首页的示例
Mar 28 Javascript
微信小程序以ssm做后台开发的实现示例
Apr 08 Javascript
vue实现动态表格提交参数动态生成控件的操作
Nov 09 Javascript
Vue中引入svg图标的两种方式
Jan 14 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
模拟SQLSERVER的两个函数:dateadd(),datediff()
2006/10/09 PHP
第二节--PHP5 的对象模型
2006/11/16 PHP
php Smarty 字符比较代码
2011/02/27 PHP
laravel框架创建授权策略实例分析
2019/11/22 PHP
Javascript 获取链接(url)参数的方法
2009/02/15 Javascript
JavaScript 继承详解(一)
2009/07/13 Javascript
FF IE浏览器修改标签透明度的方法
2014/01/27 Javascript
JavaScript程序中的流程控制语句用法总结
2016/05/23 Javascript
微信小程序页面开发注意事项整理
2017/05/18 Javascript
3种vue组件的书写形式
2017/11/29 Javascript
如何重置vue打印变量的显示方式
2017/12/06 Javascript
vue+element-ui+ajax实现一个表格的实例
2018/03/09 Javascript
js提取中文拼音首字母的封装工具类
2018/03/12 Javascript
Vue 实现对quill-editor组件中的工具栏添加title
2020/08/03 Javascript
vue实现禁止浏览器记住密码功能的示例代码
2021/02/03 Vue.js
简单了解Python中的几种函数
2017/11/03 Python
Python使用cx_Oracle模块操作Oracle数据库详解
2018/05/07 Python
python 识别图片中的文字信息方法
2018/05/10 Python
对python的输出和输出格式详解
2018/12/08 Python
python 随机打乱 图片和对应的标签方法
2018/12/14 Python
Pyqt5如何让QMessageBox按钮显示中文示例代码
2019/04/11 Python
python flask框架实现传数据到js的方法分析
2019/06/11 Python
Python操作多维数组输出和矩阵运算示例
2019/11/28 Python
将数据集制作成VOC数据集格式的实例
2020/02/17 Python
利用Python pandas对Excel进行合并的方法示例
2020/11/04 Python
python中PyQuery库用法分享
2021/01/15 Python
IE浏览器单独写CSS样式的几种方法
2014/10/14 HTML / CSS
css3给背景图片加颜色遮罩的方法
2019/11/05 HTML / CSS
全球性的在线商店:Vogca
2019/05/10 全球购物
zooplus意大利:在线宠物商店
2019/08/07 全球购物
公务员的自我鉴定
2013/10/26 职场文书
可口可乐广告词
2014/03/20 职场文书
2014年档案管理员工作总结
2014/12/01 职场文书
2015年幼儿园班务工作总结
2015/05/12 职场文书
详解Vue router路由
2021/11/20 Vue.js
Java Lambda表达式常用的函数式接口
2022/04/07 Java/Android