game-of-15
by Anchit Gupta
HTML
<div id="container">
<div class="tile" row="1" col="1">1</div>
<div class="tile" row="1" col="2">2</div>
<div class="tile" row="1" col="3">3</div>
<div class="tile" row="1" col="4">4</div>
<div class="tile" row="2" col="1">5</div>
<div class="tile" row="2" col="2">6</div>
<div class="tile" row="2" col="3">7</div>
<div class="tile" row="2" col="4">8</div>
<div class="tile" row="3" col="1">9</div>
<div class="tile" row="3" col="2">10</div>
<div class="tile" row="3" col="3">11</div>
<div class="tile" row="3" col="4">12</div>
<div class="tile" row="4" col="1">13</div>
<div class="tile" row="4" col="2">14</div>
<div class="tile" row="4" col="3">15</div>
</div>
CSS
#container{
width:400px;
height:400px;
border: 1px solid black;
position: relative;
font-size: 32px;
}
.tile{
width:94px;
padding-top: 30px;
height:64px;
background-color:#f77;
border: 1px solid #faa;
margin: 2px;
text-align: center;
position: absolute;
transition-duration: 1s;
}
.tile:active{
margin-left:1px;
margin-right:3px;
}
.tile[row="1"]{ top: 0px;}
.tile[row="2"]{ top: 98px;}
.tile[row="3"]{ top: 196px;}
.tile[row="4"]{ top: 294px;}
.tile[col="1"]{ left: 0px;}
.tile[col="2"]{ left: 98px;}
.tile[col="3"]{ left: 196px;}
.tile[col="4"]{ left: 294px;}
JavaScript
(function(){
var rowNo = 4, colNo = 4;
$('.tile').on('click',function(event){
var row = parseInt($(event.target).attr("row"), 10);
var col = parseInt($(event.target).attr("col"), 10);
if ( (Math.abs(row - rowNo) == 1 && col === colNo)
|| (Math.abs(col - colNo) == 1 && row === rowNo))
{
// Swap
$(event.target).attr("row",rowNo);
$(event.target).attr("col",colNo);
rowNo = row;
colNo = col;
}
});
})();