15 puzzle game: Difference between revisions

→‎{{header|Java}}: fix bug, reverse some unnecessary pedantic edits
(→‎{{header|Java}}: visual feedback when the puzzle is solved)
(→‎{{header|Java}}: fix bug, reverse some unnecessary pedantic edits)
Line 2,472:
 
class FifteenPuzzle extends JPanel {
 
private final int side = 4;
private final int numTiles = side * side - 1;
Line 2,500 ⟶ 2,501:
int ey = e.getY() - margin;
 
if (ex < 0 || ex > gridSize || ey < 0 || ey > gridSize) {
return;
f.pack(); }
 
int c1 = ex / tileSize;
Line 2,527 ⟶ 2,529:
 
private void reset() {
for (int i = 0; i < tiles.length; i++) {
tiles[i] = (i + 1) % tiles.length;
}
blankPos = numTiles;
}
Line 2,545 ⟶ 2,548:
 
/* Only half the permutations of the puzzle are solvable.
 
Whenever a tile is preceded by a tile with higher value it counts
as an inversion. In our case, with the blank space in the home
position, the number of inversions must be even for the puzzle
to be solvable.
 
See also:
www.cs.bham.ac.uk/~mdr/teaching/modules04/java2/TilesSolvability.html
*/
private boolean isSolvable() {
int countInversions = 0;
for (int i = 0; i < numTiles; i++) {
for (int j = 0; j < i; j++) {
if (tiles[j] > tiles[i]) {
countInversions++;
}
}
}
Line 2,582 ⟶ 2,586:
 
if (tiles[i] == 0) {
if (!isSolved()) {
g.setColor(Color.GREEN);
drawCenteredString(g, "✓", x, y);
Line 2,602 ⟶ 2,606:
FontMetrics fm = g.getFontMetrics();
int asc = fm.getAscent();
int descdec = fm.getDescent();
 
int baseXx = x + (tileSize - fm.stringWidth(s)) / 2;
int baseYy = y + (asc + (tileSize - (asc + descdec)) / 2);
 
g.drawString(s, baseXx, baseYy);
}
 
Line 2,617 ⟶ 2,622:
 
drawGrid(g);
}
 
private static void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
f.setTitle("Fifteen Puzzle");
f.setResizable(false);
f.add(new FifteenPuzzle(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
 
public static void main(String[] args) {
SwingUtilities.invokeLater(FifteenPuzzle::run(); -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstantsJFrame.DISPOSE_ON_CLOSEEXIT_ON_CLOSE);
f.setTitle("Fifteen Puzzle");
f.setResizable(false);
f.add(new FifteenPuzzle(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}</lang>
Anonymous user