Pen Settings

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

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

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

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

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.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <div id="board">
	<p id="counter">
		<span id="progress-bar" :style="{width: howManyCorrect / ratioSquared * 100 + '%'}"></span>
		<strong>{{howManyCorrect}} / {{ratioSquared}}</strong>
	</p>
	<form @click="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 🖱️, 👆, or ⌨️ ⬆️ ➡️ ⬇️ ⬅️</p>
	<div 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="randomizeBoard">Re-Shuffle</button>
	</div>
</div>
	
            
          
!
            
              $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%;
	#counter {
		font-size: 1.5em;
		width: var(--maxBoardWidth);
		background: rgba(0,0,0,.1);
		position: relative;
		line-height: 1.6;
		border-radius: 5vmin;
		overflow: hidden;
		#progress-bar {
			width: 46%;
			height: 100%;
			content: '';
			background: var(--highlight);
			position: absolute;
			left: 0;
			top: 0;
			z-index: 0;
			transition: width .4s ease-in-out;
		}
		strong {
			position: relative;
			z-index: 2;
		}
	}
	form {
		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;
	}
}
            
          
!
            
              // 👀Change the "ratio" value below to alter the board size

const app = new Vue({
	el: '#board',
	data(){
		return {
			ratio: 4, //👈 A little buggy at some sizes; works best at 4, but ¯\_(ツ)_/¯
			squares: [],
			solution: [],
			illegalMoves: [],
			invertSwipe: false,
			gameStarted: false
		}
	},
	watch: {
		squares: function(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: function(){ //Generate a board, an answer, and a list of illegal moves based on this.ratio
		const max = this.ratio * this.ratio;
		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: function(){ //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(){
			return (this.ratio * 75);
		},
		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){
				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.ratio * this.ratio && b < this.ratio * this.ratio);
		},
		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)
		},
		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;	
			} else {
				return false;
			}
		},
		randomizeBoard(){
			let randomized = this.randomMoveQty;
			let shuffleSpeed = 10;
			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();
							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;
		},
		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;
			}
		},
		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;
		},
		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;
			}
			if(this.isValidMove(emptyIndex, clickedIndex)){
				this.swap(emptyIndex, clickedIndex);	
				this.gameStarted && this.focusEmptySquare();
			}
		},
		handleClick(e){
			e.preventDefault();
			//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
				console.log(emptyIndex, clickedIndex);
				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
			}
		},
		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
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console