HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
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.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
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.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
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.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<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>
$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;
}
}
// 👀 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);
}
}
});
Also see: Tab Triggers