经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » JavaScript » 查看文章
用JS实现贪吃蛇游戏
来源:jb51  时间:2022/7/4 8:50:58  对本文有异议

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

效果图:

完整代码如下:

html:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. ?
  4. <head>
  5. ? ? <meta charset="UTF-8">
  6. ? ? <meta http-equiv="X-UA-Compatible" content="IE=edge">
  7. ? ? <meta name="viewport" content="width=device-width, initial-scale=1.0">
  8. ? ? <title>Document</title>
  9. ? ? <link rel="stylesheet" href="index.css" >
  10. ? ? <script src="index.js"></script>
  11. </head>
  12. ?
  13. <body>
  14. ? ? <div class="content">
  15. ? ? ? ? <div class="btn startBtn"><button></button></div>
  16. ? ? ? ? <div class="btn pauseBtn"><button></button></div>
  17. ? ? ? ? <div id="snakeWrap">
  18. ? ? ? ? ? ? <!-- <div class="snakeHead"></div>
  19. ? ? ? ? ? ? <div class="snakeBody"></div>
  20. ? ? ? ? ? ? <div class="food"></div> -->
  21. ? ? ? ? </div>
  22. ? ? </div>
  23. ?
  24. </body>
  25. ?
  26. </html>

css:

  1. .content {
  2. ? ? position: relative;
  3. ? ? width: 640px;
  4. ? ? height: 640px;
  5. ? ? margin: 100px auto;
  6. }
  7. ?
  8. .btn {
  9. ? ? width: 100%;
  10. ? ? height: 100%;
  11. ? ? position: absolute;
  12. ? ? top: 0;
  13. ? ? left: 0;
  14. ? ? background-color: black;
  15. ? ? opacity: .1;
  16. ? ? z-index: 2;
  17. }
  18. ?
  19. .btn button {
  20. ? ? background: none;
  21. ? ? border: none;
  22. ? ? background-size: 100% 100%;
  23. ? ? cursor: pointer;
  24. ? ? outline: none;
  25. ? ? position: absolute;
  26. ? ? left: 50%;
  27. ? ? top: 50%;
  28. }
  29. ?
  30. .startBtn button {
  31. ? ? width: 200px;
  32. ? ? height: 80px;
  33. ? ? background-image: url(../贪吃蛇/img/btn.gif);
  34. ? ? margin-left: -100px;
  35. ? ? margin-top: -40px;
  36. }
  37. ?
  38. .pauseBtn {
  39. ? ? display: none;
  40. }
  41. ?
  42. .pauseBtn button {
  43. ? ? width: 70px;
  44. ? ? height: 70px;
  45. ? ? background-image: url(../贪吃蛇/img/btn4.png);
  46. ? ? margin-left: -35px;
  47. ? ? margin-top: -35px;
  48. }
  49. ?
  50. #snakeWrap {
  51. ? ? width: 600px;
  52. ? ? height: 600px;
  53. ? ? background-color: pink;
  54. ? ? border: 20px solid purple;
  55. ? ? position: relative;
  56. }
  57. ?
  58. ?
  59. /* #snakeWrap div {
  60. ? ? width: 20px;
  61. ? ? height: 20px;
  62. } */
  63. ?
  64. .snakeHead {
  65. ? ? background-image: url(../贪吃蛇/img/snake.png);
  66. ? ? background-size: cover;
  67. }
  68. ?
  69. .snakeBody {
  70. ? ? background-color: rgb(85, 146, 126);
  71. ? ? border-radius: 50%;
  72. }
  73. ?
  74. .food {
  75. ? ? background-image: url(../贪吃蛇/img/草莓.png);
  76. ? ? background-size: cover;
  77. }

