Search code examples
javaswingjframesliding-tile-puzzle

8-puzzle images dimensions incorect


Now it works for get my image in my buttons but there is something wrong when i put the parts of the image in the buttons.

I think the fault is in the for loop where i put the parts of my image in the buttons

my images https://i.sstatic.net/8ele1.png https://i.sstatic.net/t7WdQ.jpg

can someone look where i have maked the mistake

i think the problem is in this small piece of code

   ImageIcon sid = new ImageIcon(Puzzle.class.getResource("1.jpg"));
        source = sid.getImage();

        width = sid.getIconWidth();
        height = sid.getIconHeight();



            /** Initialize button array */
         for (int i=0; i<btArray.length;i++){

                  image = createImage(new FilteredImageSource(source.getSource(),
                        new CropImageFilter(i*width/15, i*height/15, 
                            (width/4)+1, height/4)));

    btArray[i]=new JButton(new ImageIcon(image));
}

this is the full project code

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.List;
import java.awt.MediaTracker;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Random;
import static javafx.scene.input.KeyCode.T;

import javax.imageio.ImageIO;
import javax.swing.*;

public class Puzzle extends JFrame implements ActionListener
{
        /** JPanel variable */
        private JPanel centerPanel = new JPanel();
        private JPanel northPanel = new JPanel();
        private JPanel southPanel = new JPanel();

        /** JButton variable */
        private JButton newGame = new JButton("New Game"); 
        private JButton[] btArray = new JButton[15];
            List Collections = new List(15);



        /** JLabel variable */
        private JLabel moves = new JLabel("Moves : ");
        private JLabel label;

        private Container mainPanel = this.getContentPane();
        private int[][] pos;
        private int count;
        private String str;
            private Image source, image;

                   int width, height;



     public static <T> void shuffle(T[] array) {
    Random random = new Random();

    for (int i = array.length - 1 ; i >= 1; --i) {
        int j = random.nextInt(i);
        T temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

        public Puzzle()
    {
            super("Puzzle Game");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            initUI();






        }


        public void initUI()
        {

       /*     pos = new int[][]{
                    {0, 1, 2},
                    {3, 4, 5},
                    {6, 7, 8}

          *///      };
                pos = new int[][]{
                    {0, 1, 2, 3},
                    {4, 5, 6, 7},
                        {8, 9, 10, 11},
                        {12, 13, 14, 15},

                };


         ImageIcon sid = new ImageIcon(Puzzle.class.getResource("1.jpg"));
        source = sid.getImage();

        width = sid.getIconWidth();
        height = sid.getIconHeight();



            /** Initialize button array */
         for (int i=0; i<btArray.length;i++){

                  image = createImage(new FilteredImageSource(source.getSource(),
                        new CropImageFilter(i*width/15, i*height/15, 
                            (width/4)+1, height/4)));

    btArray[i]=new JButton(new ImageIcon(image));
}








            /** North Panel */
            newGame.setFocusable(false);
            newGame.addActionListener(this);
            northPanel.setBackground(Color.red);
            northPanel.add(newGame);
            mainPanel.add(northPanel, BorderLayout.NORTH);

            /** South Panel */
            southPanel.add(moves);
            southPanel.setBackground(Color.LIGHT_GRAY);
            mainPanel.add(southPanel, BorderLayout.SOUTH);

            /** Game Panel */
        centerPanel.setLayout(new GridLayout(4, 4, 0, 0));
            centerPanel.setBackground(Color.BLACK);




            /** Add actionListeners to buttons */
            for (int i = 0; i < 15; i++)
        {
                btArray[i].addActionListener(this);
        }

            newGame();
        mainPanel.revalidate();
        label = new JLabel("");
            label.setBackground(Color.BLACK);
            centerPanel.add(label);
        mainPanel.add(centerPanel);
        }

        public void newGame()
        {

           count = 0;
               shuffle(btArray);

            for (int j = 14; j >= 0; j--)
            {
                centerPanel.remove(btArray[j]);

                       //   JOptionPane.showMessageDialog(null, "pfff");
            }


            for (int j = 14; j >= 0; j--)
            {
                centerPanel.add(btArray[j]);

            }
            centerPanel.revalidate();

        }



        public boolean isFinished()
            {
    {
            if ((btArray[0].getY() == btArray[1].getY() && btArray[1].getY() == btArray[2].getY()) && (btArray[3].getY() == btArray[4].getY() && btArray[4].getY() == btArray[5].getY())
                    && (btArray[6].getY() == btArray[7].getY()))
            {
                if (btArray[0].getX() == btArray[3].getX() && btArray[3].getX() == btArray[6].getX()
                        && btArray[1].getX() == btArray[4].getX() && btArray[4].getX() == btArray[7].getX()
                    && btArray[2].getX() == btArray[5].getX())
                {
                    return true;
                }
        }

            return false;
        }
            }


        public static void main(String[] args)
        {
        Puzzle puz = new Puzzle();
            puz.setBounds(20, 20, 300, 325);
            puz.setVisible(true);
        }




        public void actionPerformed(ActionEvent ae)
        {


            JButton button = (JButton) ae.getSource();
            Dimension size = button.getSize();

                if (isFinished())
            {
            JOptionPane.showMessageDialog(null, "You have Won the game");
            }

            if (ae.getSource() == newGame)
            {
                newGame();

            }



            int labelX = label.getX();
            int labelY = label.getY();
            int buttonX = button.getX();
       int buttonY = button.getY();
            int buttonPosX = buttonX / size.width;
            int buttonPosY = buttonY / size.height;
       int buttonIndex = pos[buttonPosY][buttonPosX];

       if (labelX == buttonX && (labelY - buttonY) == size.height) {

                int labelIndex = buttonIndex + 4;

                centerPanel.remove(buttonIndex);
                centerPanel.add(label, buttonIndex);
                centerPanel.add(button, labelIndex);
                centerPanel.validate();
                count++;

            }

            if (labelX == buttonX && (labelY - buttonY) == -size.height) {

                int labelIndex = buttonIndex - 4;
                centerPanel.remove(labelIndex);
                centerPanel.add(button, labelIndex);
                centerPanel.add(label, buttonIndex);
                centerPanel.validate();
                count++;

            }

        if (labelY == buttonY && (labelX - buttonX) == size.width) {

                int labelIndex = buttonIndex + 1;

                centerPanel.remove(buttonIndex);
            centerPanel.add(label, buttonIndex);
                centerPanel.add(button, labelIndex);
           centerPanel.validate();
           count++;

            }

            if (labelY == buttonY && (labelX - buttonX) == -size.width) {

                int labelIndex = buttonIndex - 1;

                centerPanel.remove(buttonIndex);
                centerPanel.add(label, labelIndex);
                centerPanel.add(button, labelIndex);
                centerPanel.validate();
                count++;

            }

        str = String.valueOf(count);
            moves.setText("Moves : " + str);


        }
    }

Solution

  • The task is to divide the picture into 16 equal parts with the 16th piece missing. The for loop for dividing the image into 16 equal pieces is given below.

    for(int i=0;i<btArray.length;i++){
        image = createImage(new FilteredImageSource(source.getSource(),
              new CropImageFilter((i%4)*width/4, (i/4)*height/4, width/4, height/4)));
    
    
        btArray[i]=new JButton(new ImageIcon(image));
    }
    

    The first two parameters in the CropImageFilter constructer are the x and y coordinates of the top of the rectangle to be extracted i.e.the sub images we are cropping out of the main picture. And the 3rd and 4th parameters are the width and height of the cropped image which should always be width/4 and height/4.