簡體   English   中英

Java滑動拼圖,知道何時完成?

[英]Java sliding puzzle, know when finished?

我正在為課堂制作一個Java滑動拼圖,到目前為止,我能夠裁剪圖片,並且我找到了一種通過動作偵聽器滑動所有按鈕的方法。 但是,在這一點上,我無法理解如何檢查所有按鈕是否都位於正確的位置以祝賀用戶完成操作。 此外,知道該怎么做將使我能夠對圖像進行隨機化和隨機化處理-我尚未實現。

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Image;
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 javax.imageio.ImageIO;
import javax.swing.*;

public class JEightPuzzleFrame extends JFrame implements ActionListener{

    private int width;
    private int height;

    int position[][];
    private Image image1;
    private JPanel centerPanel;
    private JButton[][] listOfBtn = new JButton[3][3];

    public JEightPuzzleFrame(String Title, String Source){

         position = new int[][] {
                 {0, 1, 2}, 
                 {3, 4, 5}, 
                 {6, 7, 8}};    

         centerPanel = new JPanel();
         centerPanel.setLayout(new GridLayout(3, 3, 0, 0)); // 3x3 grid
         add(centerPanel, BorderLayout.CENTER);

         // Read the image from folder
        BufferedImage image=null;
        try{
            image = ImageIO.read(new File(Source));
        }catch(IOException e){
            System.err.println("Image not found");
            System.exit(1);
        }       
        // get the height and width of the image for the window size
         width = image.getWidth();
         height = image.getHeight();

         for ( int i = 0; i < 3; i++) {
             for ( int j = 0; j < 3; j++) {
                 if ( i == 2 && j == 1) {
                     listOfBtn[2][1] = new JButton();
                     centerPanel.add(listOfBtn[2][1]);
                 } else {
                     listOfBtn[i][j] = new JButton();
                     listOfBtn[i][j].addActionListener(this);
                     centerPanel.add(listOfBtn[i][j]);
                     Image source = (Image) image;
                      image1 = createImage(new FilteredImageSource(source.getSource(),
                             new CropImageFilter(j*width/3, i*height/3, 
                                 (width/3)+1, height/3)));
                     listOfBtn[i][j].setIcon(new ImageIcon(image1));
                     listOfBtn[i][j].setVisible(true);
                 }
             }
         }     
        validate();
        setSize(width, height);
        setTitle(Title);
        setResizable(false);
        setLocationRelativeTo(null); // center the image
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);   
    }
    public void shuffle(){

    }
    public static void main(String[] args) {

            new JEightPuzzleFrame("puzzle", "picture.png");
    }
    @Override
    public void actionPerformed(ActionEvent e){

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

        int labelX = listOfBtn[2][1].getX();
        int labelY = listOfBtn[2][1].getY();
        int buttonX = button.getX();
        int buttonY = button.getY();
        int buttonPosX = buttonX / size.width;
        int buttonPosY = buttonY / size.height;
        int buttonIndex = position[buttonPosY][buttonPosX];

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

             int labelIndex = buttonIndex + 3;

             centerPanel.remove(buttonIndex);
             centerPanel.add(listOfBtn[2][1], buttonIndex);
             centerPanel.add(button,labelIndex);
             centerPanel.validate();
        }

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

             int labelIndex = buttonIndex - 3;
             centerPanel.remove(labelIndex);
             centerPanel.add(button,labelIndex);
             centerPanel.add(listOfBtn[2][1], buttonIndex);
             centerPanel.validate();
        }

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

             int labelIndex = buttonIndex + 1;

             centerPanel.remove(buttonIndex);
             centerPanel.add(listOfBtn[2][1], buttonIndex);
             centerPanel.add(button,labelIndex);
             centerPanel.validate();
        }

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

             int labelIndex = buttonIndex - 1;

             centerPanel.remove(buttonIndex);
             centerPanel.add(listOfBtn[2][1], labelIndex);
             centerPanel.add(button,labelIndex);
             centerPanel.validate();
        }
        if(labelY == buttonY && labelX == buttonX) {
            System.out.println("Congrats");
        }
 }
     }

與其裁剪圖像並將其粘貼到構造函數中的按鈕上,不如以一個數組(按預定義的順序)包含裁剪后的圖像列表。 還請記住將名稱/編號與Image關聯(可以通過創建一個不同的類來實現,該類具有Image及其在完整圖像中的原始位置作為該類的成員變量)。

現在,在執行操作的最后,遍歷所有按鈕並獲取附加到其上的圖像的名稱。 如果正確設置了所有圖像(按照原始完整圖像),則其所有名稱(順序)的串聯將始終相同(獨立於所使用的圖像),因此可用於確定最終的“中獎”條件。

