Verification of sliding puzzle functionality in JavaScript

I have successfully created a sliding puzzle with various formats, including 3x3, 3x4, 4x3, and 4x4. When you run my code, you will notice a selection box on the right side where you can choose from these four formats. The sliding puzzle is almost complete. However, I am in need of a function that can check after each move if the puzzle has been solved. If it has, I would like it to display a message such as "Congratulations! You solved it!" or "You won!". Do you have any ideas on how I can implement this feature?

In the javascript code, you will see that the first function, loadFunc(), is used to replace every piece with a blank one. The subsequent functions are responsible for selecting and changing the format, shifting puzzle pieces into the blank space, and shuffling the pieces' positions randomly. If you have any questions or encounter any difficulties understanding the code, please feel free to ask in the comments. Thank you in advance.

As my reputation is limited, I will provide a link to the images here: https://i.sstatic.net/9fIyk.jpg. These images are currently being used as placeholders.

Here is the jsfiddle:

    http://jsfiddle.net/Cuttingtheaces/vkyxgwo6/19/

Answer №1

There are always two ways to achieve a goal: the quick and dirty method, or the more elegant but complex approach that requires significant code changes.

Quick Method

To quickly check if pieces are in the correct order, you can parse the "id"s of each piece based on their expected positions. This can be done by looking for the pattern "position" + index or "blank":

function isFinished() {
    var puzzleEl = document.getElementById('slidingpuzzleContainer').children[0];
    var pieces = [].slice.call(puzzleEl.children);

    return pieces
        .map(function (piece) {
            return piece.id.substr(8);
        })
        .every(function (id, index, arr) {
            if (arr.length - 1 == index) {
                return id == "blank";
            }
            return index == parseInt(id);
        });
}

You can then call the isFinished() function after each move in your game to display a finishing message if all pieces are in order:

function shiftPuzzlepieces(el) {
    // ...
    if (isFinished()) {
        alert("You won!");
    }
}

A live version of this method can be found here.

Elegant Approach

In my opinion, a better way to implement this game would be to track the current positions of pieces using a data structure instead of parsing DOM elements. This allows for easier manipulation of the game state, similar to how a React.js application works: updating the game state onclick and rendering it into the DOM.

Here's how I would implement the game:

The main advantage of this approach is its flexibility: functions such as finding blank spaces around pieces can be modified without affecting other parts of the code. This separation of concerns makes the code more maintainable and extensible.

Answer №2

    $(document).on('click','.puzzlepiece', function(){
        var count = 0;
         var imgarray = []; 
        var test =[0,1,2,3,4,5,6,7,8,'blank']
        $('#slidingpuzzleContainer img').each(function(i){
          var imgalt =  $(this).attr('alt');             
            imgarray[i] = imgalt;            
            count++;

        });
        var is_same = (imgarray.length == test.length) &&   imgarray.every(function(element, index) {
        return element === array2[index]; 
    });

        console.log(is_same);    ///it will true if two array is same           
    });

Give this a try... specifically designed for 3x3 puzzles with dynamic value assignment.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

repeated execution of a javascript function

I have created a tag picker that generates checkbox inputs based on the "group" selected. After selecting the desired tags and pressing the done button, it should return a string to set the value of a text input. Below are some related code snippets. The ...

Stop the submission of a form using jQuery based on its unique identifier

When using the jQuery Ajax function to verify if a user email exists in the database during a jQuery change event, there are two possible outcomes in the Ajax response. If the user email does exist, an error message is displayed. In this scenario, I aim ...

Displaying grid in object in threejs: a tutorial

I currently have a horizontal grid Helper and polygon within my scene. Is there a way to hide the grid outside of the polygon, similar to the image below? https://i.sstatic.net/pQ40h.png Here is the JSFiddle var camera, scene, renderer, controls, geo ...

What is the best way to showcase my subscription form on a web browser?

I am encountering an issue with my code. My goal is to generate a subscribe form modal. Although I have incorporated the subscribe form in my HTML document, upon running the code in the browser, the subscribe section is not visible. Can anyone offer assist ...

