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 class="wrapper">
<h1 class="title"> Nonogram </h1>
<button id="mute" onclick="handleMute(this)">mute</button>
<p class="explination">A <a href="https://en.wikipedia.org/wiki/Nonogram" target="_blank"> nonogram </a> is a puzzle that challenges you to fill in squares on a grid based on numeric clues. Each row and column has a sequence of numbers indicating the lengths of continuous lines of filled squares in it. Your task is to deduce which squares are filled by logically combining these clues.
<br /><br />
(Click the top left O/X to toggle between selection and rejection mode)
</p>
<div id="nono"></div>
<p> Puzzle: <span id="winState">unsolved</span>
</p>
<div class="generateContainer">
<input type="range" class="slider" min="1" max="10" value="4" step="1" oninput="handleSizeChange(this.value)" />
<p id="gridSize">4</p>
<button onclick="handleGen()"> new Puzzle </button>
</div>
</div>
:root {
--cellSize: 25px;
--headerSize: 60px;
--col-bg: #004643;
--col-primary: #abd1c6;
--col-accent: #f9bc60;
--col-white: #fffffe;
--col-dark: #001e1d;
--tableBorder: 2px solid var(--col-dark);
}
p {
color: var(--col-dark);
}
.title {
color: var(--col-white);
margin-top: 1rem;
margin-bottom: 0;
}
.explination {
color: var(--col-primary);
margin-bottom: 1rem;
max-width: 500px;
font-size: 13px;
text-align: center;
padding: 0 1rem;
a {
color: var(--col-white);
}
}
#switcher {
font-weight: bold;
color: var(--col-accent);
&.alt {
color: var(--col-dark);
}
}
#winState {
color: var(--col-dark);
font-weight: bold;
&.won {
content: "hello";
color: var(--col-accent);
}
}
body {
background: var(--col-bg);
}
.wrapper {
display: flex;
flex-direction: column;
margin-top: 2rem;
align-items: center;
#nono {
min-height: 100px;
padding-top: 2rem;
table {
border-spacing: 0;
tr {
// The first row
&:first-child {
th {
height: var(--headerSize);
.clues {
height: 100%;
flex-direction: column;
margin-bottom: 8px;
}
}
}
th {
border-bottom: var(--tableBorder);
border-right: var(--tableBorder);
//The first column
&:first-child {
width: var(--headerSize);
.clues {
gap: 8px;
margin-bottom: 0;
margin-right: 8px;
}
}
.clues {
display: flex;
justify-content: flex-end;
gap: 4px;
p {
margin: 0;
color: var(--col-accent);
}
}
}
td {
cursor: pointer;
width: var(--cellSize);
height: var(--cellSize);
border-bottom: var(--tableBorder);
border-right: var(--tableBorder);
transition: all 0.2s;
&:hover {
background: var(--col-primary);
}
&.rejected {
background: var(--col-dark);
&:hover {
opacity: 0.5;
}
}
&.toggled {
background: var(--col-accent);
&:hover {
opacity: 0.5;
}
}
}
}
}
}
}
.generateContainer {
display: flex;
align-items: center;
#gridSize {
font-weight: bold;
color: var(--col-primary);
font-size: 1.5rem;
margin-left: 8px;
margin-right: 16px;
}
}
button {
background: var(--col-primary);
outline: none;
border: none;
padding: 4px 10px;
color: var(--col-dark);
font-weight: bold;
cursor: pointer;
}
#mute {
position: fixed;
right: 8px;
bottom: 8px;
}
.slider {
-webkit-appearance: none;
height: 15px;
background: #d3d3d3;
outline: none;
opacity: 0.7;
-webkit-transition: 0.2s;
transition: opacity 0.2s;
}
.slider:hover {
opacity: 1;
}
.slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 15px;
height: 15px;
background: #04aa6d;
cursor: pointer;
}
.slider::-moz-range-thumb {
width: 15px;
height: 15px;
background: #04aa6d;
cursor: pointer;
}
let audioContext = new (window.AudioContext || window.webkitAudioContext)();
let gridSize = 4;
let nextSize = 4;
let wonCurrent = false;
let currentNono = [[]];
let vClues = [[]];
let hClues = [[]];
let muted = false;
let markAsActive = true;
const generateNono = () => {
let nextNono = [];
for (let x = 0; x < gridSize; x++) {
const newRow = [];
for (let y = 0; y < gridSize; y++) {
newRow.push({ value: Math.random() > 0.5 ? 1 : 0, guess: 0 });
}
nextNono.push(newRow);
}
currentNono = nextNono;
populateClues();
};
const getNonogramClueFromArray = (arr) => {
let clues = [],
count = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] === 1) {
count++;
} else if (count > 0) {
clues.push(count);
count = 0;
}
}
//make sure we add final clue
if (count > 0) {
clues.push(count);
}
return clues;
};
//returns the clues given a col index
const calculateVerticalClues = (index) => {
const col = currentNono.reduce((acc, row) => {
acc.push(row[index].value);
return acc;
}, []);
return getNonogramClueFromArray(col);
};
//returns the clues given a row index
const calculateHorizontalClues = (index) => {
const row = currentNono[index].map((n) => n.value);
return getNonogramClueFromArray(row);
};
const populateClues = () => {
hClues = [];
vClues = [];
for (let n = 0; n < gridSize; n++) {
hClues.push(calculateHorizontalClues(n));
vClues.push(calculateVerticalClues(n));
}
};
//builds a th element with given clues
const constructClueHeader = (clues) => {
const header = document.createElement("th");
const wrapper = document.createElement("div");
wrapper.classList.add("clues");
clues.forEach((clue) => {
const clueElement = document.createElement("p");
clueElement.innerText = clue;
wrapper.append(clueElement);
});
header.append(wrapper);
return header;
};
const getCellClickHandler = (row, col) => {
return async (event) => {
if (!wonCurrent) {
if (markAsActive) {
if (!event.target.classList.contains("rejected")) {
currentNono[row][col].guess = 1 - currentNono[row][col].guess;
playSound(currentNono[row][col].guess == 1 ? 600 : 400, 0.1);
event.target.classList.toggle("toggled");
if (hasWon()) {
wonCurrent = true;
document.getElementById("winState").classList.add("won");
document.getElementById("winState").innerText = "solved!";
await getTimeoutPromise(600);
playVictory();
}
}
} else {
if (!event.target.classList.contains("toggled")) {
playSound(500, 0.1);
event.target.classList.toggle("rejected");
}
}
}
};
};
const arraysMatch = (a1, a2) => {
if (a1.length != a2.length) return false;
for (let n = 0; n < a1; n++) {
if (a1[n] != a1[n]) return false;
}
return true;
};
const hasWon = () => {
//We need to check the guessed grid satisfies the clues
for (let n = 0; n < gridSize; n++) {
//horiziontally
const row = currentNono[n].map((i) => i.guess);
const equivRowClue = getNonogramClueFromArray(row);
if (!arraysMatch(equivRowClue, hClues[n])) {
return false;
}
//vertically
const col = currentNono.reduce((acc, row) => {
acc.push(row[n].guess);
return acc;
}, []);
const equivColClue = getNonogramClueFromArray(col);
if (!arraysMatch(equivColClue, vClues[n])) {
return false;
}
}
return true;
};
const constructFirstRow = () => {
const row = document.createElement("tr");
const switcher = document.createElement("th");
switcher.innerText = markAsActive ? "O" : "X";
switcher.id = "switcher";
switcher.addEventListener("click", () => {
markAsActive = !markAsActive;
switcher.classList.toggle("alt");
switcher.innerText = markAsActive ? "O" : "X";
});
row.append(switcher);
vClues.forEach((clues) => {
row.append(constructClueHeader(clues));
});
return row;
};
const constructRegularRow = (rowIndex) => {
const row = document.createElement("tr");
row.append(constructClueHeader(hClues[rowIndex]));
for (let x = 0; x < gridSize; x++) {
const cell = document.createElement("td");
cell.addEventListener("click", getCellClickHandler(rowIndex, x));
row.append(cell);
}
return row;
};
const constructHTMLNono = () => {
const table = document.createElement("table");
//Create the firs row (just clues)
table.append(constructFirstRow());
for (let y = 0; y < gridSize; y++) {
table.append(constructRegularRow(y));
}
const nono = document.getElementById("nono");
nono.innerHTML = "";
nono.append(table);
};
const getTimeoutPromise = (millis) => {
return new Promise((res) => {
setTimeout(res, millis);
});
};
const playSound = (freq, dur = 0.1) => {
if (muted) return;
let oscillator = audioContext.createOscillator();
let gainNode = audioContext.createGain();
oscillator.type = "sine";
oscillator.frequency.setValueAtTime(freq || 440, audioContext.currentTime);
oscillator.connect(gainNode);
gainNode.gain.value = 0.07;
gainNode.connect(audioContext.destination);
oscillator.start();
oscillator.stop(audioContext.currentTime + dur);
return getTimeoutPromise(dur * 1000);
};
const playVictory = async () => {
const C = 261.63,
E = 329.63,
G = 392.0,
C_high = 523.25;
const duration = 0.14; // Duration for each note in milliseconds
const pauseDur = 10;
await playSound(C, duration);
await getTimeoutPromise(pauseDur);
await playSound(E, duration);
await getTimeoutPromise(pauseDur);
await playSound(G, duration);
await getTimeoutPromise(pauseDur);
await playSound(C_high, duration);
await getTimeoutPromise(pauseDur);
await playSound(G, duration);
await getTimeoutPromise(pauseDur);
await playSound(C_high, duration * 4);
await getTimeoutPromise(pauseDur);
};
const handleSizeChange = (newVal) => {
nextSize = newVal;
document.getElementById("gridSize").innerText = nextSize;
};
const handleGen = () => {
gridSize = nextSize;
buildNono();
wonCurrent = false;
document.getElementById("winState").classList.remove("won");
document.getElementById("winState").innerText = "unsolved";
};
const handleMute = (e) => {
muted = !muted;
e.innerText = muted ? "unmute" : "mute";
};
const buildNono = () => {
generateNono();
constructHTMLNono();
currentNono.forEach((row) => {
console.log(row.map((c) => c.value));
});
};
buildNono();
Also see: Tab Triggers