Building Sliding Puzzle in Vanilla Javascript
This will be exciting to build.
Demo: https://sliding-puzzle-basic.netlify.app/
Prerequisites
- Bootstrap
- Javascript
- CSS/SASS
Introduction
Step 1:
Let’s create index.html file , in there we will add font family -> Poppins, bootstrap (version 4 you can use whatever is the latest).
Step 2:
Let’s create a Modal for Instructions and add it.
Step 3:
We will add the major buttons,
- Difficulty — We will dropdown to choose form Easy, medium , and Difficult
- Start — the trigger to initiate the game
- Reset Time — the trigger to reset the timer
- Shuffle — the trigger to shuffle up all the tiles
- Reset Tile — this trigger will reset all tiles to initial position
Step 4:
Finish — this trigger will calculate the game result and reset the game
Step 5:
Let us now add all the tiles with their ids (1,2,3,4,…) and the move function (which we will build later).
This is how complete index.html should look like
Styling
Feel free to change this styling. I did in the way I liked it.
Implementing Functions
— Let just create initial variables.
— After this we will initiate exchangeable function where in based on their index position we will hard code where these tiles can go from here.
— Even if there is possibility for tile one to reach position 2 and 4 it can only move if that position in empty. For that check we will create the function isThere.
— Using the above function to verify if the tile can be moved to the position or not, we exchange the tiles in this function move.
— Remember user selects difficulty in the dropdown, now we have to assign a value in JS using select_difficulty. rand function is where we generate random value between 1 and 16. shuffle has different cases based on difficulty 1, 2, 3 in which based on number of iteration we move the tiles randomly.
— All timer functions
— startTimer — When user clicks it the interval created and timer is started with unpausing, shuffling and displaying the timer
— resetTimer — We clear interval, pause and being them all to default
— getShowTime — In here this function takes care of displaying the timer or not
— correctPos —This function determines either at the end of timer or when user clicks ‘finish’ the tiles are in correct position or not.
— resultModal — This function triggers the correctPos to determine the result message and display it in a modal when the timer completes 60 seconds.
— resultModal _before— This function triggers the correctPos to determine the result message and display it in a modal when the user clicks on finish button.
— Finish_task — This function triggers resetTimer and calls resultModal _before.
Complete JS code
Feel free to check out the code if you missed any of the point above
Conclusion
Thanks… Bye Bye