const EMPTY = 0; // constants and variables
const QUEEN = 1;
var board = []; // chessboard
var countQueens; // number of queens
var excludedRow; // row to be skipped
function loop(row) // recursive function
{
if (row == excludedRow) // skip the excluded row
row++; // this is for the fixed queen
for (var x = 0; x < 8; x++) // go through all columns
{
if (isPossible(row, x)) // check all directions
{
board[row][x] = QUEEN; // place a queen on the board
countQueens++; // increase the number of queens
if (countQueens >= 8) // check the number of queens
return true; // return true when solved
// otherwise
if (loop(row + 1)) // start a new loop in the next row
return true; // return true when solved
// otherwise if it does not work
countQueens--; // decrease the number of queens
board[row][x] = EMPTY; // delete the queen
}
}
return false;
}
function isPossible(y1, x1) // check all directions
{
if (board[y1][x1] == EMPTY)
{
for (let x = 0; x < 8; x++) // check row
{
if (board[y1][x] == QUEEN)
return false;
}
for (let y = 0; y < 8; y++) // check column
{
if (board[y][x1] == QUEEN)
return false;
}
for (let y = y1, x = x1; y < 8 && x < 8; y++, x++)
{ // check bottom right
if (board[y][x] == QUEEN)
return false;
}
for (let y = y1, x = x1; y >= 0 && x >= 0; y--, x--)
{ // check top left
if (board[y][x] == QUEEN)
return false;
}
for (let y = y1, x = x1; y >= 0 && x < 8; y--, x++)
{ // check top right
if (board[y][x] == QUEEN)
return false;
}
for (let y = y1, x = x1; y < 8 && x >= 0; y++, x--)
{ // check bottom left
if (board[y][x] == QUEEN)
return false;
}
}
else
return false;
return true;
}
function clickBoard(ev) // mouse click
{
if (ev.target.id[1] >= 0 && ev.target.id[1] < 8 && ev.target.id[2] >= 0
&& ev.target.id[1] < 8) // ensures that the values are valid
{
resetBoard(); // reset the chessboard
// this position is set with a mouse click
// the excludedRow is skipped in the algorithm
// this position is fixed
excludedRow = ev.target.id[1];
board[excludedRow][ev.target.id[2]] = QUEEN;
countQueens = 1;
loop(0); // start the recursive loop in row zero
updateBoard();
}
}
function load() // onLoad event
{
// reset the chessboard at first
resetBoard();
// place the first queen at random
// the excludedRow is skipped in the algorithm
// this position is fixed
excludedRow = Math.floor(Math.random() * 8);
board[excludedRow][Math.floor(Math.random() * 8)] = QUEEN;
countQueens = 1;
// start the recursive loop in row zero
loop(0);
updateBoard();
}
function resetBoard()
{
board = []; // overwrite the board
for (let i = 0; i < 8; i++)
board[i] = new Array(8).fill(EMPTY);// fill the board with zeros
}
function updateBoard() // show the result
{
for (var y = 0; y < 8; y++)
{
for (var x = 0; x < 8; x++)
{
var el = document.getElementById("I" + y.toString() + x.toString());
if (board[y][x] == QUEEN) // draw a queen
{
if (y == excludedRow)
el.innerHTML = "<span style='color: red;'>♕</span>";
else
el.innerHTML = "♕";
}
else // empty square
el.innerHTML = "";
}
}
}