JSFiddle - React, Tailwind, and code Playground
by Zareh Geertjes
HTML
<script src="//code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<link rel="stylesheet" href="//stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script src="//stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js"></script>
<div class="container">
</div>
SCSS
body{
padding: 20px;
}
.row{
.tile{
width:40px;
height: 40px;
background: #fff;
border: solid 1px #fff;
text-align: center;
line-height: 40px;
cursor: pointer;
background-image: url(https://zareh.nl/tegel.png);
&:not(.tileBlanco){
background-size: cover;
}
&.tile2{
transform: rotate(90deg);
}
&.tile3{
transform: rotate(180deg);
}
&.tile4{
transform: rotate(270deg);
}
}
}
JavaScript
var wall = {};
function drawTiles(tile, wall) {
var tiles = '';
_.forEach(tile, function(value, key) {
tiles = tiles + '<div class="tile tile' + value.type + '" ID="' + wall + '-' + key + '"></div>';
});
return tiles;
}
function drawRows(wall) {
_.forEach(wall, function(value, key) {
$('.container').append(
$("<div />").addClass("row " + key).html(
drawTiles(value, key)
)
);
});
}
function getRandomType() {
var elements = [
"Blanco",
"Blanco",
"1",
"2",
"3",
"4"
];
return _.sample(elements);
};
function createWall(rows, cols) {
_.times(rows, function(rowIndex) {
wall['row' + rowIndex] = {};
_.times(cols, function(colIndex) { // allows multiple grids
wall['row' + rowIndex]['tile' + colIndex] = {
type: getRandomType(),
fixed: false
};
});
});
drawRows(wall);
localStorage.setItem('wall', JSON.stringify(wall));
};
$("body").on("click", ".tile", function() {
var ID = $(this).attr('ID').split('-');
var row = ID[0];
var tile = ID[1]
wall[row][tile].type = getRandomType();
$('.container').html('');
drawRows(wall);
localStorage.setItem('wall', JSON.stringify(wall));
});
var existingWall = localStorage.getItem('wall');
if (existingWall) {
wall = JSON.parse(existingWall);
drawRows(wall);
} else {
createWall(17, 13);
}