1. 程式人生 > >Java實現多功能交換拼圖

Java實現多功能交換拼圖

java實現多功能交換拖拽拼圖

不同於傳統的計步拼圖,本專案沒有空白格的存在,依靠滑鼠的點選事件進行圖片的位置交換,可以根據需求選擇本地的圖片,程式碼中預設為F盤路徑下的圖片檔案,可以根據需要進行更改或者去掉預設圖片,該遊戲實現圖片重排,不同矩陣大小的拼圖,其中添加了3*3,4*4,5*5,可以根據需求進行修改。同時可以是實現計時挑戰模式,時間根據矩陣的大小而定,可以自己設定,美中不足的是,存在拼圖成功之後執行緒沒有中斷的問題,讀者可以自行感受修改。本遊戲含有四個類,按鈕Cell類,主控介面類Main,操作類Operate,顯示原圖類TotalPicture。

package 拼圖Dome;
import
java.awt.Rectangle; import javax.swing.Icon; import javax.swing.JButton; @SuppressWarnings("serial") public class Cell extends JButton{ private static int IMAGEWIDTH;//設定按鈕的寬度大小 private static int IMAGEHEIGHT; private int ID; public Cell(Icon icon, int id, int imagewidth, int height)//建構函式初始化,傳入兩個引數,一個是影象的圖示,一個是該按鈕的陣列ID { this
.setIcon(icon); this.ID = id; this.IMAGEWIDTH = imagewidth; this.IMAGEHEIGHT = height; this.setSize(IMAGEWIDTH, IMAGEHEIGHT); } public int getID() { return ID; } public int getX() { return this.getBounds().x; } public int getY
() { return this.getBounds().y; } }
package 拼圖Dome;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import 拼圖Dome.Cell;
public class Operate extends JPanel implements MouseListener{
    public int row;
    public int k=0;
    public int col;//設定這個拼圖的行列
    Cell[] cells;
    public String filepath;
    int ImageWidth;
    int ImageHeight;
    public  Operate()
    {

    }
    public Operate(int row,int col) {
        this.row=row;
        this.col=col;
        this.setLayout(null);
        this.setBounds(154, 20, 400, 400);
        this.setVisible(true);
        cells= new Cell[row*col];//建立一個按鈕物件陣列
    }


    public String getpath() {
        JFileChooser jf = new JFileChooser();  
        jf.showOpenDialog(this);//顯示開啟的檔案對話方塊  
        File f =  jf.getSelectedFile();//使用檔案類獲取選擇器選擇的檔案  
        filepath = f.getAbsolutePath();//返回路徑名 
        return filepath;
    }
          public void init() {
              int num = 0;
              BufferedImage buf=null;
              BufferedImage bufnew = null;
              ImageIcon icon = null;
              int width = 0;
              int height = 0;
              try
              {  

                  ImageIcon image = new ImageIcon(filepath);
                  image.setImage(image.getImage().getScaledInstance(400, 400, Image.SCALE_DEFAULT));
                  buf = new BufferedImage(400, 400,  
                        BufferedImage.TYPE_INT_RGB);
                   Graphics2D biContext = buf.createGraphics();
                   biContext.drawImage(image.getImage(), 0, 0, null);
                  width = 400/col;
                  height = 400/row;
              }catch(Exception e)
              {
                  System.out.println(e);
              }
              for(int i = 0; i < row; i++)
              {
                  for(int j = 0; j < col; j++)
                  {
                      num = i*col+j;//表示當前這個影象的座標id,在陣列中的下標
                      bufnew = buf.getSubimage(width*j, height*i, width, height);
                      icon = new ImageIcon(bufnew);//將影象轉化成圖示
                      cells[num] = new Cell(icon, num, width, height);//新增圖示到每一個BUTTON按鈕上面
                      cells[num].setLocation(width*j, height*i);
                  }
              }
              for(int i = 0; i <cells.length; i++)
              {
                      this.add(cells[i]);//將每一個按鈕新增到當前這個面板上面
                      cells[i].addMouseListener(this);//空白格不新增監聽機制
              }
          } 

          public void initt() {
              int num = 0;
              BufferedImage buf=null;
              BufferedImage bufnew = null;
              ImageIcon icon = null;
              int width = 0;
              int height = 0;
              try
              {  

                  ImageIcon image = new ImageIcon("F://temp/_11.jpg");
                  image.setImage(image.getImage().getScaledInstance(400, 400, Image.SCALE_DEFAULT));
                  buf = new BufferedImage(400, 400,  
                        BufferedImage.TYPE_INT_RGB);
                   Graphics2D biContext = buf.createGraphics();
                   biContext.drawImage(image.getImage(), 0, 0, null);
                  width = 400/col;
                  height = 400/row;
              }catch(Exception e)
              {
                  System.out.println(e);
              }
              for(int i = 0; i < row; i++)
              {
                  for(int j = 0; j < col; j++)
                  {
                      num = i*col+j;//表示當前這個影象的座標id,在陣列中的下標
                      bufnew = buf.getSubimage(width*j, height*i, width, height);
                      icon = new ImageIcon(bufnew);//將影象轉化成圖示
                      cells[num] = new Cell(icon, num, width, height);//新增圖示到每一個BUTTON按鈕上面
                      cells[num].setLocation(width*j, height*i);
                  }
              }
              for(int i = 0; i <cells.length; i++)
              {
                      this.add(cells[i]);//將每一個按鈕新增到當前這個面板上面
                      cells[i].addMouseListener(this);//空白格不新增監聽機制
              }
          } 

