基于JavaScript实现十五拼图代码实例


Posted in Javascript onApril 26, 2020

顾名思义,十五拼图就是将游戏画面中的数字从上到下,从左到右按顺序从1到15排列下来,看起来很简单,但是玩起来不容易。

css代码

body {
  font-family: cursive;
  font-size: 14pt;
  text-align: center;
}

#puzzlearea {
  height: 400px;
  margin: 0 auto;
  position: relative;
  width: 400px;
}

.highlight {
  border-color: red;
  cursor: pointer;
}

.puzzletile {
  background-image: url("../background.jpg");
  border: 5px solid black;
  position: absolute;
}

.highlight, #output {
  color: red;
}

.puzzletile, #output {
  font-size: 40pt;
}

html代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>CSE 154 Fifteen Puzzle</title>
  <!-- your files that you will write -->
  <link href="css/fifteen.css" rel="external nofollow" type="text/css" rel="stylesheet"/>
  <script src="js/fifteen.js" type="text/javascript"></script>

</head>
<body>
<h1>Fifteen Puzzle</h1>

<p>
  The goal of the fifteen puzzle is to un-jumble its fifteen squares
  by repeatedly making moves that slide squares into the empty space.
  How quickly can you solve it?
</p>

<div id="puzzlearea">
  <!--
    this area holds the actual fifteen puzzle pieces
    add to it as you need to
  -->
</div>

<p id="controls">
  <button id="shufflebutton">Shuffle</button>
</p>

<div id="output"></div>

<p>
  American puzzle author and mathematician Sam Loyd is often falsely
  credited with creating the puzzle; indeed, Loyd claimed from 1891
  until his death in 1911 that he invented it.
  The puzzle was actually created around 1874 by Noyes Palmer Chapman,
  a postmaster in Canastota, New York.
</p>
</body>
</html>

JavaScript代码

