Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div id="game-wrapper">
    <h1 class="title">ReactJS Slide Puzzle</h1>
    <div id="game-container"></div>
</div>
              
            
!

CSS

              
                #game-wrapper {
    margin: 40px auto;
    width: 500px;
    text-align: center;
    font-family: Consolas, Monaco, 'Andale Mono', monospace;
}

#game-board, #game-board * {
    box-sizing: border-box;
}

#game-board {
    display: inline-block;
    width: 304px;
    height: 304px;
    padding: 0;
    margin: 0;
    border: 2px solid black;
}

.tile,
.button {
    // get rid of highlighting
    user-select: none;
    -webkit-touch-callout: none;
}

.tile {
    width: 100px;
    height: 100px;
    float: left;
    line-height: 100px;
    font-size: 50px;
    background: #fff;
    &:hover:not(:empty) {
        cursor: pointer;
        transition: transform 0.2s, background 0.2s;
        background: #eee;
    }
}

.win {
    animation: winner 2s infinite;
}

.highlight,
.move-up,
.move-right,
.move-down,
.move-left {
    background: #fdd !important;
}

.highlight {
    background: #fff;
    // animation time horribly linked to JavaScript setTimeout
    animation: highlight 0.4s;
}

.move-up {
    transform: translateY(-100px);
}
.move-right {
    transform: translateX(100px);
}
.move-down {
    transform: translateY(100px);
}
.move-left {
    transform: translateX(-100px);
}

.button {
    display: inline-block;
    padding: 4px 10px;
    color: black;
    border: 2px solid black;
    &:hover { cursor: pointer; }
}

@keyframes winner {
    0%   { background: #fdd; }
    50%  { background: #fff; }
    100% { background: #fdd; }
}

@keyframes highlight {
    0%   { background: #fdd; }
    100% { background: #fff; }
}
              
            
!

JS

              
                // ReactJS Slide Puzzle
// Author:     Evan Henley
// Author URI: henleyedition.com

(function() {

    var Game = React.createClass({displayName: 'Game',

        shuffle: function(array) {

            // switches first two tiles
            function switchTiles(array) {
                var i = 0;

                // find the first two tiles in a row
                while (!array[i] || !array[i+1]) i++;

                // store tile value
                var tile = array[i];
                // switche values
                array[i] = array[i+1];
                array[i+1] = tile;

                return array;
            }

            // counts inversions
            function countInversions(array) {
                // make array of inversions
                var invArray = array.map(function(num, i) {
                    var inversions = 0;
                    for (j = i + 1; j < array.length; j++) {
                        if (array[j] && array[j] < num) {
                            inversions += 1;
                        }
                    }
                    return inversions;
                });
                // return sum of inversions array
                return invArray.reduce(function(a, b) {
                    return a + b;
                });
            }

            // fischer-yates shuffle algorithm
            function fischerYates(array) {
                var counter = array.length, temp, index;

                // While there are elements in the array
                while (counter > 0) {
                    // Pick a random index
                    index = Math.floor(Math.random() * counter);
                    // Decrease counter by 1
                    counter--;
                    // And swap the last element with it
                    temp = array[counter];
                    array[counter] = array[index];
                    array[index] = temp;
                }

                return array;
            }

            // Fischer-Yates shuffle
            array = fischerYates(array);

            // check for even number of inversions
            if (countInversions(array) % 2 !== 0) {
                // switch two tiles if odd
                array = switchTiles(array);
            }

            return array;
        },
        getInitialState: function() {
            return {
                // initial state of game board
                tiles: this.shuffle([
                    1,2,3,
                    4,5,6,
                    7,8,''
                ]),
                win: false
            };
        },
        checkBoard: function() {
            var tiles = this.state.tiles;

            for (var i = 0; i < tiles.length-1; i++) {
                if (tiles[i] !== i+1) return false;
            }

            return true;
        },
        tileClick: function(tileEl, position, status) {
            var tiles = this.state.tiles;
            // Possible moves
            // [up,right,down,left]
            // 9 = out of bounds
            var moves = [
                [null,1,3,null],[null,2,4,0],[null,null,5,1],
                [0,4,6,null],   [1,5,7,3],   [2,null,8,4],
                [3,7,null,null],[4,8,null,6],[5,null,null,7]
            ];

            function animateTiles(i, move) {
                var directions = ['up','right','down','left'];
                var moveToEl = document.querySelector('.tile:nth-child(' + (move + 1) + ')');
                direction = directions[i];
                tileEl.classList.add('move-' + direction);
                // this is all a little hackish.
                // css/js are used together to create the illusion of moving blocks
                setTimeout(function() {
                    moveToEl.classList.add('highlight');
                    tileEl.classList.remove('move-' + direction);
                    // time horribly linked with css transition
                    setTimeout(function() {
                        moveToEl.classList.remove('highlight');
                    }, 400);
                }, 200);
            }

            // called after tile is fully moved
            // sets new state
            function afterAnimate() {
                tiles[position] = '';
                tiles[move] = status;
                this.setState({
                    tiles: tiles,
                    moves: moves,
                    win: this.checkBoard()
                });
            };

            // return if they've already won
            if (this.state.win) return;

            // check possible moves
            for (var i = 0; i < moves[position].length; i++) {
                var move = moves[position][i];
                // if an adjacent tile is empty
                if (typeof move === 'number' && !tiles[move]) {
                    animateTiles(i, move);
                    setTimeout(afterAnimate.bind(this), 200);
                    break;
                }
            }
        },
        restartGame: function() {
            this.setState(this.getInitialState());
        },
        render: function() {
            return React.DOM.div(null, 
                React.DOM.div({id: "game-board"}, 
                    this.state.tiles.map(function(tile, position) {
                        return ( Tile({status: tile, key: position, tileClick: this.tileClick}) );
                    }, this)
                ), 
                Menu({winClass: this.state.win ? 'button win' : 'button', status: this.state.win ? 'You win!' : 'Solve the puzzle.', restart: this.restartGame})
            );
        }
    });

    var Tile = React.createClass({displayName: 'Tile',
        clickHandler: function(e) {
            this.props.tileClick(e.target, this.props.key, this.props.status);
        },
        render: function() {
            return React.DOM.div({className: "tile", onClick: this.clickHandler}, this.props.status);
        }
    });

    var Menu = React.createClass({displayName: 'Menu',
        clickHandler: function() {
            this.props.restart();
        },
        render: function() {
            return React.DOM.div({id: "menu"}, 
                React.DOM.h3({id: "subtitle"}, this.props.status), 
                React.DOM.a({className: this.props.winClass, onClick: this.clickHandler}, "Restart")
            );
        }
    });

    // render Game to container
    React.renderComponent(
        Game(null),
        document.getElementById('game-container')
    );

}());
              
            
!
999px

Console