          public void OutOfOrder()//亂序----打亂圖片的排布順序
          {
              Random random = new Random();
              for(int i = 0 ; i <cells.length ; i++)
              {
                  int index1 = random.nextInt(cells.length);//cells的長度是9,但是他的上限是9,取不到9,所取值範圍是0-8
                  int index2 = random.nextInt(cells.length);
                  int x = cells[index1].getX();
                  int y = cells[index1].getY();//獲取下標是index1的陣列元素按鈕的座標
                  cells[index1].setLocation(cells[index2].getX(), cells[index2].getY());
                  cells[index2].setLocation(x, y);
              }
          }
          public boolean IsWin()//判斷遊戲玩家是否贏
          {
              for(int i = 0; i <cells.length; i++)
              {
                  int x = cells[i].getX();
                  int y = cells[i].getY();
                  if((x/(400/col)+ (y/(400/row)) *3)!= i)
                  {
                      return false;
                  }
              }
              return true;
          }
          int x1,y1,x2,y2;
          Cell click1,click2;
          public void mouseClicked(MouseEvent e) {
                          if(k==0) {
                             click1=(Cell) e.getSource();
                            x1=click1.getX();
                            y1=click1.getY();
                            k=1;
                          }else {
                            click2=(Cell) e.getSource();
                            x2=click2.getX();
                            y2=click2.getY();
                            click1.setLocation(x2,y2);
                            click2.setLocation(x1, y1);
                            k=0;
                            if(IsWin()) {

                                int choice = JOptionPane.showConfirmDialog(null, "恭喜您過關了是否還來一局?", "提示", JOptionPane.YES_NO_OPTION);
                                if(choice == 0)//表示再來一局
                                {
                                    this.OutOfOrder();
                                }
                                else//表示退出遊戲
                                    System.exit(1);

                          }
                        }
          }
        @Override
        public void mouseEntered(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }
        @Override
        public void mouseExited(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }
        @Override
        public void mousePressed(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }
        @Override
        public void mouseReleased(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }
}
package 拼圖Dome;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class TotalPicture extends JFrame {

    private JPanel contentPane;
    /**
     * Create the frame.
     */
    String filepath;
    public TotalPicture(String filepath) {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 501, 506);
        this.setVisible(true);
        contentPane = new JPanel();
        contentPane.setLayout(null);
        setContentPane(contentPane);

        JLabel lblNewLabel = new JLabel("");
        lblNewLabel.setBounds(10, 40, 465, 420);
        contentPane.add(lblNewLabel);

        int width = 465,height = 420;
        ImageIcon image = new ImageIcon(filepath);
        image.setImage(image.getImage().getScaledInstance(width, height, Image.SCALE_DEFAULT));
        lblNewLabel.setIcon(image);

        JButton button = new JButton("\u5173\u95ED");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
        button.setFont(new Font("宋體", Font.PLAIN, 14));
        button.setBounds(0, 10, 93, 23);
        contentPane.add(button);
    }
}
package 拼圖Dome;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import java.awt.Image;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.concurrent.TimeUnit;
import java.awt.event.ActionEvent;
import javax.swing.JComboBox;
import javax.swing.JTable;
public class Main extends JFrame implements Runnable{
    public  JPanel contentPane=new JPanel();
    /**
     * Create the frame.
     */
    Thread t;
    public  String path;
    int time,count=3;
    public Main() {

        super("拼圖遊戲");
        contentPane.setLayout(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 593, 483);
        setContentPane(contentPane);


        Operate op=new Operate(3,3);
        op.setBounds(154, 20, 400, 400);
        contentPane.add(op);
        op.setVisible(true);
        op.initt();
        path="F://temp/_11.jpg";

        JButton button = new JButton("檢視原圖");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                new TotalPicture(path);
            }
        });
        button.setFont(new Font("宋體", Font.PLAIN, 16));
        button.setBounds(10, 10, 106, 42);
        contentPane.add(button);

        JButton button_2 = new JButton("試玩新圖");
        button_2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                op.removeAll();
                op.repaint();
                path=op.getpath();
                contentPane.repaint();
                op.init();
                }
            }
        );
        button_2.setFont(new Font("宋體", Font.PLAIN, 16));
        button_2.setBounds(10, 75, 106, 42);
        contentPane.add(button_2);



        JButton button_3 = new JButton("圖片重排");
        button_3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                op.OutOfOrder();
            }
        });
        button_3.setFont(new Font("宋體", Font.PLAIN, 16));
        button_3.setBounds(10, 138, 106, 42);
        contentPane.add(button_3);

        JLabel lblNewLabel = new JLabel("\u5207\u5272\u6570\u91CF\uFF1A");
        lblNewLabel.setFont(new Font("宋體", Font.PLAIN, 16));
        lblNewLabel.setBounds(23, 256, 100, 27);
        contentPane.add(lblNewLabel);

        String[] str=new String[3];
        str[0]="3";str[1]="4";str[2]="5";
        JComboBox comboBox = new JComboBox(str);
        comboBox.setBounds(23, 293, 90, 27);
        contentPane.add(comboBox);
        comboBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int t=Integer.parseInt((String) comboBox.getSelectedItem());
                op.removeAll();
                op.row=t;
                op.col=t;
                count=t;
                op.cells=new Cell[t*t];
                contentPane.repaint();
                if(path.equals("F://temp/_11.jpg")) op.initt();
                else  op.init();
            }});

        JButton button_1 = new JButton("挑戰模式");
        button_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) { 
                startT();
            }
        });
        button_1.setFont(new Font("宋體", Font.PLAIN, 16));
        button_1.setBounds(10, 204, 106, 42);
        contentPane.add(button_1);


        JLabel lblNewLabel_1 = new JLabel("\u5012\u8BA1\u65F6\uFF1A");
        lblNewLabel_1.setFont(new Font("宋體", Font.PLAIN, 16));
        lblNewLabel_1.setBounds(23, 330, 67, 27);
        contentPane.add(lblNewLabel_1);


    }
    public void startT() {
        t=new Thread(this);
        t.start();
    }
    public void  running(int k) {
        JTextField jl2 = new JTextField("");
        jl2.setFont(new Font("宋體", Font.PLAIN, 16));
        jl2.setBounds(55, 367, 68, 27);
        contentPane.add(jl2);
        jl2.setText("");
        jl2.setText(String.valueOf(k));

    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        int i = 0;
        if(count==3) i=20;
        if(count==4) i=40;
        if(count==5) i=60;
        for( ;i>=0;i--) {
            try{ running(i);
            Thread.sleep(1000);}catch(Exception e) {
            System.out.println(e.toString()); }
        }   
        int choice = JOptionPane.showConfirmDialog(null, "挑戰失敗,是否繼續遊戲?", "提示", JOptionPane.YES_NO_OPTION);
        if(choice == 0)//表示再來一局
        {
        }
        else//表示退出遊戲
            System.exit(1);
    }

    public static void main(String []args) {
        Main m=new Main();
        m.setVisible(true);
    }
}

這裡寫圖片描述