js:

  1. window.addEventListener('load', function() {
  2. ? ? // 声明方块的宽高,行数和列数
  3. ? ? var sw = 20,
  4. ? ? ? ? sh = 20,
  5. ? ? ? ? tr = 30,
  6. ? ? ? ? td = 30;
  7. ?
  8. ? ? var snake = null, //蛇的实例
  9. ? ? ? ? food = null, //食物的实例
  10. ? ? ? ? game = null; //游戏的实例
  11. ?
  12. ? ? function Square(x, y, classname) {
  13. ? ? ? ? this.x = sw * x;
  14. ? ? ? ? this.y = sh * y;
  15. ? ? ? ? this.class = classname;
  16. ?
  17. ? ? ? ? this.viewContent = document.createElement('div'); //方块对应的DOM元素
  18. ? ? ? ? this.viewContent.className = this.class;
  19. ? ? ? ? this.parent = document.getElementById('snakeWrap'); //方块的父级
  20. ? ? }
  21. ? ? //创建方块DOM,并添加到页面里
  22. ? ? Square.prototype.create = function() {
  23. ? ? ? ? this.viewContent.style.position = 'absolute';
  24. ? ? ? ? this.viewContent.style.width = sw + 'px';
  25. ? ? ? ? this.viewContent.style.height = sh + 'px';
  26. ? ? ? ? this.viewContent.style.left = this.x + 'px';
  27. ? ? ? ? this.viewContent.style.top = this.y + 'px';
  28. ? ? ? ? this.parent.appendChild(this.viewContent);
  29. ?
  30. ? ? };
  31. ? ? Square.prototype.remove = function() {
  32. ? ? ? ? this.parent.removeChild(this.viewContent);
  33. ? ? };
  34. ? ? //蛇
  35. ? ? function Snake() {
  36. ? ? ? ? this.head = null //存蛇头的信息
  37. ? ? ? ? this.tail = null //存蛇尾的信息
  38. ? ? ? ? this.pos = []; //存蛇身上每个方块的位置
  39. ?
  40. ? ? ? ? //存储蛇走的方向,用一个对象来表示
  41. ? ? ? ? this.directionNum = {
  42. ? ? ? ? ? ? left: {
  43. ? ? ? ? ? ? ? ? x: -1,
  44. ? ? ? ? ? ? ? ? y: 0,
  45. ? ? ? ? ? ? ? ? rotate: 180
  46. ? ? ? ? ? ? },
  47. ? ? ? ? ? ? right: {
  48. ? ? ? ? ? ? ? ? x: 1,
  49. ? ? ? ? ? ? ? ? y: 0,
  50. ? ? ? ? ? ? ? ? rotate: 0
  51. ? ? ? ? ? ? },
  52. ? ? ? ? ? ? up: {
  53. ? ? ? ? ? ? ? ? x: 0,
  54. ? ? ? ? ? ? ? ? y: -1,
  55. ? ? ? ? ? ? ? ? rotate: -90
  56. ? ? ? ? ? ? },
  57. ? ? ? ? ? ? down: {
  58. ? ? ? ? ? ? ? ? x: 0,
  59. ? ? ? ? ? ? ? ? y: 1,
  60. ? ? ? ? ? ? ? ? rotate: 90
  61. ? ? ? ? ? ? }
  62. ? ? ? ? };
  63. ? ? }
  64. ? ? //初始化
  65. ? ? Snake.prototype.init = function() {
  66. ? ? ? ? //创建蛇头
  67. ? ? ? ? var snakeHead = new Square(2, 0, 'snakeHead');
  68. ? ? ? ? snakeHead.create();
  69. ? ? ? ? this.head = snakeHead; //存储蛇头信息
  70. ? ? ? ? this.pos.push([2, 0]); //把蛇头的位置存起来
  71. ?
  72. ? ? ? ? //创建蛇身体1
  73. ? ? ? ? var snakeBody1 = new Square(1, 0, 'snakeBody');
  74. ? ? ? ? snakeBody1.create();
  75. ? ? ? ? this.pos.push([1, 0]); //把蛇身1的坐标存起来
  76. ?
  77. ? ? ? ? //创建蛇身体2
  78. ? ? ? ? var snakeBody2 = new Square(0, 0, 'snakeBody');
  79. ? ? ? ? snakeBody2.create();
  80. ? ? ? ? this.tail = snakeBody2; //把蛇尾的信息存起来
  81. ? ? ? ? this.pos.push([0, 0]); //把蛇身1的坐标存起来
  82. ?
  83. ? ? ? ? //形成链表关系
  84. ? ? ? ? snakeHead.last = null;
  85. ? ? ? ? snakeHead.next = snakeBody1;
  86. ?
  87. ? ? ? ? snakeBody1.last = snakeHead;
  88. ? ? ? ? snakeBody1.next = snakeBody2;
  89. ?
  90. ? ? ? ? snakeBody2.last = snakeBody1;
  91. ? ? ? ? snakeBody2.next = null;
  92. ?
  93. ? ? ? ? //给蛇添加一条属性,用来表示蛇的走向
  94. ? ? ? ? this.direction = this.directionNum.right; //默认让蛇往右走
  95. ? ? };
  96. ?
  97. ? ? //该方法用来获取蛇头的下一个位置对应的元素,要根据元素做不同的事情
  98. ? ? Snake.prototype.getNextPos = function() {
  99. ? ? ? ? var nextPos = [ //蛇头要走的下一个点的坐标
  100. ? ? ? ? ? ? this.head.x / sw + this.direction.x,
  101. ? ? ? ? ? ? this.head.y / sh + this.direction.y
  102. ? ? ? ? ];
  103. ? ? ? ? // console.log(nextPos[0]);
  104. ?
  105. ? ? ? ? //下个点是自己,游戏结束
  106. ? ? ? ? var selfCollied = false; //是否撞到自己,默认是否
  107. ? ? ? ? //value表示数组中的某一项
  108. ? ? ? ? this.pos.forEach(function(value) {
  109. ? ? ? ? ? ? // console.log(nextPos[0], value[0]);
  110. ? ? ? ? ? ? if (value[0] == nextPos[0] && value[1] == nextPos[1]) {
  111. ? ? ? ? ? ? ? ? selfCollied = true;
  112. ? ? ? ? ? ? ? ? // console.log(2);
  113. ? ? ? ? ? ? }
  114. ? ? ? ? });
  115. ? ? ? ? if (selfCollied) {
  116. ? ? ? ? ? ? console.log('撞到自己了!');
  117. ? ? ? ? ? ? this.strategies.die.call(this);
  118. ? ? ? ? ? ? return;
  119. ? ? ? ? }
  120. ?
  121. ? ? ? ? // 下个点是墙,游戏结束
  122. ? ? ? ? if (nextPos[0] < 0 || nextPos[1] < 0 || nextPos[0] > td - 1 || nextPos[1] > tr - 1) {
  123. ? ? ? ? ? ? console.log('撞墙!');
  124. ? ? ? ? ? ? this.strategies.die.call(this);
  125. ? ? ? ? ? ? return;
  126. ? ? ? ? }
  127. ?
  128. ? ? ? ? // 下个点是食物,吃
  129. ? ? ? ? if (food && food.pos[0] == nextPos[0] && food.pos[1] == nextPos[1]) {
  130. ? ? ? ? ? ? //如这条件成立,说明蛇头走的下一点是食物的点
  131. ? ? ? ? ? ? console.log('撞到食物了');
  132. ? ? ? ? ? ? this.strategies.eat.call(this);
  133. ? ? ? ? ? ? return;
  134. ? ? ? ? }
  135. ?
  136. ? ? ? ? // 下个点什么都不是,继续走
  137. ? ? ? ? this.strategies.move.call(this);
  138. ?
  139. ? ? };
  140. ? ? // 处理碰撞后要做的事
  141. ? ? Snake.prototype.strategies = {
  142. ? ? ? ? move: function(format) { //format这个参数用于决定要不要删除最后一个方块(蛇尾),当传了这个参数就表示要做的事情是吃
  143. ? ? ? ? ? ? //创建新身体(在旧蛇头的位置)
  144. ?
  145. ? ? ? ? ? ? var newBody = new Square(this.head.x / sw, this.head.y / sh, 'snakeBody');
  146. ? ? ? ? ? ? //更新链表的关系
  147. ? ? ? ? ? ? newBody.next = this.head.next;
  148. ? ? ? ? ? ? newBody.next.last = newBody;
  149. ? ? ? ? ? ? newBody.last = null;
  150. ?
  151. ? ? ? ? ? ? //把旧蛇头从原来的位置删除
  152. ? ? ? ? ? ? this.head.remove();
  153. ? ? ? ? ? ? newBody.create();
  154. ?
  155. ? ? ? ? ? ? //创建新的蛇头(蛇头下一个要走到的点nextPos)
  156. ? ? ? ? ? ? var newHead = new Square(this.head.x / sw + this.direction.x, this.head.y / sh + this.direction.y, 'snakeHead');
  157. ?
  158. ? ? ? ? ? ? //更新链表关系
  159. ? ? ? ? ? ? newHead.next = newBody;
  160. ? ? ? ? ? ? newHead.last = null;
  161. ? ? ? ? ? ? newBody.last = newHead;
  162. ? ? ? ? ? ? newHead.viewContent.style.transform = 'rotate(' + this.direction.rotate + 'deg)';
  163. ? ? ? ? ? ? newHead.create();
  164. ?
  165. ? ? ? ? ? ? //蛇身上的每一个方块的坐标也要更新
  166. ? ? ? ? ? ? this.pos.splice(0, 0, [this.head.x / sw + this.direction.x, this.head.y / sh + this.direction.y])
  167. ? ? ? ? ? ? this.head = newHead; //还要把this.head的信息更新一下
  168. ?
  169. ? ? ? ? ? ? if (!format) { //如果format的值为false,表示需要删除(除了吃之外的操作)
  170. ? ? ? ? ? ? ? ? this.tail.remove();
  171. ? ? ? ? ? ? ? ? this.tail = this.tail.last;
  172. ? ? ? ? ? ? ? ? this.pos.pop();
  173. ? ? ? ? ? ? }
  174. ? ? ? ? },
  175. ? ? ? ? eat: function() {
  176. ? ? ? ? ? ? this.strategies.move.call(this, true);
  177. ? ? ? ? ? ? createFood();
  178. ? ? ? ? ? ? game.score++;
  179. ? ? ? ? },
  180. ? ? ? ? die: function() {
  181. ? ? ? ? ? ? // console.log('die');
  182. ? ? ? ? ? ? game.over();
  183. ? ? ? ? }
  184. ? ? }
  185. ?
  186. ?
  187. ? ? snake = new Snake();
  188. ?
  189. ?
  190. ?
  191. ? ? //创建食物
  192. ? ? function createFood() {
  193. ? ? ? ? //食物小方块的随机坐标
  194. ?
  195. ? ? ? ? var x = null;
  196. ? ? ? ? var y = null;
  197. ?
  198. ? ? ? ? var include = true; //循环跳出的条件,true表示食物坐标在蛇身上。(需要继续循环)false表示食物的坐标不再蛇身上(不用继续循环)
  199. ? ? ? ? while (include) {
  200. ? ? ? ? ? ? x = Math.round(Math.random() * (td - 1));
  201. ? ? ? ? ? ? y = Math.round(Math.random() * (tr - 1));
  202. ?
  203. ? ? ? ? ? ? snake.pos.forEach(function(value) {
  204. ? ? ? ? ? ? ? ? if (x != value[0] && y != value[1]) {
  205. ? ? ? ? ? ? ? ? ? ? //这个条件成立说明现在随机出来的这个坐标,在蛇身上没有找到。
  206. ? ? ? ? ? ? ? ? ? ? include = false;
  207. ? ? ? ? ? ? ? ? }
  208. ? ? ? ? ? ? });
  209. ? ? ? ? }
  210. ?
  211. ? ? ? ? //生成食物
  212. ? ? ? ? food = new Square(x, y, 'food');
  213. ? ? ? ? //存储生成食物的坐标,用于跟蛇头要走的下一坐标对比
  214. ? ? ? ? food.pos = [x, y];
  215. ?
  216. ? ? ? ? var foodDom = document.querySelector('.food');
  217. ? ? ? ? if (foodDom) {
  218. ? ? ? ? ? ? foodDom.style.left = x * sw + 'px';
  219. ? ? ? ? ? ? foodDom.style.top = y * sh + 'px';
  220. ? ? ? ? } else {
  221. ? ? ? ? ? ? food.create();
  222. ? ? ? ? }
  223. ?
  224. ? ? }
  225. ? ? //创建游戏逻辑
  226. ? ? function Game() {
  227. ? ? ? ? this.timer = null;
  228. ? ? ? ? this.score = 0;
  229. ? ? }
  230. ? ? Game.prototype.init = function() {
  231. ? ? ? ? snake.init();
  232. ? ? ? ? // snake.getNextPos();
  233. ? ? ? ? createFood();
  234. ? ? ? ? var flag = true;
  235. ? ? ? ? document.onkeydown = function(ev) {
  236. ? ? ? ? ? ? //当蛇在往右走,不能按左键
  237. ? ? ? ? ? ? if (ev.which == 37 && snake.direction != snake.directionNum.right) {
  238. ? ? ? ? ? ? ? ? if (flag) {
  239. ? ? ? ? ? ? ? ? ? ? flag = false;
  240. ? ? ? ? ? ? ? ? ? ? setTimeout(function() {
  241. ? ? ? ? ? ? ? ? ? ? ? ? snake.direction = snake.directionNum.left;
  242. ? ? ? ? ? ? ? ? ? ? ? ? flag = true;
  243. ? ? ? ? ? ? ? ? ? ? }, 150)
  244. ? ? ? ? ? ? ? ? }
  245. ?
  246. ? ? ? ? ? ? } else if (ev.which == 38 && snake.direction != snake.directionNum.down) {
  247. ? ? ? ? ? ? ? ? if (flag) {
  248. ? ? ? ? ? ? ? ? ? ? flag = false;
  249. ? ? ? ? ? ? ? ? ? ? setTimeout(function() {
  250. ? ? ? ? ? ? ? ? ? ? ? ? snake.direction = snake.directionNum.up;
  251. ? ? ? ? ? ? ? ? ? ? ? ? flag = true;
  252. ? ? ? ? ? ? ? ? ? ? }, 150)
  253. ? ? ? ? ? ? ? ? }
  254. ? ? ? ? ? ? } else if (ev.which == 39 && snake.direction != snake.directionNum.left) {
  255. ? ? ? ? ? ? ? ? if (flag) {
  256. ? ? ? ? ? ? ? ? ? ? flag = false;
  257. ? ? ? ? ? ? ? ? ? ? setTimeout(function() {
  258. ? ? ? ? ? ? ? ? ? ? ? ? snake.direction = snake.directionNum.right;
  259. ? ? ? ? ? ? ? ? ? ? ? ? flag = true;
  260. ? ? ? ? ? ? ? ? ? ? }, 150)
  261. ? ? ? ? ? ? ? ? }
  262. ? ? ? ? ? ? } else if (ev.which == 40 && snake.direction != snake.directionNum.up) {
  263. ? ? ? ? ? ? ? ? if (flag) {
  264. ? ? ? ? ? ? ? ? ? ? flag = false;
  265. ? ? ? ? ? ? ? ? ? ? setTimeout(function() {
  266. ? ? ? ? ? ? ? ? ? ? ? ? snake.direction = snake.directionNum.down;
  267. ? ? ? ? ? ? ? ? ? ? ? ? flag = true;
  268. ? ? ? ? ? ? ? ? ? ? }, 150)
  269. ? ? ? ? ? ? ? ? }
  270. ? ? ? ? ? ? }
  271. ? ? ? ? }
  272. ? ? ? ? this.start();
  273. ? ? };
  274. ? ? //开始游戏
  275. ? ? Game.prototype.start = function() {
  276. ? ? ? ? this.timer = setInterval(function() {
  277. ? ? ? ? ? ? snake.getNextPos();
  278. ? ? ? ? }, 150);
  279. ? ? };
  280. ? ? //暂停游戏
  281. ? ? Game.prototype.pause = function() {
  282. ? ? ? ? clearInterval(this.timer);
  283. ? ? };
  284. ? ? //游戏结束
  285. ? ? Game.prototype.over = function() {
  286. ? ? ? ? clearInterval(this.timer);
  287. ? ? ? ? alert('你的得分为' + this.score);
  288. ?
  289. ? ? ? ? //游戏回到初始状态
  290. ? ? ? ? var snakeWrap = document.getElementById('snakeWrap');
  291. ? ? ? ? snakeWrap.innerHTML = '';
  292. ?
  293. ? ? ? ? snake = new Snake();
  294. ? ? ? ? game = new Game();
  295. ?
  296. ? ? ? ? var startBtnWrap = document.querySelector('.startBtn');
  297. ? ? ? ? startBtnWrap.style.display = 'block';
  298. ? ? };
  299. ? ? //开启游戏
  300. ? ? game = new Game();
  301. ? ? var startBtn = document.querySelector('.startBtn button');
  302. ? ? console.log(startBtn);
  303. ? ? startBtn.onclick = function() {
  304. ? ? ? ? startBtn.parentNode.style.display = 'none';
  305. ? ? ? ? game.init();
  306. ? ? };
  307. ? ? //暂停游戏
  308. ? ? var snakeWrap = document.getElementById('snakeWrap');
  309. ? ? console.log(snakeWrap);
  310. ? ? var pauseBtn = document.querySelector('.pauseBtn button');
  311. ? ? console.log(pauseBtn);
  312. ? ? snakeWrap.onclick = function() {
  313. ? ? ? ? game.pause();
  314. ? ? ? ? pauseBtn.parentNode.style.display = 'block';
  315. ? ? ? ? console.log(123);
  316. ? ? };
  317. ? ? pauseBtn.onclick = function() {
  318. ? ? ? ? game.start();
  319. ? ? ? ? pauseBtn.parentNode.style.display = 'none';
  320. ? ? }
  321. })

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

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号