Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.GridLayout;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.List;
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import javax.swing.JOptionPane;
- import javax.swing.SwingUtilities;
- public class Puzzle15 {
- private JFrame f;
- private JButton[] a;
- private final List<String> xs = new ArrayList<>(Arrays
- .asList(new String[] {
- "1", "2", "3", "4",
- "5", "6", "7", "8",
- "9", "10", "11", "12",
- "13", "14", "15", " "
- }));
- private final int[][] dir = {
- { 1, 4 }, { -1, 1, 4 }, { -1, 1, 4 }, { -1, 4 },
- { -4, 1, 4 }, { -4, -1, 1, 4 }, { -4, -1, 1, 4 }, { -4, -1, 4 },
- { -4, 1, 4 }, { -4, -1, 1, 4 }, { -4, -1, 1, 4 }, { -4, -1, 4 },
- { -4, 1 }, { -4, -1, 1 }, { -4, -1, 1 }, { -4, -1 }
- };
- private void swapButtonText(JButton a, JButton b) {
- String t = a.getText();
- a.setText(b.getText());
- b.setText(t);
- }
- private boolean finished() {
- List<String> ys = new ArrayList<>(Arrays.stream(a).map(JButton::getText).toList());
- // System.out.println(ys);
- return xs.equals(ys);
- }
- private void clickedAction(int i) {
- for (int j : dir[i]) {
- if (a[i + j].getText().equals(" ")) {
- swapButtonText(a[i], a[i + j]);
- break;
- }
- }
- if (finished()) {
- JOptionPane.showMessageDialog(f, "Finish");
- }
- }
- public Puzzle15(String[] numStr) {
- a = new JButton[16];
- f = new JFrame("My 15 puzzle");
- f.setSize(250, 250);
- f.getContentPane().setLayout(new GridLayout(4, 4));
- for (int i = 0; i < 16; i++) {
- final int index = i;
- a[index] = new JButton(numStr[index]);
- f.getContentPane().add(a[index]);
- a[index].addActionListener(e -> clickedAction(index));
- }
- f.setVisible(true);
- }
- public static void main(final String[] args) {
- SwingUtilities.invokeLater(() -> new Puzzle15(new String[] {
- "1", "2", "3", "4",
- "5", "6", "7", "8",
- "9", "10", "15", "11",
- "13", "14", " ", "12"
- }));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement