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 is required to process package imports. If you need a different preprocessor remove all packages first.

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

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="board">

	
	<div id="game-group">
		<form @click="handleClick" :aria-label="`${howManyCorrect} of ${ratioSquared} tiles correctly placed.`" :class="{dim: dimTiles, invertNumbers: invertNumbers, showNumbers: showNumbers}">
			<transition-group name="slide" id="innerBoard" tag="div" :style="{gridTemplateColumns: `repeat(${ratio}, 1fr)`, gridTemplateColumns: `repeat(${ratio}, 1fr)`}">
				<button 
					v-for="(tile, index) in tiles" 
					:key="tile.val" @keyup.prevent="handleArrow"
					:index="index" :ref="!tile.val && 'empty'" 
					:disabled="!tile.isPossibleMove && tile.val > 0"
					class="tile"
					:class="{ correct: isTileCorrect(tile.val,index), possible_move: tile.isPossibleMove }" 
					:aria-label="getAccessibleTilePosition(tile.val, index)"
					:style="{
						backgroundPosition: getBackgroundPosition(tile.val),
						backgroundSize: `calc(100% * ${ratio}) calc(100% * ${ratio})`
					}"
				>
					<span v-if="tile.val">{{showNumbers ? tile.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 id="counter">
			<span id="progress-bar" :style="{width: howManyCorrect / ratioSquared * 100 + '%'}"></span>
			<strong>{{howManyCorrect}} / {{ratioSquared}}</strong>
		</p>
		<p>Play with 🖱️, 👆, or ⌨️ ⬆️ ➡️ ⬇️ ⬅️</p>
	</div>
	
	
	<aside id="options">			
		<div id="custom-image">
			<label for="custom-image-input">Custom Image:</label>
			<select v-model="imageSelect" name="imageSelect" id="imageSelect">
				<option value="https://s3-us-west-2.amazonaws.com/s.cdpn.io/240751/sanfran.jpg">Golden Gate</option>
				<option value="https://s3-us-west-2.amazonaws.com/s.cdpn.io/240751/chicago.jpg">Chicago</option>
				<option value="https://s3-us-west-2.amazonaws.com/s.cdpn.io/240751/griff.jpg">Hiding Pupper</option>
				<option value="custom">Custom URL</option>
			</select>
			<input v-if="imageSelect === `custom`" @click="highlightInput" v-model="customImage" id="custom-image-input" type="text"/>
		</div>
		<div v-if="showSolution" id="solution" :style="{backgroundImage: imageSelect == 'custom' ? `url(${customImage})` : `url(${imageSelect})`}">
			<span>[Solution]</span>
		</div>
		<div class="options-group">
			<input v-model="showSolution" type="checkbox" id="show-solution">
			<label for="show-solution">Show solution</label>
		</div>
		<div class="options-group">
			<input v-model="dimTiles" type="checkbox" id="highlight-tiles">
			<label for="highlight-tiles">Dim incorrect tiles</label>
		</div>
		<div class="options-group">
			<input v-model="showNumbers" type="checkbox" id="show-numbers">
			<label for="show-numbers">Show numbers</label>
			<transition name="fade">
				<div v-if="showNumbers">
					<input v-model="invertNumbers" type="checkbox" id="invert-numbers">
					<label for="invert-numbers">Invert number colors</label>
				</div>
			</transition>
		</div>
		<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>
	</aside>
</div>
	
              
            
!

CSS

              
                $breakpoint1: 480px;
$breakpoint2: 769px;
$breakpoint3: 1020px;

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

:root {
	--dark: #53565a;
	--light: #a7a8aa;
	--highlight: #ffd100;
	--background: #7BA7BC;
	--transition: transform .15s;
	--ratio: 4;
	--maxBoardWidth: 80vmin;
	--smallColumn: calc(240px + 2em);
	--backgroundImage: '';
	--radius: 8px;
	@media (min-width: $breakpoint1){
		--maxBoardWidth: 60vh;
	}
	@media (min-width: $breakpoint3){
		--maxBoardWidth: 70vh;
	}
}

$ratio: var(--ratio);

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

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

#custom-image {
	width: 100%;
	max-width: 40em;
	align-items: center;
	input {
		width: 100%;
		padding: .25em;
		font-size: .8em;
		margin: .5em 0 0;
		border: none;
	}
	& + #solution {
		margin-top: .5em;
	}
}

