├── src ├── constants.js ├── index.js ├── App.js ├── index.css ├── Tile.js ├── Board.js └── helpers.js ├── public └── index.html ├── .gitignore ├── package.json ├── LICENSE └── README.md /src/constants.js: -------------------------------------------------------------------------------- 1 | export const TILE_COUNT = 16; 2 | export const GRID_SIZE = 4; 3 | export const BOARD_SIZE = 320; -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import ReactDOM from "react-dom"; 3 | import "./index.css"; 4 | import App from "./App"; 5 | 6 | ReactDOM.render( 7 | 8 | 9 | , 10 | document.getElementById("root") 11 | ); 12 | -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | React Sliding Puzzle 7 | 8 | 9 | 10 |
11 | 12 | 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /src/App.js: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect } from "react"; 2 | import Board from "./Board"; 3 | import { updateURLParameter } from "./helpers" 4 | 5 | function App() { 6 | const [imgUrl, setImgUrl] = useState("") 7 | 8 | useEffect(() => { 9 | const urlParams = new URLSearchParams(window.location.search) 10 | if (urlParams.has("img")) { 11 | setImgUrl(urlParams.get("img")) 12 | } 13 | }, []) 14 | 15 | const handleImageChange = (e) => { 16 | setImgUrl(e.target.value) 17 | window.history.replaceState("", "", updateURLParameter(window.location.href, "img", e.target.value)) 18 | } 19 | 20 | return ( 21 |
22 |

React sliding puzzle

23 | 24 | 25 |
26 | ); 27 | } 28 | 29 | export default App; 30 | -------------------------------------------------------------------------------- /src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", 4 | "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | min-height: 100vh; 9 | background: #111; 10 | color: white; 11 | } 12 | 13 | code { 14 | font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", 15 | monospace; 16 | } 17 | .App { 18 | display: grid; 19 | place-items: center; 20 | height: 100vh; 21 | } 22 | h1 { 23 | margin: 0; 24 | } 25 | .board { 26 | position: relative; 27 | padding: 0; 28 | } 29 | .tile { 30 | position: absolute; 31 | list-style: none; 32 | background: #ec6f66; 33 | display: grid; 34 | place-items: center; 35 | font-size: 20px; 36 | } 37 | button { 38 | display: block; 39 | } 40 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-sliding-puzzle", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@testing-library/jest-dom": "^4.2.4", 7 | "@testing-library/react": "^9.3.2", 8 | "@testing-library/user-event": "^7.1.2", 9 | "react": "^16.13.1", 10 | "react-dom": "^16.13.1", 11 | "react-motion": "^0.5.2", 12 | "react-scripts": "3.4.3" 13 | }, 14 | "scripts": { 15 | "start": "react-scripts start", 16 | "build": "react-scripts build", 17 | "test": "react-scripts test", 18 | "eject": "react-scripts eject" 19 | }, 20 | "eslintConfig": { 21 | "extends": "react-app" 22 | }, 23 | "browserslist": { 24 | "production": [ 25 | ">0.2%", 26 | "not dead", 27 | "not op_mini all" 28 | ], 29 | "development": [ 30 | "last 1 chrome version", 31 | "last 1 firefox version", 32 | "last 1 safari version" 33 | ] 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | This is free and unencumbered software released into the public domain. 2 | 3 | Anyone is free to copy, modify, publish, use, compile, sell, or 4 | distribute this software, either in source code form or as a compiled 5 | binary, for any purpose, commercial or non-commercial, and by any 6 | means. 7 | 8 | In jurisdictions that recognize copyright laws, the author or authors 9 | of this software dedicate any and all copyright interest in the 10 | software to the public domain. We make this dedication for the benefit 11 | of the public at large and to the detriment of our heirs and 12 | successors. We intend this dedication to be an overt act of 13 | relinquishment in perpetuity of all present and future rights to this 14 | software under copyright law. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 19 | IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR 20 | OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 21 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 22 | OTHER DEALINGS IN THE SOFTWARE. 23 | 24 | For more information, please refer to 25 | -------------------------------------------------------------------------------- /src/Tile.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { Motion, spring } from "react-motion"; 3 | import { getMatrixPosition, getVisualPosition } from "./helpers"; 4 | import { TILE_COUNT, GRID_SIZE, BOARD_SIZE } from "./constants" 5 | 6 | function Tile(props) { 7 | const { tile, index, width, height, handleTileClick, imgUrl } = props; 8 | console.log("img in tile", imgUrl) 9 | const { row, col } = getMatrixPosition(index); 10 | const visualPos = getVisualPosition(row, col, width, height); 11 | const tileStyle = { 12 | width: `calc(100% / ${GRID_SIZE})`, 13 | height: `calc(100% / ${GRID_SIZE})`, 14 | translateX: visualPos.x, 15 | translateY: visualPos.y, 16 | backgroundImage: `url(${imgUrl})`, 17 | backgroundSize: `${BOARD_SIZE}px`, 18 | backgroundPosition: `${(100 / (GRID_SIZE - 1)) * (tile % GRID_SIZE)}% ${(100 / (GRID_SIZE - 1)) * (Math.floor(tile / GRID_SIZE))}%`, 19 | 20 | }; 21 | const motionStyle = { 22 | translateX: spring(visualPos.x), 23 | translateY: spring(visualPos.y) 24 | } 25 | 26 | return ( 27 | 28 | {({ translateX, translateY }) => ( 29 |
  • handleTileClick(index)} 38 | > 39 | {!imgUrl && `${tile + 1}`} 40 |
  • 41 | )} 42 |
    43 | ); 44 | } 45 | 46 | export default Tile; 47 | -------------------------------------------------------------------------------- /src/Board.js: -------------------------------------------------------------------------------- 1 | import React, { useState } from "react"; 2 | import Tile from "./Tile"; 3 | import { TILE_COUNT, GRID_SIZE, BOARD_SIZE } from "./constants" 4 | import { canSwap, shuffle, swap, isSolved } from "./helpers" 5 | 6 | function Board({ imgUrl }) { 7 | const [tiles, setTiles] = useState([...Array(TILE_COUNT).keys()]); 8 | const [isStarted, setIsStarted] = useState(false); 9 | console.log('is started:', isStarted) 10 | 11 | const shuffleTiles = () => { 12 | const shuffledTiles = shuffle(tiles) 13 | setTiles(shuffledTiles); 14 | } 15 | 16 | const swapTiles = (tileIndex) => { 17 | if (canSwap(tileIndex, tiles.indexOf(tiles.length - 1))) { 18 | const swappedTiles = swap(tiles, tileIndex, tiles.indexOf(tiles.length - 1)) 19 | setTiles(swappedTiles) 20 | } 21 | } 22 | 23 | const handleTileClick = (index) => { 24 | swapTiles(index) 25 | } 26 | 27 | const handleShuffleClick = () => { 28 | shuffleTiles() 29 | } 30 | 31 | const handleStartClick = () => { 32 | shuffleTiles() 33 | setIsStarted(true) 34 | } 35 | 36 | const pieceWidth = Math.round(BOARD_SIZE / GRID_SIZE); 37 | const pieceHeight = Math.round(BOARD_SIZE / GRID_SIZE); 38 | const style = { 39 | width: BOARD_SIZE, 40 | height: BOARD_SIZE, 41 | }; 42 | const hasWon = isSolved(tiles) 43 | 44 | return ( 45 | <> 46 | 59 | {hasWon && isStarted &&
    Puzzle solved 🧠 🎉
    } 60 | {!isStarted ? 61 | () : 62 | ()} 63 | 64 | ); 65 | } 66 | 67 | export default Board; 68 | -------------------------------------------------------------------------------- /src/helpers.js: -------------------------------------------------------------------------------- 1 | import { TILE_COUNT, GRID_SIZE } from "./constants" 2 | 3 | // Credits to https://codepen.io/unindented/pen/QNWdRQ 4 | export function isSolvable(tiles) { 5 | let product = 1; 6 | for (let i = 1, l = TILE_COUNT - 1; i <= l; i++) { 7 | for (let j = i + 1, m = l + 1; j <= m; j++) { 8 | product *= (tiles[i - 1] - tiles[j - 1]) / (i - j); 9 | } 10 | } 11 | return Math.round(product) === 1; 12 | } 13 | 14 | export function isSolved(tiles) { 15 | for (let i = 0, l = tiles.length; i < l; i++) { 16 | if (tiles[i] !== i) { 17 | return false; 18 | } 19 | } 20 | return true; 21 | } 22 | 23 | // Get the linear index from a row/col pair. 24 | export function getIndex(row, col) { 25 | return parseInt(row, 10) * GRID_SIZE + parseInt(col, 10); 26 | } 27 | 28 | // Get the row/col pair from a linear index. 29 | export function getMatrixPosition(index) { 30 | return { 31 | row: Math.floor(index / GRID_SIZE), 32 | col: index % GRID_SIZE, 33 | }; 34 | } 35 | 36 | export function getVisualPosition(row, col, width, height) { 37 | return { 38 | x: col * width, 39 | y: row * height, 40 | }; 41 | } 42 | 43 | export function shuffle(tiles) { 44 | const shuffledTiles = [ 45 | ...tiles 46 | .filter((t) => t !== tiles.length - 1) 47 | .sort(() => Math.random() - 0.5), 48 | tiles.length - 1, 49 | ]; 50 | return isSolvable(shuffledTiles) && !isSolved(shuffledTiles) 51 | ? shuffledTiles 52 | : shuffle(shuffledTiles); 53 | } 54 | 55 | export function canSwap(srcIndex, destIndex) { 56 | const { row: srcRow, col: srcCol } = getMatrixPosition(srcIndex); 57 | const { row: destRow, col: destCol } = getMatrixPosition(destIndex); 58 | return Math.abs(srcRow - destRow) + Math.abs(srcCol - destCol) === 1; 59 | } 60 | 61 | export function swap(tiles, src, dest) { 62 | const tilesResult = [...tiles]; 63 | [tilesResult[src], tilesResult[dest]] = [tilesResult[dest], tilesResult[src]]; 64 | return tilesResult; 65 | } 66 | 67 | export function updateURLParameter(url, param, paramVal) { 68 | var newAdditionalURL = ""; 69 | var tempArray = url.split("?"); 70 | var baseURL = tempArray[0]; 71 | var additionalURL = tempArray[1]; 72 | var temp = ""; 73 | if (additionalURL) { 74 | tempArray = additionalURL.split("&"); 75 | for (var i = 0; i < tempArray.length; i++) { 76 | if (tempArray[i].split("=")[0] !== param) { 77 | newAdditionalURL += temp + tempArray[i]; 78 | temp = "&"; 79 | } 80 | } 81 | } 82 | 83 | var rows_txt = temp + "" + param + "=" + paramVal; 84 | return baseURL + "?" + newAdditionalURL + rows_txt; 85 | } 86 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 2 | 3 | ## Available Scripts 4 | 5 | In the project directory, you can run: 6 | 7 | ### `yarn start` 8 | 9 | Runs the app in the development mode.
    10 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 11 | 12 | The page will reload if you make edits.
    13 | You will also see any lint errors in the console. 14 | 15 | ### `yarn test` 16 | 17 | Launches the test runner in the interactive watch mode.
    18 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 19 | 20 | ### `yarn build` 21 | 22 | Builds the app for production to the `build` folder.
    23 | It correctly bundles React in production mode and optimizes the build for the best performance. 24 | 25 | The build is minified and the filenames include the hashes.
    26 | Your app is ready to be deployed! 27 | 28 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 29 | 30 | ### `yarn eject` 31 | 32 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 33 | 34 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 35 | 36 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 37 | 38 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 39 | 40 | ## Learn More 41 | 42 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 43 | 44 | To learn React, check out the [React documentation](https://reactjs.org/). 45 | 46 | ### Code Splitting 47 | 48 | This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting 49 | 50 | ### Analyzing the Bundle Size 51 | 52 | This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size 53 | 54 | ### Making a Progressive Web App 55 | 56 | This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app 57 | 58 | ### Advanced Configuration 59 | 60 | This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration 61 | 62 | ### Deployment 63 | 64 | This section has moved here: https://facebook.github.io/create-react-app/docs/deployment 65 | 66 | ### `yarn build` fails to minify 67 | 68 | This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify 69 | --------------------------------------------------------------------------------