(function () {
  "use strict";

  let NUM = 4; //拼图的行列数 the number of rows/cols in the puzzle
  let spaceRow = 3; // 空白图块所在行
  let spaceColumn = 3; // 空白图块所在列
  let WIDTH = 100; // the pixel width/height of each tile

  // gets everything set when the window has loaded
  window.onload = function () {
   setSize();
   document.getElementById("select").onchange = changeSize;
   document.getElementById("shufflebutton").onclick = shuffle;
   createSquares();

  };

  // add a drop-down list to select difficulty level
  // 设置下拉列表 默认选中 option4
  function setSize() {
   var select = document.createElement("select");
   select.id = "select";
   for (var i = 3; i < 7; i++) {
     var option = document.createElement("option");
     option.innerHTML = i + " * " + i;
     option.value = i;
     option.id = "option" + i;
     select.appendChild(option);
   }
   document.getElementById("controls").appendChild(select);
   document.getElementById("option4").selected = "selected";
  }


  function changeSize() {
   NUM = this.value;
   spaceRow = this.value - 1;
   spaceColumn = this.value - 1;
   WIDTH = parseInt(400 / this.value);
   var puzzlearea = document.getElementById("puzzlearea");
   while (puzzlearea.contains(document.querySelector(".puzzletile"))) {
     puzzlearea.removeChild(document.querySelector(".puzzletile"));
   }
   createSquares();
  }

  // creates 15 puzzle tiles and sets them to their initial position
  function createSquares() {
   for (var i = 1; i < NUM * NUM; i++) {
     var div = document.createElement("div");
     div.className = "puzzletile";
     div.innerHTML = i;
     var row = Math.floor((i - 1) / NUM);
     var column = (i - 1) % NUM;
     var x = column * -1 * WIDTH + "px";
     var y = row * -1 * WIDTH + "px";

     // 减去边框的宽度 并且宽高相等
     div.style.height = WIDTH - 10 + "px";
     div.style.width = div.style.height;
     // 设置background 的 position
     div.style.backgroundPosition = x + " " + y;
     // 为每个拼图添加ID
     div.id = "square_" + row + "_" + column;
     // 设置水平和垂直方向的偏移量
     div.style.top = row * WIDTH + "px";
     div.style.left = column * WIDTH + "px";
     setEvents(div);
     document.getElementById("puzzlearea").appendChild(div);
   }
  }

  // shuffles puzzle tiles for 1000 times
  function shuffle() {
   // 实现Shuffle算法
   for (let j = 0; j < 1000; j++) {
     let neigbors = [];
     // 将所有的拼图 存储到 allPuzzles中
     let allPuzzles = document.getElementsByClassName("puzzletile");
     // 将与空白图块相邻的拼图 存储到数组neigbors中
     for (let i = 0; i < allPuzzles.length; i++) {
      // 判断拼图是否可以移动
      if (moveable(allPuzzles[i]))
        neigbors.push(allPuzzles[i]);
      }
     // 得到一个随机的索引
     let ranNum = getRandomIntInclusive(0, neigbors.length - 1);
     // 获取需要移动的拼图移动之前的偏移量
     let tempTop = neigbors[ranNum].style.top;
     let tempLeft = neigbors[ranNum].style.left;
     // 将拼图移动到空白图块处
     neigbors[ranNum].style.top = spaceRow * WIDTH + "px";
     neigbors[ranNum].style.left = spaceColumn * WIDTH + "px";
     neigbors[ranNum].id = "square_" + spaceRow + "_" + spaceColumn;
     // 更改空白图块的位置
     spaceRow = parseInt(tempTop) / WIDTH;
     spaceColumn = parseInt(tempLeft) / WIDTH;
   }


  }

  // 获取指定区间的随机数
  function getRandomIntInclusive(min, max) {
   min = Math.ceil(min);
   max = Math.floor(max);
   return Math.floor(Math.random() * (max - min + 1)) + min;
  }

  // sets up events for all puzzle tiles
  function setEvents(div) {
   div.onmouseover = function () {
     if (moveable(this)) {
      this.classList.add("highlight"); // when mouse over, adds class "highlight"
     }
   };
   div.onmouseout = function () {
     // when mouse out, removes class "highlight"
     if (moveable(this)) {
      this.classList.remove("highlight"); // when mouse out, remove class "highlight"
     }
   };
   div.onclick = helper;
  }

  // a helper function for function "makeAMove"
  // displays "congratulations" if the player wins
  function helper() {
   if (moveable(this)) {
     makeAMove(this);
     if (win()) {
      document.getElementById("output").innerHTML = "Congratulations! You win!";
     } else {
      document.getElementById("output").innerHTML = "";
     }
   }
  }

  // make one move for the given tile
  function makeAMove(div) {

   div.id = "square_" + spaceRow + "_" + spaceColumn;
   var divRow = parseInt(div.style.top) / WIDTH;
   var divColumn = parseInt(div.style.left) / WIDTH;

   div.style.top = spaceRow * WIDTH + "px";
   div.style.left = spaceColumn * WIDTH + "px";
   spaceRow = divRow;
   spaceColumn = divColumn;

  }

  // return true if the given tile is moveable
  function moveable(div) {

   var divRow = parseInt(div.style.top) / WIDTH;
   var divColumn = parseInt(div.style.left) / WIDTH;
   if (spaceRow == divRow) {
     return Math.abs(spaceColumn - divColumn) == 1;
   }
   else if (spaceColumn == divColumn) {
     return Math.abs(spaceRow - divRow) == 1;
   }
   else {
     return false;
   }
  }

  // return true if all tiles are at their original positions
  function win() {
   var tiles = document.querySelectorAll(".puzzletile");
   for (var i = 0; i < tiles.length; i++) {
     var row = Math.floor(i / NUM);
     var column = i % NUM;
     if (tiles[i].id != "square_" + row + "_" + column) {
      console.log(tiles[i].id);
      return false;
     }
   }
   return true;
  }
})();

最后的效果

基于JavaScript实现十五拼图代码实例

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