Enhancing interactivity with jQuery's ajax event functionality

Alright, let me share my code with you: $("#content_Div").ajaxStart(function () { $(this).css('cursor', 'wait') }).ajaxComplete(function () { $(this).css('cursor', 'default') }); I'm facing a simple is ...

Refreshing the Parent Component in a React Application

I'm currently delving into the world of React and TypeScript, exploring how to create a login form. Once I verify the user's details and set a cookie, I aim to refresh the parent component. This is my index.tsx (condensed version): import React ...

Utilizing AJAX in jQuery Mobile for Collapsible Content

I am currently generating a variable number of these elements using a foreach() loop: <div id="<?php echo $data['id']; ?>" data-role="collapsible" data-theme="a"> <h1 style="white-space: normal"><?php echo $data['te ...

Can an array in html be accessed using a scope variable?

I am facing a challenge with utilizing a Json array in my template file. To access specific elements of the array, I need to use a scope variable. While I can achieve this in the controller, I also require the same functionality in the HTML file. An excer ...

How to address critical vulnerabilities found in a Vue.js project that relies on the 'vue-svg-loader' dependency, specifically impacting 'nth-check', 'css-select', and 'svgo'?

Attempting to launch a Vue version 2 project, encountered the following error: # npm audit report nth-check <2.0.1 Severity: high Inefficient Regular Expression Complexity in nth-check - https://github.com/advisories/GHSA-rp65-9cf3-cjxr fix available ...

typescript scrolling location

In my Angular UI code, I have a component class that includes the following structure: app.component.html //... <div class="banner"> <p-dialog [(visible)]="displayCOI" styleClass="coiDialog" [contentStyle]=" ...

The `stream.Transform.unshift()` method in Node.js

Let's take a look at this simple example: stream = require 'stream' util = require 'util' class TestTransform extends stream.Transform _transform: (chunk, encoding, callback) -> if not @noMore @noMore ...

Send the form data to a PHP file for processing

I have a form set up where a user can input data and click submit, triggering a PHP file to execute. Below is the form itself along with the corresponding PHP file. <form action="php_scripts/test.php" method="POST"> <input name="feature" ...

Mastering state management for various input types in React

Developing a proof of concept for showcasing tennis player details on a webpage. The page can display information for any number of players, and the user should be able to update all player details simultaneously. I have created 3 components: PlayersPage, ...

Building an HTTP request and response directly from an active socket in a Node.js environment

My current project involves passing HTTP requests to a child process in Node.js. I am struggling with passing the active Socket using child.send('socket', req.socket). Once inside the child process, I need to recreate the HTTP request and respons ...

Tips for Creating an Animated Progress Bar in a Slider

After implementing jQuery, I managed to create a unique slider on my website. This slider included a thumbnail with captions for each photo. Positioned below the thumbnail was a progress bar fixed in the center between the caption and the image. Users can ...

The NgFor is unable to iterate over an array because it is being treated as an

When attempting to call a new endpoint for displaying data, I noticed that the previous set of data is wrapped with an extra pair of brackets '[]', which seems to be causing a problem. The new endpoint does not format the data in this way when I ...

Toggle the font weight in a text area by clicking a button

I need help with creating a button that will change the font-weight to bold when clicked and then revert back to normal when un-clicked. However, I only want the specific part of the text area where the user clicks the button to be bolded, not the entire t ...

Transmitting PHP variable to JavaScript using Callback Method

I am looking to implement password validation using JavaScript along with an Ajax function. Upon successful validation, I aim to return a boolean variable (true or false) and perform specific actions in my PHP file based on the callback. Unfortunately, my ...

Ways to effortlessly activate an angular directive once the page has been fully loaded

I am facing an issue with a print directive that is triggered by the print="id" attribute within an <a></a> element. The button is contained in a modal that remains hidden from the user. I want the directive to execute as soon as the modal is l ...

The intricacies of CSS flexbox's breaking tendencies

I am trying to create a 'responsive' box with a fixed width that contains a logo and an infobar. The infobar should take up the remaining space in the box, calculated using calc(). To ensure the infobar is still usable, I have set a min-width for ...