基于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非法字符过滤代码(骂人的话等等)
May 26 Javascript
js类型检查实现代码
Oct 29 Javascript
js判断undefined类型,undefined,null, 的区别详细解析
Dec 16 Javascript
javascript事件冒泡详解和捕获、阻止方法
Apr 12 Javascript
JQuery右键菜单插件ContextMenu使用指南
Dec 19 Javascript
JS获取图片高度宽度的方法分享
Apr 17 Javascript
jQuery prototype冲突的2种解决方法(附demo示例下载)
Jan 21 Javascript
论JavaScript模块化编程
Mar 07 Javascript
详解MVC如何使用开源分页插件(shenniu.pager.js)
Dec 16 Javascript
Javascript刷新页面的实例
Sep 23 Javascript
layui的select联动实现代码
Sep 28 Javascript
JS 逻辑判断不要只知道用 if-else 和 switch条件判断(小技巧)
May 27 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 mysql数据库操作类
2008/06/04 PHP
微信扫描二维码登录网站代码示例
2013/12/30 PHP
php将textarea数据提交到mysql出现很多空格的解决方法
2014/12/19 PHP
php处理json格式数据经典案例总结
2016/05/19 PHP
php 提交表单 关闭layer弹窗iframe的实例讲解
2018/08/20 PHP
php转换上传word文件为PDF的方法【基于COM组件】
2019/06/10 PHP
Javascript处理DOM元素事件实现代码
2012/05/23 Javascript
JS数组的赋值介绍
2014/03/10 Javascript
手机端网页点击链接触发自动拨打或保存电话的示例代码
2014/08/15 Javascript
JS和css实现检测移动设备方向的变化并判断横竖屏幕
2015/05/25 Javascript
AngularJS ng-bind 指令简单实现
2016/07/30 Javascript
Centos7 中安装 Node.js v4.4.4
2016/11/03 Javascript
jQuery按需加载轮播图(web前端性能优化)
2017/02/17 Javascript
详解vue-cli + webpack 多页面实例应用
2017/04/25 Javascript
深入解析Python中的集合类型操作符
2015/08/19 Python
python机器学习实战之K均值聚类
2017/12/20 Python
pytorch模型预测结果与ndarray互转方式
2020/01/15 Python
Python拼接字符串的7种方式详解
2020/03/19 Python
Python 随机生成测试数据的模块:faker基本使用方法详解
2020/04/09 Python
Python绘图之二维图与三维图详解
2020/08/04 Python
Python命名空间及作用域原理实例解析
2020/08/12 Python
python 调用API接口 获取和解析 Json数据
2020/09/28 Python
python 基于opencv操作摄像头
2020/12/24 Python
使用HTML5中的contentEditable来将多行文本自动增高
2016/03/01 HTML / CSS
MAC彩妆澳洲官网:M·A·C AU
2021/01/17 全球购物
最新党员的自我评价分享
2013/11/04 职场文书
《两个铁球同时着地》教学反思
2014/02/13 职场文书
二手房买卖协议书
2014/04/10 职场文书
就业协议书样本
2014/08/20 职场文书
2015年小学美术工作总结
2015/05/25 职场文书
外出听课学习心得体会
2016/01/15 职场文书
如何在pycharm中快捷安装pip命令(如pygame)
2021/05/31 Python
只用40行Python代码就能写出pdf转word小工具
2021/05/31 Python
一篇文章带你复习java知识点
2021/06/28 Java/Android
Redis Lua脚本实现ip限流示例
2022/07/15 Redis
HTML静态页面获取url参数和UserAgent的实现
2022/08/05 HTML / CSS