基于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 相关文章推荐
JQuery datepicker 使用方法
May 20 Javascript
js关闭子窗体刷新父窗体实现方法
Dec 04 Javascript
js实现点击后将文字或图片复制到剪贴板的方法
Aug 04 Javascript
node.js中的path.delimiter方法使用说明
Dec 09 Javascript
浅谈Javascript变量作用域问题
Dec 16 Javascript
jquery插件jSignature实现手动签名
May 04 Javascript
jquery实现的淡入淡出下拉菜单效果
Aug 25 Javascript
常用javascript表单验证汇总
Jul 20 Javascript
学习JavaScript设计模式之迭代器模式
Jan 19 Javascript
基于JS模仿windows文件按名称排序效果
Jun 29 Javascript
jQuery+CSS3实现四种应用广泛的导航条制作实例详解
Sep 17 Javascript
js实现二级导航功能
Mar 03 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
dedecms模版制作使用方法
2007/04/03 PHP
php学习笔记 php中面向对象三大特性之一[封装性]的应用
2011/06/13 PHP
解析PHP工厂模式的好处
2013/06/18 PHP
PHP实现微信公众平台音乐点播
2014/03/20 PHP
thinkphp实现上一篇与下一篇的方法
2014/12/08 PHP
php源码分析之DZX1.5加密解密函数authcode用法
2015/06/17 PHP
WHOOPS PHP调试库的使用
2017/09/29 PHP
Laravel框架路由设置与使用示例
2018/06/12 PHP
Yii实现微信公众号场景二维码的方法实例
2020/08/30 PHP
Nigma vs Liquid BO3 第二场2.14
2021/03/10 DOTA
jQuery中文入门指南,翻译加实例,jQuery的起点教程
2007/02/09 Javascript
鼠标滑上去后图片放大浮出效果的js代码
2011/05/28 Javascript
javascript读写XML实现广告轮换(兼容IE、FF)
2013/08/09 Javascript
js下将阿拉伯数字每三位一逗号分隔(如:15000000转化为15,000,000)
2014/06/02 Javascript
NodeJS Web应用监听sock文件实例
2015/02/18 NodeJs
JS运动基础框架实例分析
2015/03/03 Javascript
JQuery实现可直接编辑的表格
2015/04/16 Javascript
Knockout自定义绑定创建方法
2015/12/26 Javascript
Nodejs+Socket.io实现通讯实例代码
2017/02/13 NodeJs
详解JavaScript中的坐标和距离
2019/05/27 Javascript
详解Vuex下Store的模块化拆分实践
2019/07/31 Javascript
vue项目配置 webpack-obfuscator 进行代码加密混淆的实现
2021/02/26 Vue.js
python 实现堆排序算法代码
2012/06/05 Python
python中的hashlib和base64加密模块使用实例
2014/09/02 Python
轻量级的Web框架Flask 中模块化应用的实现
2017/09/11 Python
Python基于聚类算法实现密度聚类(DBSCAN)计算【测试可用】
2018/12/26 Python
Python整数对象实现原理详解
2019/07/01 Python
Python + OpenCV 实现LBP特征提取的示例代码
2019/07/11 Python
Python partial函数原理及用法解析
2019/12/11 Python
Docker部署Python爬虫项目的方法步骤
2020/01/19 Python
浅析Python __name__ 是什么
2020/07/07 Python
纯CSS3实现表单验证效果(非常不错)
2017/01/18 HTML / CSS
旅游管理专业个人求职信范文
2013/12/24 职场文书
社区活动总结报告
2014/05/05 职场文书
超市理货员岗位职责
2014/07/04 职场文书
使用CSS连接数据库的方式
2022/02/28 HTML / CSS