Javascript 相关文章推荐
js实现图片放大缩小功能后进行复杂排序的方法
Nov 08 Javascript
Js中获取frames中的元素示例代码
Jul 30 Javascript
JavaScript中如何通过arguments对象实现对象的重载
May 12 Javascript
jQuery通过ajax请求php遍历json数组到table中的代码(推荐)
Jun 12 Javascript
微信小程序  wx.request合法域名配置详解
Nov 23 Javascript
Bootstrap 模态框实例插件案例分析
Dec 28 Javascript
AngularJS 防止页面闪烁的方法
Mar 09 Javascript
JS设置手机验证码60s等待实现代码
Jun 14 Javascript
利用纯js + transition动画实现移动端web轮播图详解
Sep 10 Javascript
Vue利用路由钩子token过期后跳转到登录页的实例
Oct 26 Javascript
Vue.js实现双向数据绑定方法(表单自动赋值、表单自动取值)
Aug 27 Javascript
js利用递归与promise 按顺序请求数据的方法
Aug 30 Javascript
小程序自定义导航栏兼容适配所有机型(附完整案例)
Apr 26 #Javascript
vue 使用 vue-pdf 实现pdf在线预览的示例代码
Apr 26 #Javascript
javascript设计模式 ? 访问者模式原理与用法实例分析
Apr 26 #Javascript
详解关于Vue单元测试的几个坑
Apr 26 #Javascript
es6函数之箭头函数用法实例详解
Apr 25 #Javascript
es6数组之扩展运算符操作实例分析
Apr 25 #Javascript
es6函数之尾调用优化实例分析
Apr 25 #Javascript
You might like
php imagecreatetruecolor 创建高清和透明图片代码小结
2010/05/15 PHP
PHP hex2bin()函数用法讲解
2019/02/25 PHP
javascript getElementsByClassName函数
2010/04/01 Javascript
JavaScript中两种链式调用实现代码
2011/01/12 Javascript
基于jquery自定义图片热区效果
2012/07/21 Javascript
使用jQuery解决IE与FireFox下createElement方法的差异
2013/11/14 Javascript
利用javascript判断文件是否存在
2013/12/31 Javascript
如何通过js实现图片预览功能【附实例代码】
2016/03/30 Javascript
JavaScript常用判断写法大全(推荐)
2016/05/30 Javascript
从零学习node.js之利用express搭建简易论坛(七)
2017/02/25 Javascript
ES6新特性七:数组的扩充详解
2017/04/21 Javascript
基于Bootstrap的标签页组件及bootstrap-tab使用说明
2017/07/25 Javascript
原生JavaScrpit中异步请求Ajax实现方法
2017/11/03 Javascript
关于angularJs清除浏览器缓存的方法
2017/11/28 Javascript
[原创]js实现保存文本框内容为本地文件兼容IE,chrome,火狐浏览器
2018/02/14 Javascript
基于nodejs res.end和res.send的区别
2018/05/14 NodeJs
纯js封装的ajax功能函数与用法示例
2018/05/14 Javascript
浅谈vue引用静态资源需要注意的事项
2018/09/28 Javascript
node将geojson转shp返回给前端的实现方法
2019/05/29 Javascript
Vue数据绑定实例写法
2019/08/06 Javascript
微信小程序上传图片并等比列压缩到指定大小的实例代码
2019/10/24 Javascript
jQuery+css实现的点击图片放大缩小预览功能示例【图片预览 查看大图】
2020/05/29 jQuery
[07:39]第一届亚洲邀请赛回顾视频
2017/02/14 DOTA
两个命令把 Vim 打造成 Python IDE的方法
2016/03/20 Python
Python API自动化框架总结
2019/11/12 Python
opencv python如何实现图像二值化
2020/02/03 Python
Django自关联实现多级联动查询实例
2020/05/19 Python
Keras预训练的ImageNet模型实现分类操作
2020/07/07 Python
Python+OpenCV检测灯光亮点的实现方法
2020/11/02 Python
上课玩手机检讨书
2014/02/08 职场文书
揭牌仪式策划方案
2014/05/28 职场文书
承诺书范文
2014/06/03 职场文书
七一讲话心得体会
2014/09/05 职场文书
外出培训学习心得体会
2016/01/18 职场文书
python实现调用摄像头并拍照发邮箱
2021/04/27 Python
前端JS获取URL参数的4种方法总结
2022/04/05 Javascript