#board {
	text-align: center;
	display: grid;
	place-items: center;
	position: relative;
	width: 100%;
	min-height: 100%;
	grid-gap: 2em;
	@media (min-width: $breakpoint2){
		align-items: start;
		grid-template-columns: 1fr var(--smallColumn);
	}
	#game-group {
		@media (min-width: $breakpoint2){
			justify-content: center;
		}
	}
	#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;
		}
	}
	label {
		cursor: pointer;
	}
	form {
		width: var(--maxBoardWidth);
		height: var(--maxBoardWidth);
		border-radius: var(--radius);
		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;
		}
		&.dim {
			.tile {
				//opacity: .5;
				span:before {
					content: '';
					width: 100%;
					height: 100%;
					padding: 100%;
					background: rgba(0,0,0,.5);
					position: absolute;
					left: -50%;
					top: -50%;
					z-index: -1;
				}
			&.correct span:before {
					background: transparent;
				}
			}
		}
		&.invertNumbers {
			.tile {
				color: #fff;
				&.correct {
					color: var(--highlight);
				}
			}
		}
		&.showNumbers {
			.square.possible-move:hover span {
				transform: scale(1.3);
			}
		}
	}
	& > p {
		font-size: 1.4rem;
	}
	& aside#options {
		width: var(--maxBoardWidth);
		display: flex;
		flex-wrap: wrap;
		align-items: center;
		justify-content: center;
		text-align: left;
		position: relative;
		background: rgba(0,0,0,.2);
		background: var(--background);
		background: rgba(0,0,0,.1);
		//box-shadow: 2px 4px 6px rgba(0,0,0,.15);
		padding: 1.5em 2em;
		border-radius: var(--radius);
		@media(min-width: $breakpoint2){
			width: 100%;
		}
		select {
			width: 100%;
			padding: .5em;
			font-size: 1em;
			font-family: 'Nunito', sans-serif;
			color: #53565a;
			background: #fff;
			margin-top: .25em;
			cursor: pointer;
		}
		#solution {
			width: 100%;
			height: 0;
			padding: 50% 0;
			opacity: .8;
			background-size: 100% 100%;
			position: relative;
			transition: opacity .3s ease;
			display: grid;
			line-height: 0;
			place-items: center;
			text-align: center;
			font-size: 2em;
			color: rgba(255,255,255,.5);
			text-shadow: 0px 0px .5em rgba(0,0,0,.5);
			&:hover {
				opacity: 1;
			}
			&:after {
				content: '';
				position: absolute;
				display: block;
				width: calc(100% / var(--ratio));
				height: calc(100% / var(--ratio));
				background: var(--dark);
				bottom: 0;
				right: 0;
			}
		}
		.options-group {
			width: 100%;
			margin: .75em 0 0;
			&:first-of-type{
				margin-top: 2em;
			}
			&:last-of-type{
				// padding: 1em 0;
				// border-bottom: 1px solid;
			}
			input[type=checkbox] {
				transform: scale(1.5);
				margin-right: .5em;
			}
			label {
				vertical-align: middle;
			}
		}
		button {
			margin: 1em 0 0;
			padding: 2vmin 3vmin;
			font-size: 1rem;
			border-radius: 20vmin;
			border: none;
			text-transform: uppercase;
			outline-color: var(--highlight);
		}
	}
}

#innerBoard {
	display: grid;
	height: 100%;
	width: 100%;
	margin: 0 auto;
	overflow: hidden;
	.tile {
		cursor: initial;
		padding: 0;
		font-size: calc(4.2vmin - (var(--ratio) * .1vmin));
		display: grid;
		text-align: center;
		place-items: center;
		align-content: stretch;
		border: none;
		background: #fff;
		background: var(--backgroundImage);
		position: relative;
		z-index: 1;
		background-size: calc(100% * var(--ratio));
    background-position: 0% 0%;
		overflow: hidden;
		@media (min-width: $breakpoint1){
				font-size: calc(4vmin - (var(--ratio) * .2vmin));
		}
		span {
			transition: transform .1s;
			pointer-events: none!important; //Just being safe		
			&:before {
				content: '';
				width: 100%;
				height: 100%;
				padding: 100%;
				background: transparent;
				position: absolute;
				left: -50%;
				top: -50%;
				z-index: -1;
			}
		}
		&:focus {
			outline: none;
			& span {
				transform: scale(1.5);
			}
		}
		&.possible-move {
			cursor: pointer;
		}
		&.correct {
			color: var(--highlight)!important;
		}
		&:empty {
			background: var(--dark)!important;
			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 {
  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);
	span:before {
		transition: all .3s ease;
	}
}

@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(){
		return {
			ratio: 4, //👈 A little buggy at some sizes; works best at 4, but ¯\_(ツ)_/¯
			tiles: [],
			solution: [],
			illegalMoves: [],
			invertSwipe: false,
			showNumbers: false,
			invertNumbers: false,
			dimTiles: false,
			imageSelect: 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/240751/sanfran.jpg',
			customImage: 'https://ih0.redbubble.net/image.369334182.5732/flat,1000x1000,075,f.u2.jpg',
			showSolution: true,
			gameStarted: false
		}
	},
	watch: {
		tiles: function(newTiles){
			if(this.gameStarted){
				//We need nextTick here or the board will render legal moves based on where the empty tile *used to* be
				this.$nextTick(()=>{
					const legalMoves = this.getLegalMoves();
					newTiles.forEach((tile, index) => {
						newTiles[index].isPossibleMove = legalMoves.includes(index) ? true : false;
					});
				})
			}
		},
		customImage(){
			document.querySelector('.root').style.setProperty('--backgroundImage', `url(${this.customImage})`);
		},
		imageSelect(){
			document.querySelector('.root').style.setProperty('--backgroundImage', this.imageSelect === 'custom' ? `url(${this.customImage})` : `url(${this.imageSelect})`);
		}
	},
	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.tiles.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 tiles = document.querySelectorAll('#innerBoard .tile');
		
		//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 and background image in CSS
		document.querySelector('.root').style.setProperty('--ratio', this.ratio);
		document.querySelector('.root').style.setProperty('--backgroundImage', this.imageSelect === 'custom' ? `url(${customImage})` : `url(${this.imageSelect})`);
		
		//Prevent arrow keys from scrolling
		innerBoard.addEventListener("keydown", function(e) {
    // space and arrow keys
			if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) {
				e.preventDefault();
			}
		}, false);
		
		this.randomizeBoard();
	},
	computed: {
		randomMoveQty(){
			return (this.ratio * 75);
		},
		howManyCorrect(){
			const correctlyPlacedTiles = this.tiles.filter((tile, index) => {
				return (Number(tile.val) == Number(index + 1) || Number(index + 1) == this.ratioSquared && !tile.val);
			});
			if(correctlyPlacedTiles.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 correctlyPlacedTiles.length;
		},
		ratioSquared(){
			return this.ratio * this.ratio;
		},
	},
	methods: {
		isTileCorrect(val, index){
			return val - 1 == index;
		},
		highlightInput(e) {
			e.target.select();
		},
		getBackgroundPosition(val){
			return val ? `${(100 / (this.ratio - 1)) * (val -1)}% ${Math.floor((val - 1) / this.ratio) * (100 / (this.ratio - 1))}%` : '5% 5%';
		},
		moveIsNotTheSameTile(a, b){
			return a != b; //Can't shuffle a tile with itself
		},
		moveIsInBounds(a, b){
			//Don't let the user try to move a tile outside the board
			return (a >= 0 && b >= 0 && a < this.ratio * this.ratio && b < this.ratio * this.ratio);
		},
		moveIsAdjacentTile(a, b){
			//Tiles 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.moveIsNotTheSameTile(a, b) && this.moveIsInBounds(a, b) && this.moveIsAdjacentTile(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.getEmptyTileIndex();			
					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.focusEmptyTile();
							document.querySelector('.root').style.setProperty('--transition', 'transform .15s ease-out');
							return;
						}
					}
				}
			}
			setTimeout(()=>{
				randomMove();
			},100)
		},
		getLegalMoves(){
			const emptyIndex = this.getEmptyTileIndex();
			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;
			}
		},
		getAccessibleTilePosition(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}`
		},
		focusEmptyTile(){
			 this.$nextTick(() => this.$refs.empty[0].focus());
		},
		getEmptyTileIndex(){
			return this.$refs.empty ? Number(this.$refs.empty[0].getAttribute('index')) : this.ratioSquared -1;
		},
		handleArrow(e){
			const emptyIndex = this.getEmptyTileIndex();
			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.focusEmptyTile();
			}
		},
		handleClick(e){
			e.preventDefault();
			//Get the empty tile and the clicked tile, then both of their index values
			const emptyIndex = this.getEmptyTileIndex();
			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 tile and the clicked tile, exit early
			}

			//Check if the clicked move is valid
			if (this.isValidMove(emptyIndex, clickedIndex)) {
				//Shuffle the two tiles if it's a valid move
				console.log(emptyIndex, clickedIndex);
				this.swap(emptyIndex, clickedIndex);
				//Focus the empty tile if it was a click or keyboard move
				this.gameStarted && !wasSwipe && this.focusEmptyTile();
			} else {
				return; //If it's not a valid move, do nothing
			}
		},
		swap(clickedIndex, emptyIndex) {
				const a = this.tiles[clickedIndex];
				const b = this.tiles[emptyIndex];
				this.$set(this.tiles, clickedIndex, b);
				this.$set(this.tiles, emptyIndex, a);
		}
	}
});
              
            
!
999px

Console