I've been writing out a Javascript version of the 15 slider puzzle and am able to simulate the "moving" of the tiles through swapping innerHTML values. I'm also using instead of an array, as I've seen others suggest. Given my code, how would I go about inputting a way to check whether the puzzle is solved or not? When it's solved, I'd like it to alert with a "Solved!" message, which I can do. I just don't know how to make it check to see if the puzzle actually IS solved.
I was thinking of having an alert pop-up with a conditional if statement (i.e., if the blank cell is located at row 3, cell 3) but that quickly fizzled out. It also doesn't check whether or not each row has 1-15 in the correct order, either. I initially have the puzzle start out with 2 tiles swapped. Here's where I am so far:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html> <head>
<title>15 puzzle</title>
<style>
td {
border: 1px solid blue;
width: 30px;
height: 30px;
text-align: center;
vertical-align: middle;
}
td:hover {
background-color: yellow;
}
</style>
<script>
var blank_row = 3;
var blank_col = 3;
var puzzle = document.getElementById("puzzle");
function f(e) {
var my_row = e.parentElement.rowIndex;
var my_col = e.cellIndex;
if ((blank_col == my_col &&
Math.abs(blank_row - my_row) == 1)
||
(blank_row == my_row &&
Math.abs(blank_col - my_col) == 1)) {
var e2 = document.getElementById("puzzle").rows[blank_row].cells[blank_col];
e2.innerHTML = e.innerHTML;
e.innerHTML = " ";
blank_row = my_row;
blank_col = my_col;
}
}
</script>
</head>
<body>
<table id="puzzle">
<tr>
<td onclick="f(this)">1</td>
<td onclick="f(this)">6</td>
<td onclick="f(this)">3</td>
<td onclick="f(this)">4</td>
</tr>
<tr>
<td onclick="f(this)">5</td>
<td onclick="f(this)">10</td>
<td onclick="f(this)">7</td>
<td onclick="f(this)">8</td>
</tr>
<tr>
<td onclick="f(this)">9</td>
<td onclick="f(this)">2</td>
<td onclick="f(this)">11</td>
<td onclick="f(this)">12</td>
</tr>
<tr>
<td onclick="f(this)">13</td>
<td onclick="f(this)">14</td>
<td onclick="f(this)">15</td>
<td onclick="f(this)"> </td>
</tr>
</table>
</body>
</html>