JavaScript: Gem Puzzle

Last update: 22 Jan 23:20
0
Students

15 puzzle or gem puzzle is a popular game invented in 1878 by Noah Chapman. It is a set of identical numbered square tiles, enclosed in a square box. The side length of the box is four times the side length of the tiles for a set of 15 elements, while one square field remains empty. The game goal is to arrange tiles by numbers by moving them around the box, preferably by making as few movements as possible.

application.js

Implement the game according to the following requirements:

  • The frame size should be 4x4
  • The lower right square is always empty in the initial game state
  • Elements are arranged randomly according to the following algorithm: first they are shuffled using randomize(values), and then they fill the table
  • The values should be ordered in the table from top to bottom, that is, in this way:

    1 5 9 13
    2 6 10 14
    ---- ---- ---- ----
    3 7 11 15
    ---- ---- ---- ----
    4 8 12

The tiles are moved using the arrows: when you press , the left tile will move to the right to an empty area.

Since the tests are tied to the layout implementation (Bootstrap) we have a special requirement for it. Here's what the initial state looks like:

<div class="gem-puzzle">
    <table class="table-bordered">
        <tbody>
            <tr>
                <td class="p-3">10</td>
                <td class="p-3">11</td>
                <td class="p-3">6</td>
                <td class="p-3">4</td>
            </tr>
            <tr>
                <td class="p-3">14</td>
                <td class="p-3">2</td>
                <td class="p-3">12</td>
                <td class="p-3">1</td>
            </tr>
            <tr>
                <td class="p-3">3</td>
                <td class="p-3">13</td>
                <td class="p-3">9</td>
                <td class="p-3">8</td>
            </tr>
            <tr>
                <td class="p-3">5</td>
                <td class="p-3">7</td>
                <td class="p-3">15</td>
                <td class="p-3 table-active"></td>
            </tr>
        </tbody>
    </table>
</div>
  • The table class is constant
  • Each cell has a p-3 class
  • An empty cell contains no text
  • The table-active class is added to an empty cell

init position

Tips

  • Key press event generates a code indicating which key has been pressed
  • You can check the codes for the arrows in the tests
  • To get a pressed key from an event, use the key property from the event object
  • Use the keyup event

For full access to the challenge you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests