Advertisement
cd62131

Puzzle15

Jan 16th, 2023
1,186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.08 KB | None | 0 0
  1. import java.awt.GridLayout;
  2. import java.util.ArrayList;
  3. import java.util.Arrays;
  4. import java.util.List;
  5.  
  6. import javax.swing.JButton;
  7. import javax.swing.JFrame;
  8. import javax.swing.JOptionPane;
  9. import javax.swing.SwingUtilities;
  10.  
  11. public class Puzzle15 {
  12.   private JFrame f;
  13.   private JButton[] a;
  14.   private final List<String> xs = new ArrayList<>(Arrays
  15.       .asList(new String[] {
  16.           "1", "2", "3", "4",
  17.           "5", "6", "7", "8",
  18.           "9", "10", "11", "12",
  19.           "13", "14", "15", " "
  20.       }));
  21.   private final int[][] dir = {
  22.       { 1, 4 }, { -1, 1, 4 }, { -1, 1, 4 }, { -1, 4 },
  23.       { -4, 1, 4 }, { -4, -1, 1, 4 }, { -4, -1, 1, 4 }, { -4, -1, 4 },
  24.       { -4, 1, 4 }, { -4, -1, 1, 4 }, { -4, -1, 1, 4 }, { -4, -1, 4 },
  25.       { -4, 1 }, { -4, -1, 1 }, { -4, -1, 1 }, { -4, -1 }
  26.   };
  27.  
  28.   private void swapButtonText(JButton a, JButton b) {
  29.     String t = a.getText();
  30.     a.setText(b.getText());
  31.     b.setText(t);
  32.   }
  33.  
  34.   private boolean finished() {
  35.     List<String> ys = new ArrayList<>(Arrays.stream(a).map(JButton::getText).toList());
  36.     // System.out.println(ys);
  37.     return xs.equals(ys);
  38.   }
  39.  
  40.   private void clickedAction(int i) {
  41.     for (int j : dir[i]) {
  42.       if (a[i + j].getText().equals(" ")) {
  43.         swapButtonText(a[i], a[i + j]);
  44.         break;
  45.       }
  46.     }
  47.     if (finished()) {
  48.       JOptionPane.showMessageDialog(f, "Finish");
  49.     }
  50.   }
  51.  
  52.   public Puzzle15(String[] numStr) {
  53.     a = new JButton[16];
  54.     f = new JFrame("My 15 puzzle");
  55.     f.setSize(250, 250);
  56.     f.getContentPane().setLayout(new GridLayout(4, 4));
  57.     for (int i = 0; i < 16; i++) {
  58.       final int index = i;
  59.       a[index] = new JButton(numStr[index]);
  60.       f.getContentPane().add(a[index]);
  61.       a[index].addActionListener(e -> clickedAction(index));
  62.     }
  63.     f.setVisible(true);
  64.   }
  65.  
  66.   public static void main(final String[] args) {
  67.     SwingUtilities.invokeLater(() -> new Puzzle15(new String[] {
  68.         "1", "2", "3", "4",
  69.         "5", "6", "7", "8",
  70.         "9", "10", "15", "11",
  71.         "13", "14", " ", "12"
  72.     }));
  73.   }
  74. }
  75.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement