Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
15-puzzle stub
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="">
<style type="text/css">
* {
font-family: Helvetica;
}
#board {
width: 160px;
height: 160px;
min-height: 160px;
min-width: 160px;
background-color: #fe0;
}
.klocek {
width: 38px;
height: 38px;
background-color: green;
color: white;
font-size: 18px;
text-align: center;
display: inline-block;
margin: 1px;
}
.klocek span {
margin-top: 8px;
display: block;
}
</style>
</head>
<body>
<h1>PUZZLE</h1>
<div id="board">
</div>
<script type="text/javascript">
// Get board element
var board = document.getElementById('board');
// Iterate through 4x4 board
for (y = 0; y < 4; y++) {
for (x = 0; x < 4; x++) {
// Assign a number to each piece 1..15
var label = (y * 4 + x + 1);
// We want to skip last piece, so adding a condition
if (label < 16) {
// Create HTML element in memory
var p = document.createElement('div');
// set contents so it is for example:
// <div><span>12</span></div>
p.innerHTML = '<span>' + label + '</span>';
// Set CSS class
p.setAttribute('class', 'klocek');
// Calculate coordinates
var px = x * 40; // multiply by size of each piece
var py = y * 40;
// And position this element within its container (#board)
p.style.top = py + 'px';
p.style.left = px + 'px';
// Finally, append this element to document. Until then
// it existed only in memory.
board.appendChild(p);
}
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment