基于JavaScript實現(xiàn)十五拼圖代碼實例
更新時間:2020年04月26日 09:06:59 作者:陳太浪
這篇文章主要介紹了基于JavaScript實現(xiàn)十五拼圖代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
顧名思義,十五拼圖就是將游戲畫面中的數(shù)字從上到下,從左到右按順序從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; //拼圖的行列數(shù) 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 // 設(shè)置下拉列表 默認選中 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; // 設(shè)置background 的 position div.style.backgroundPosition = x + " " + y; // 為每個拼圖添加ID div.id = "square_" + row + "_" + column; // 設(shè)置水平和垂直方向的偏移量 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() { // 實現(xiàn)Shuffle算法 for (let j = 0; j < 1000; j++) { let neigbors = []; // 將所有的拼圖 存儲到 allPuzzles中 let allPuzzles = document.getElementsByClassName("puzzletile"); // 將與空白圖塊相鄰的拼圖 存儲到數(shù)組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; } } // 獲取指定區(qū)間的隨機數(shù) 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; } })();
最后的效果
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
JavaScript鏈?zhǔn)秸{(diào)用原理與實現(xiàn)方法詳解
這篇文章主要介紹了JavaScript鏈?zhǔn)秸{(diào)用,結(jié)合實例形式詳細分析了JavaScript鏈?zhǔn)秸{(diào)用基本原理、實現(xiàn)方法與相關(guān)操作注意事項,需要的朋友可以參考下2020-05-05原生js實現(xiàn)手風(fēng)琴功能(支持橫縱向調(diào)用)
本文主要介紹了原生js實現(xiàn)手風(fēng)琴功能(支持橫縱向調(diào)用)的示例代碼。具有一定的參考價值,下面跟著小編一起來看下吧2017-01-01在JavaScript中獲取請求的URL參數(shù)[正則]
在ASP.NET后臺代碼中,對于這樣的URL請求地址:http://www.abc.com?id=001,我們可以通過Request.QueryString["id"]的方法很容易的獲取到URL中請求的參數(shù)的值,但是要在前臺js代碼中獲取請求的參數(shù)的值,應(yīng)該怎么做呢?2010-12-12JavaScript嚴格模式下關(guān)于this的幾種指向詳解
除了正常運行模式,ECMAscript 5添加了第二種運行模式:"嚴格模式"(strict mode)。下面這篇文章主要給大家介紹了在JavaScript嚴格模式下關(guān)于this的幾種指向的相關(guān)資料,需要的朋友可以參考借鑒,下面來一起看看吧。2017-07-07詳釋JavaScript執(zhí)行環(huán)境與執(zhí)行棧
一句話就可以概括:代碼 ( 包括函數(shù) ) 執(zhí)行時所需要的所有信息就是執(zhí)行環(huán)境。由于 ES 歷經(jīng)多個版本,所以執(zhí)行環(huán)境的標(biāo)準(zhǔn)也一直在變。文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04