隨機排序之前,按鈕的編號會調用容器getComponents存儲數組,以便在每次移動后進行比較

有一組裁剪的圖像和相同數量的按鈕。

BufferedImage image[] = new BufferedImage[noOfImages];
JButton buttons[] = new JButton[image.length];

現在使用java.util.Random類,為圖像生成隨機索引,並將其設置為該索引處的按鈕。

// Randomizing algorithm. I don't expect you to copy the same code. Just for you to understand the logic.

Random rand = new Random(); 
int index;

/ We'll iterate through each button.
for(int i = 0; i < buttons.length; i++) {

        // Pick up a random image.
        do {

            index = rand.nextInt(images.length); // Generate a random number from 0 to images.length -1
            // We will set this index position from the image array to null after setting the icon to a button, so that same picture is not selected for some other button.
        } while(images[index] != null);


        button[i].setIcon(new javax.swing.ImageIcon(images[index])); // Set the image.
        images[index] = null; // coz you don't want the same image to be set to other buttons again.
}
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Image;
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 javax.imageio.ImageIO;
import javax.swing.*;

public class JEightPuzzleFrame extends JFrame implements ActionListener{

    private int width;
    private int height;     
    private int position[][];
    private int count[] = {1,2,3,4,5,6,7,8,9};  // keep track of where the pieces are 
    private Image image1;
    private JPanel centerPanel;
    private JButton[][] listOfBtn = new JButton[3][3];
    private String Source;
    private String Title;
    private int ShuffleCount;

    public JEightPuzzleFrame(String Title, String Source){
        this.Source = Source;
        this.Title = Title;

        ShuffleCount = 0;
        if (ShuffleCount == 0){
            ShuffleCount++;
            set();

        }else{
            shuffle();
        }
    }
    private Image getIcon(int i, int j){
         // Read the image from folder
        BufferedImage image=null;
        try{
            image = ImageIO.read(new File(Source));
        }catch(IOException e){
            System.err.println("Image not found");
            System.exit(1);
        }       
        // get the height and width of the image for the window size
         width = image.getWidth();
         height = image.getHeight(); 
         Image source = (Image) image;
         image1 = createImage(new FilteredImageSource(source.getSource(),
                 new CropImageFilter(j*width/3, i*height/3, 
                     (width/3)+1, height/3)));
         return image1;
    }
    private void set(){
        position = new int[][] {
                {0, 1, 2}, 
                {3, 4, 5}, 
                {6, 7, 8}};

         centerPanel = new JPanel();
         centerPanel.setLayout(new GridLayout(3, 3, 0, 0)); // 3x3 grid
         add(centerPanel, BorderLayout.CENTER);

         // Read the image from folder
        BufferedImage image=null;
        try{
            image = ImageIO.read(new File(Source));
        }catch(IOException e){
            System.err.println("Image not found");
            System.exit(1);
        }       
        // get the height and width of the image for the window size
         width = image.getWidth();
         height = image.getHeight(); 
    /*  for ( int i = 0; i < 3; i++) {
            for ( int j = 0; j < 3; j++) {
                if ( i == 2 && j == 1) {
                    listOfBtn[2][1] = new JButton();
                    centerPanel.add(listOfBtn[2][1]);
                } else {
                 listOfBtn[i][j] = new JButton();
                 listOfBtn[i][j].addActionListener(this);
                 centerPanel.add(listOfBtn[i][j]);
                 Image source = (Image) image;
                  image1 = createImage(new FilteredImageSource(source.getSource(),
                            new CropImageFilter(j*width/3, i*height/3, 
                                (width/3)+1, height/3)));
                    listOfBtn[i][j].setIcon(new ImageIcon(image1));
                    listOfBtn[i][j].setVisible(true);
                }
            }
        } */
         // Set up for initial Game        
         //Button 1
         listOfBtn[0][0] = new JButton();
         centerPanel.add(listOfBtn[0][0]);
         count [0] = 9;
         // Button 2
         listOfBtn[0][1] = new JButton();
         listOfBtn[0][1].addActionListener(this);
         centerPanel.add(listOfBtn[0][1]);
         listOfBtn[0][1].setIcon(new ImageIcon(getIcon(0,0)));
         listOfBtn[0][1].setVisible(true);
         count[1] = 1;
         //Button 3
         listOfBtn[0][2] = new JButton();
         listOfBtn[0][2].addActionListener(this);
         centerPanel.add(listOfBtn[0][2]);
         listOfBtn[0][2].setIcon(new ImageIcon(getIcon(0,1)));
         listOfBtn[0][2].setVisible(true);
         count[2] = 2;
       //Button 4
         listOfBtn[1][0] = new JButton();
         listOfBtn[1][0].addActionListener(this);
         centerPanel.add(listOfBtn[1][0]);
         listOfBtn[1][0].setIcon(new ImageIcon(getIcon(1,1)));
         listOfBtn[1][0].setVisible(true);
         count[3] = 5;
       //Button 5
         listOfBtn[1][1] = new JButton();
         listOfBtn[1][1].addActionListener(this);
         centerPanel.add(listOfBtn[1][1]);
         listOfBtn[1][1].setIcon(new ImageIcon(getIcon(1,2)));
         listOfBtn[1][1].setVisible(true);
         count[4] = 6;
       //Button 6
         listOfBtn[1][2] = new JButton();
         listOfBtn[1][2].addActionListener(this);
         centerPanel.add(listOfBtn[1][2]);
         listOfBtn[1][2].setIcon(new ImageIcon(getIcon(0,2)));
         listOfBtn[1][2].setVisible(true);
         count[5] = 3;
       //Button 7
         listOfBtn[2][0] = new JButton();
         listOfBtn[2][0].addActionListener(this);
         centerPanel.add(listOfBtn[2][0]);
         listOfBtn[2][0].setIcon(new ImageIcon(getIcon(1,0)));
         listOfBtn[2][0].setVisible(true);
         count[6] = 4;
       //Button 8
         listOfBtn[2][1] = new JButton();
         listOfBtn[2][1].addActionListener(this);
         centerPanel.add(listOfBtn[2][1]);
         listOfBtn[2][1].setIcon(new ImageIcon(getIcon(2,0)));
         listOfBtn[2][1].setVisible(true);
         count[7] = 7;
       //Button 9
         listOfBtn[2][2] = new JButton();
         listOfBtn[2][2].addActionListener(this);
         centerPanel.add(listOfBtn[2][2]);
         listOfBtn[2][2].setIcon(new ImageIcon(getIcon(2,1)));
         listOfBtn[2][2].setVisible(true);
         count[8] = 8;

        validate();
        setSize(width, height);
       setTitle(Title);
       setResizable(false);
       setLocationRelativeTo(null); // center the image
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       setVisible(true);
    }
    public void shuffle(){
        set();

    }

