Eight queens puzzle
Eight queens puzzle
by mgtheboss
HTML
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.3.0/fabric.min.js"></script>
<title>Eight queens puzzle</title>
<body>
<canvas width="640" height="640" id="c"></canvas>
</body>
CSS
canvas {
border: 1px solid #000000;
}
JavaScript
// create a wrapper around native canvas element (with id="c")
var canvas = new fabric.Canvas('c');
var noOfQueens = 0;
for (i = 0; i < 8; i++)
for (j = 0; j < 8; j++)
canvas.add(new fabric.Rect({
left: (2 * j + 1) * 40,
top: (2 * i + 1) * 40,
fill: (i + j) % 2 == 0 ? 'white' : 'black',
width: 80,
height: 80,
strokeWidth: 5,
stroke: 'black',
lockMovementX: true,
lockMovementY: true,
lockScalingX: true,
lockScalingY: true,
hasControls: false,
hasBorders: false
}).on('selected', function () {
changeColor(this);
}));
function changeColor(obj) {
canvas.deactivateAllWithDispatch();
if (obj.getFill() != '#d914a0') {
if (noOfQueens >= 8) {
console.log('Have you forgotten that you have eight queens?');
return;
}
obj.setFill('#d914a0');
noOfQueens++;
if (noOfQueens == 8 && canvas.item(5).getFill() == '#d914a0' && canvas.item(11).getFill() == '#d914a0' && canvas.item(22).getFill() == '#d914a0' && canvas.item(24).getFill() == '#d914a0' && canvas.item(39).getFill() == '#d914a0' && canvas.item(41).getFill() == '#d914a0' && canvas.item(52).getFill() == '#d914a0' && canvas.item(58).getFill() == '#d914a0') {
console.log('Good job! You just solved famous Eight-Queens Puzzle.');
}
} else {
j = ((obj.getLeft() / 40) - 1) / 2;
i = ((obj.getTop() / 40) - 1) / 2;
obj.setFill((i + j) % 2 == 0 ? 'white' : 'black');
noOfQueens--;
}
}