Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ 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

Auto Save

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="board">
	<form id="game-board" @click.prevent="handleClick" :aria-label="`${howManyCorrect} of ${ratioSquared} tiles correctly placed.`">
		<transition-group
			name="slide"
			id="innerBoard"
			tag="div"
			:style="{gridTemplateColumns: `repeat(${ratio}, 1fr)`, gridTemplateColumns: `repeat(${ratio}, 1fr)`}"
		>
			<button 
				v-for="(square, index) in squares" 
				:key="square.val" @keyup.prevent="handleArrow"
				:index="index" :ref="!square.val && 'empty'" 
				:class="`square ${square.val -1 == index ? 'correct' : ''} ${square.isPossibleMove ? 'possible-move' : ''}`" 
				:aria-label="getAccessibleSquarePosition(square.val, index)"
			>
				<span v-if="square.val">{{square.val}}</span>
			</button>
		</transition-group>
		
		<transition name="fade">
			<div v-if="!gameStarted" class="loader">
				<p>
					Randomizing solvable puzzle
					<span class="dot">.</span><span class="dot">.</span><span class="dot">.</span>	
				</p>
			</div>
		</transition>
	</form>
	
	<p>Play with <span role="img" aria-label="mouse">🖱️</span>, <span role="img" aria-label="touch">👆</span>, or <span role="img" aria-label="keyboard arrow keys">⌨️ ⬆️ ➡️ ⬇️ ⬅️</span></p>
	
	<form id="options">
		<div class="options-group">
			<input v-model="invertSwipe" type="checkbox" id="invert-swipe">
			<label for="invert-swipe">Invert swipe directions</label>
		</div>
		<button @click.prevent="randomizeBoard">Re-Shuffle</button>
	</form>
</div>
	
              
            
!

CSS

              
                $breakpoint: 480px;

*, *:after, *:before {
	box-sizing: border-box;
}

:root {
	--dark: #53565a;
	--light: #a7a8aa;
	--highlight: #ffd100;
	--background: #7BA7BC;
	--transition: transform .15s;
	--ratio: 4;
	--maxBoardWidth: 80vmin;
	@media (min-width: $breakpoint){
		--maxBoardWidth: 55vmin;
	}
}

body {
	font-family: Nunito, sans-serif;
	min-height: 100vh;
	margin: 0;
	display: grid;
	place-items: center;
	color: var(--dark);
	background-color: var(--background);
	background: linear-gradient(-20deg, var(--highlight), var(--background) 60%);
}

form, button, input {
	font-family: Nunito, sans-serif;
	color: var(--dark);
	cursor: pointer;
}

#board {
	text-align: center;
	display: grid;
	place-items: center;
	position: relative;
	width: 100%;
	
	#game-board {
		width: var(--maxBoardWidth);
		height: var(--maxBoardWidth);
		border-radius: 6px;
		border: 1.5vmin solid var(--dark);
		background: var(--dark);
		color: var(--dark);
		cursor: pointer;
		display: flex;
		justify-content: center;
		position: relative;
		overflow: hidden;
		
		& + p {
			margin: 1em 0 0;
		}
	}
	
	& > p {
		font-size: 1.4rem;
	}
	
	& #options {
		width: var(--maxBoardWidth);
		display: flex;
		flex-wrap: wrap;
		align-items: center;
		justify-content: center;
		
		.options-group {
			width: 100%;
			padding-top: 1em;
			margin: 1em 0 0;
			border-top: 1px solid;
			
			input {
				transform: scale(1.5);
				margin-right: .5em;
			}
			
			label {
				vertical-align: middle;
			}
		}
		
		button {
			margin: 1em 0;
			padding: 2vmin 3vmin;
			font-size: 1rem;
			border-radius: 1vmin;
			border: .5vmin solid var(--light);
			text-transform: uppercase;
			outline-color: var(--highlight);
		}
	}
}

#innerBoard {
	display: grid;
	height: 100%;
	width: 100%;
	margin: 0 auto;
	overflow: hidden;
	
	.square {
		cursor: initial;
		padding: 0;
		font-size: calc(4.2vmin - (var(--ratio) * .1vmin));
		display: grid;
		text-align: center;
		place-items: center;
		border: none;
		background: #fff;
		position: relative;
		z-index: 1;
		
		@media (min-width: $breakpoint){
				font-size: calc(4vmin - (var(--ratio) * .2vmin));
		}
		
		span {
			transition: transform .1s;
			pointer-events: none!important; //Just being safe
		}
		
		&:focus {
			outline: none;
			
			& span {
				transform: scale(1.5);
			}
		}
		
		&.possible-move {
			cursor: pointer;
			background: lighten(#7ba7bc, 35%);
			
			&:hover span {
				transform: scale(1.3);
			}
		}
		
		&.correct {
			color: var(--highlight)!important;
		}
		
		&:empty {
			background: var(--dark);
			border-color: var(--dark);
			border: none;
			z-index: 0;
			
			&:focus {
				outline: none;
				border-radius: 8px;
				outline-offset: -1vmin;
				animation: swell .7s infinite alternate ease-in-out;
				
				&:before {
					width: 50%;
					height: 50%;
					content: '';
					background-color: var(--highlight);
					position: absolute;
					top: calc(50% - 25%);
					left: calc(50% - 25%);
					transform: rotate(45deg);
				}
				
				&:after {
					content: '';
					width: 45%;
					height: 45%;
					background-color: var(--dark);
					position: absolute;
					top: calc(50% - 22.5%);
					left: calc(50% - 22.5%);
					z-index: 3;
				}
			}
		}
	}
}

.loader {
	display: flex;
	align-items: center;
	position: absolute;
	text-align: left;
	top: -.5em;
	left: -.5em;
	width: calc(100% + 1em);
	height: calc(100% + 1em);
	color: #fff;
	background: var(--dark);
	opacity: .9;
	z-index: 10;
	text-transform: uppercase;
	
	& p {
		font-size: calc(.6em + 4vmin);
		padding: 0 1.5em;
	}
}

.fade-enter-active,
.fade-leave-active {
  transition: all .2s;
}

.fade-enter,
.fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
  opacity: 0;
	transform: translateY(.5em);
}

.dot {
	animation: pulse .6s infinite reverse;
	animation-delay: 0;
	
	&	+ .dot {
		animation-delay: .2s;
	}
	
	&:last-of-type {
		animation-delay: .4s;
	}
}

.slide-move {
	transition: var(--transition);
	filter: blur(.3vmin);
}

@keyframes swell {
	0% {
		transform: scale(1);
	}
	100% {
		transform: scale(1.15);
	}
}

@keyframes pulse {
	0% {
		opacity: 0;
	}
	100% {
		opacity: 1;
	}
}
              
            
!

JS

              
                // 👀 Change the "ratio" value below to alter the board size

const app = new Vue({
	el: '#board',
	
	data: () => ({
		ratio: 4, // 👈 A little buggy at some sizes; works best at 4, but ¯\_(ツ)_/¯
		squares: [],
		solution: [],
		illegalMoves: [],
		invertSwipe: false,
		gameStarted: false
	}),
	
	watch: {
		// Each time the squares change, update the list of legal moves
		squares(newSquares) {
			if (this.gameStarted) {
				// We need nextTick here or the board will render legal moves based on where the empty square *used to* be
				this.$nextTick(() => {
					const legalMoves = this.getLegalMoves();
					newSquares.forEach((square, index) => {
						newSquares[index].isPossibleMove = legalMoves.includes(index) ? true : false;
					});
				})
			}
		}
	},
	
	created() { // Generates a board, an answer, and a list of illegal moves based on this.ratio
		const max = this.ratioSquared;
		for(i=0; i < max; i++) {
			this.squares.push(i === (max -1) ? {val: '', isPossibleMove: false} : {val: i+1, isPossibleMove: false} );
			this.solution.push(i === (max -1) ? {val: '', isPossibleMove: false} : {val: i+1, isPossibleMove: false} );
			if (i % this.ratio == 0) {
				this.illegalMoves.push(i + (i-1));
			}
		}
	},
	
	mounted() { // Set styles for any board size properly and randomize it to start
		const squares = document.querySelectorAll('#innerBoard .square');
		
		// Set up swipe
		const innerBoard = document.getElementById('innerBoard');
		const touchBoard = new Hammer(innerBoard);
		
		touchBoard.get('swipe').set({
  		direction: Hammer.DIRECTION_ALL,
		});

		touchBoard.on('swipeup swipedown swipeleft swiperight', (e) => {
			this.handleClick(e);
		});
		
		// Set the ratio in CSS
		document.querySelector('.root').style.setProperty('--ratio', this.ratio);
		
		this.randomizeBoard();
	},
	
	
	computed: {
		randomMoveQty() {
			// The larger the board is, the more moves it will take to sufficiently randomize it
			return (this.ratio * 75);
		},
		
		// Returns how many squares are currently in the correct position
		howManyCorrect() {
			const correctlyPlacedSquares = this.squares.filter((square, index) => {
				return (Number(square.val) == Number(index + 1) || Number(index + 1) == this.ratioSquared && !square.val);
			});
			
			if (correctlyPlacedSquares.length === this.ratioSquared && this.gameStarted === true) {
				// Lets the last move resolve visually before ending the game
				setTimeout(() => { 
					alert('YOU WIN! Click the "re-shuffle" button to start a new game (or adjust the ratio to get crazy)!')
				}, 200);
			}
			
			return correctlyPlacedSquares.length;
		},
		
		ratioSquared() {
			return this.ratio * this.ratio;
		},
	},
	
	
	methods: {
		moveIsNotTheSameSquare(a, b) {
			return a != b; // Can't shuffle a square with itself
		},
		
		moveIsInBounds(a, b) {
			// Don't let the user try to move a square outside the board
			return (a >= 0 && b >= 0 && a < this.ratioSquared && b < this.ratioSquared);
		},
		
		moveIsAdjacentSquare(a, b) {
			// Squares are either next to each other or above/below each other
			return (a + b === 1 || a - b === 1 || b - a === 1) ||
			// …And we avoid the loophole where it LOOKS like the move is valid even though it's not because the two indexes are small enough they add up to the board size
			((a + b == this.ratio && a - b >= this.ratio ) || a - b == this.ratio || b - a == this.ratio)
		},
		
		moveIsNotCrossRowHorizontal(a, b) {
			// Eliminates "adjacent" values on separate rows, like 4 -> 5 on a 4 × 4 grid
			return ( (a - b === 1 || b - a === 1) && !this.illegalMoves.includes(a + b) ) || (a - b !== 1 && b - a !== 1)
		},
		
		// Does what it says on the tin; returns true if move is valid and false otherwise
		isValidMove(a, b) {
			a = Number(a);
			b = Number(b);
			
			if (
				this.moveIsNotTheSameSquare(a, b) && 
				this.moveIsInBounds(a, b) && 
				this.moveIsAdjacentSquare(a, b) && 
				this.moveIsNotCrossRowHorizontal(a, b)
			) {
				return true;	
			} 
			
			return false;
		},
		
		// Makes a bunch of random moves to shuffle the board
		// Necessary because it is possible to get an un-winnable board,
		// So we need to start with the correct board then shuffle it up randomly.
		randomizeBoard(e) {
			if (this.gameStarted && typeof e !== 'undefined') {
				const confirmation = confirm('Are you sure you want to shuffle? Your current game will be lost forever.')
				
				if (!confirmation) return
			}
			
			let randomized = this.randomMoveQty;
			let shuffleSpeed = 10; // Speed can be adjusted; bigger boards take longer.
			this.gameStarted = false;
			
			const randomMove = () => {
				if (randomized > 0) {
					const a = this.getEmptySquareIndex();			
					const b = this.generateRandomMove(a);
					
					if (!this.isValidMove(a, b)) {
						randomMove();
					} else {
						this.swap(a, b);
						randomized--;
						
						if (randomized > 0) {
							this.$nextTick(() => randomMove());
						} else {
							this.gameStarted = true;
							this.focusEmptySquare();
							// We don't want to transition while we're shuffling
							document.querySelector('.root').style.setProperty('--transition', 'transform .15s ease-out');
							return;
						}
					}
				}
			}
			
			setTimeout(() =>{
				randomMove();
			}, 100)
		},
		
		getLegalMoves() {
			const emptyIndex = this.getEmptySquareIndex();
			const possibleMoves = [emptyIndex - 1, emptyIndex + 1, emptyIndex - this.ratio, emptyIndex + this.ratio];
			const legalMoves = possibleMoves.filter(index => {
				return this.isValidMove(index, emptyIndex);
			});
			
			return legalMoves;
		},
		
		// Used to set HTML properties on move squares
		isPossibleMove(index) {
			return this.getLegalMoves().includes(index) ? 'possible-move' : '';
		},
		
		generateRandomMove(x) {
			x = Number(x);
			const move = Math.floor(Math.random() * this.ratio);
			if (move === 0) {
				return x - 1;
			} else if (move === 1) {
				return x + 1;
			} else if (move === 2) {
				return x - this.ratio;
			} else if (move === 3) {
				return x + this.ratio; 
				// Could just be a return instead of an else/if but this reads better I think 
			}
		},
		
		// Passes accessible info on tile position to the DOM
		getAccessibleSquarePosition(val, index) {
			let tileIdentifier = val ? `Tile ${val}` : `Empty tile`;
			return `${tileIdentifier} ${val -1 === index ? 'correctly placed' : ''} in position ${index + 1}: row ${Math.floor(index / this.ratio) +1}, column ${index % this.ratio +1}`
		},
		
		focusEmptySquare() {
			 this.$nextTick(() => this.$refs.empty[0].focus());
		},
		
		getEmptySquareIndex() {
			return this.$refs.empty ? Number(this.$refs.empty[0].getAttribute('index')) : this.ratioSquared -1;
		},
		
		// Specifically handles keyboard events
		handleArrow(e) {
			const emptyIndex = this.getEmptySquareIndex();
			let clickedIndex;
			if (e.which === 37) {
				clickedIndex = emptyIndex - 1;
			} else if (e.which === 38) {
				clickedIndex = emptyIndex - this.ratio;
			} else if (e.which === 39) {
				clickedIndex = emptyIndex + 1;
			} else if (e.which === 40) {
				clickedIndex = emptyIndex + this.ratio;
			} else {
				return; // Don't do anything if the key wasn't an arrow key
			}
			
			if (this.isValidMove(emptyIndex, clickedIndex)) {
				this.swap(emptyIndex, clickedIndex);	
				this.gameStarted && this.focusEmptySquare();
			}
		},
		
		// Specifically handles clicks and swipes
		handleClick(e) {
			// Get the empty square and the clicked square, then both of their index values
			const emptyIndex = this.getEmptySquareIndex();
			const wasSwipe = (e.type && e.type.includes('swipe'));
			let clicked;
			let clickedIndex;
			
			if (wasSwipe) {
				if (e.type === 'swiperight') {
					clickedIndex = this.invertSwipe ? emptyIndex + 1 : emptyIndex - 1;
				} else if (e.type === 'swipeleft') {
					clickedIndex = this.invertSwipe ? emptyIndex - 1 : emptyIndex + 1;
				} else if (e.type === 'swipeup') {
					clickedIndex = this.invertSwipe ? emptyIndex - this.ratio : emptyIndex + this.ratio;
				} else if (e.type === 'swipedown') {
					clickedIndex = this.invertSwipe ? emptyIndex + this.ratio : emptyIndex - this.ratio;
				}
			} else {
				clicked = e.target;
				clickedIndex = Number(clicked.getAttribute('index'));
			}
			
			if (!(emptyIndex || clickedIndex)) {
				return; // If we don't have a valid index value for both the empty square and the clicked square, exit early
			}

			// Check if the clicked move is valid
			if (this.isValidMove(emptyIndex, clickedIndex)) {
				// Shuffle the two squares if it's a valid move
				this.swap(emptyIndex, clickedIndex);
				// Focus the empty square if it was a click or keyboard move
				this.gameStarted && !wasSwipe && this.focusEmptySquare();
			} else {
				return; // If it's not a valid move, do nothing
			}
		},
		
		// The big magic method that actually swaps two squares when a move is made
		swap(clickedIndex, emptyIndex) {
				const a = this.squares[clickedIndex];
				const b = this.squares[emptyIndex];
				this.$set(this.squares, clickedIndex, b);
				this.$set(this.squares, emptyIndex, a);
		}
	}
});
              
            
!
999px

Console