    public static void main(String[] args) {
            new JEightPuzzleFrame("Puzzle", "image.png");   
            System.out.println();
    }
    @Override
    public void actionPerformed(ActionEvent e){

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

        int emptyX = listOfBtn[0][0].getX();
        int emptyY = listOfBtn[0][0].getY();

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

        if (emptyX == buttonX && (emptyY - buttonY) == size.height ) {          

             int labelIndex = buttonIndex + 3;

             centerPanel.remove(buttonIndex);
             centerPanel.add(listOfBtn[0][0], buttonIndex);
             centerPanel.add(button,labelIndex);
             centerPanel.validate();

             int a = count[buttonIndex];
             count[buttonIndex] = count[labelIndex];
             count[labelIndex] = a;              
        }

        if (emptyX == buttonX && (emptyY - buttonY) == -size.height ) {

             int labelIndex = buttonIndex - 3;
             centerPanel.remove(labelIndex);
             centerPanel.add(button,labelIndex);
             centerPanel.add(listOfBtn[0][0], buttonIndex);

             centerPanel.validate();
             int a = count[buttonIndex];
             count[buttonIndex] = count[labelIndex];
             count[labelIndex] = a; 
        }

        if (emptyY == buttonY && (emptyX - buttonX) == size.width ) {

             int labelIndex = buttonIndex + 1;        
             centerPanel.remove(buttonIndex);
             centerPanel.add(listOfBtn[0][0], buttonIndex);
             centerPanel.add(button,labelIndex);                                 
             centerPanel.validate(); 
             int a = count[buttonIndex];
             count[buttonIndex] = count[labelIndex];
             count[labelIndex] = a; 
        }

        if (emptyY == buttonY && (emptyX - buttonX) == -size.width ) {

             int labelIndex = buttonIndex - 1;            
             centerPanel.remove(buttonIndex);
             centerPanel.add(listOfBtn[0][0], labelIndex);
             centerPanel.add(button,labelIndex);
             centerPanel.validate();

             int a = count[buttonIndex];
             count[buttonIndex] = count[labelIndex];
             count[labelIndex] = a; 
        } 
        if(count[0] == 1 &&
                count[1] == 2 &&
                count[2] == 3 &&
                count[3] == 4 &&
                count[4] == 5 &&
                count[5] == 6 &&
                count[6] == 7 &&
                count[7] == 8 &&
                count[8] == 9){

            JOptionPane.showMessageDialog(centerPanel,"Good job! Hit ok to scramble");
            shuffle();
         }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM