1. 程式人生 > 程式設計 >java實現拼圖小遊戲

java實現拼圖小遊戲

一個簡單的拼圖小遊戲,供大家參考,具體內容如下

1.首先設計視圖面板。
2.新增所需要的圖片按鈕。
3.最主要的是設計監聽事件,新增圖片的監聽按鈕,設定移動空白圖片周圍的按鈕。
4.判斷是否成功 。

package sxy;
import java.awt.Choice;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.util.Random;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class PintuGame {
  public static void main(String args[]) {
    new PintuFrame().StartFrame();
  }
}
class PintuFrame extends JFrame {
  private static final long serialVersionUID = 1L;
  // 等級設定
  private static int level = 3;
  // 圖片索引
  private static int index = 0;
  // 圖片數量
  private static int picCount = 2;
  // 開始時間
  private long startTime;
// 初始化小方塊
  private JButton[] buttons;
  // 初始化空方塊
  private JPanel emptyPanel = new JPanel();
  // 初始化監聽類
  private PintuListener listener = new PintuListener();
  // 初始化Panel
  private JPanel panel = new JPanel(null);
  // 圖片預覽
  private JLabel label;
  private String[] imgpath = new String[picCount];
  // 選圖時的圖片路徑
  String path;
  public PintuFrame() {
    for (int i = 0; i < picCount; i++) {
      imgpath[i] = i + ".jpg";
      System.out.println(imgpath[i]);
    }
    path = imgpath[index];
  }
  /**
   * 開始窗體載入
   */```
public void StartFrame() {
    panel.removeAll();
    JButton start = new JButton("開始");// 開始按鈕
    JButton left = new JButton("<");
    JButton right = new JButton(">");
    JLabel selLevel = new JLabel("LV:");
    label = new JLabel(getIcon());// 根據圖示設定標籤
    final Choice choice = new Choice();// 建立選擇器
    choice.add("--初級--");// 新增列表項
    choice.add("--中級--");
    choice.add("--高階--");
    selLevel.setBounds(5,20,20);// 設定座標
    choice.setBounds(28,65,20);
    start.setBounds(93,85,20);
    left.setBounds(178,61,20);
    right.setBounds(239,20);
    label.setBounds(0,22,300,300);// 設定標籤的方位
    panel.add(selLevel);
    panel.add(choice);
    panel.add(start);
    panel.add(left);
    panel.add(right);
    panel.add(label);
    panel.repaint();
    add(panel);
    setTitle("拼圖遊戲");
    setBounds(450,130,322);
    setResizable(false);
    // 新增關閉按鈕
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);
    // 監聽等級選擇
    start.addMouseListener(new MouseAdapter() {
      @Override
      public void mousePressed(MouseEvent e) {
        level = choice.getSelectedIndex() + 3;
        launchFrame();
      }
    });
    // 監聽選圖按鈕 <-
    left.addMouseListener(new MouseAdapter() {
      @Override
      public void mousePressed(MouseEvent e) {
        if (index == 0) {
          index = picCount - 1;
          path = imgpath[index];
        } else {
          path = imgpath[--index];
        }
        panel.remove(label);
        label = new JLabel(getIcon());
        label.setBounds(0,300);
        panel.add(label);
        panel.repaint();
      }
    });
    // 監聽選圖按鈕 ->
    right.addMouseListener(new MouseAdapter() {
      @Override
      public void mousePressed(MouseEvent e) {
        if (index == picCount - 1) {
          index = 0;
          path = imgpath[index];
        } else {
          path = imgpath[++index];
        }
        panel.remove(label);
        label = new JLabel(getIcon());
        label.setBounds(0,300);
        panel.add(label);
        panel.repaint();
      }
    });
  }
  /**
   * 拼圖窗體載入
   */
  public void launchFrame() {
    startTime = System.currentTimeMillis();
    panel.removeAll();
    buttons = new JButton[level * level];
    // 設定圖示組
    Icon[] icon = new PintuFrame().creatIcon(path);
    // 小方塊索引
    int index = 0;
    // 小方塊座標
    int x = 0,y = 0;
    // 設定小方塊位置,圖示,監聽
    for (int i = 0; i < level; i++) {
      for (int j = 0; j < level; j++) {
        // 新增圖示
        buttons[index] = new JButton(icon[index]);
        // 新增監聽
        buttons[index].addMouseListener(listener);
        // 設定位置
        buttons[index].setBounds(x,y,100,100);
        // 新增到panel
        panel.add(buttons[index++]);
        x += 100;
      }
      y += 100;
      x = 0;
    }
    // 移除最後一個小方塊
    panel.remove(buttons[(level * level) - 1]);
    // 設定空方塊位置
    emptyPanel.setBounds((level - 1) * 100,(level - 1) * 100,100);
    // 新增空方塊
    panel.add(emptyPanel);
    panel.repaint();
    add(panel);
    setResizable(false);
    setTitle("拼圖遊戲");
    // 設定大小
    setBounds(450,level * 100,level * 100 + 30);
    // 打亂方格順序
    breakRank();
    // 新增關閉按鈕
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
  // 選圖介面影象
  public Icon getIcon() {
    ImageIcon bi = new ImageIcon(getClass().getClassLoader().getResource(path));
    // 縮放大小並顯示到窗體
    Image image = bi.getImage().getScaledInstance(300,Image.SCALE_REPLICATE);
    return new ImageIcon(image);
  }
  // 打亂方格
  public void breakRank() {
    Random r = new Random();
    int x = 0,y = 0,emptyDir_X = 0,emptyDir_Y = 0;
    // 模擬隨即點選1000次,打亂方格
    for (int i = 0; i < 1000; i++) {
      int rid = r.nextInt(level * level - 1);
      // 獲得該方格按鈕的橫座標
      x = buttons[rid].getBounds().x;
      // 獲得該方格按鈕的縱座標
      y = buttons[rid].getBounds().y;
      // 得到空方格的橫座標
      emptyDir_X = emptyPanel.getBounds().x;
      // 得到空方格的縱座標
      emptyDir_Y = emptyPanel.getBounds().y;
      move(x,emptyDir_X,emptyDir_Y,buttons[rid]);
    }
  }
  // 移動方格
  public void move(int x,int y,int emptyDir_X,int emptyDir_Y,JButton button) {
    // 進行比較果滿足條件則交換
    if (x == emptyDir_X && y - emptyDir_Y == 100) {
      button.setLocation(button.getBounds().x,button.getBounds().y - 100);
    } else if (x == emptyDir_X && y - emptyDir_Y == -100) {
      button.setLocation(button.getBounds().x,button.getBounds().y + 100);
    } else if (x - emptyDir_X == 100 & y == emptyDir_Y) {
      button.setLocation(button.getBounds().x - 100,button.getBounds().y);
    } else if (x - emptyDir_X == -100 && y == emptyDir_Y) {
      button.setLocation(button.getBounds().x + 100,button.getBounds().y);
    } else
      return;
      // 重新設定空方格的位置
    emptyPanel.setLocation(x,y);
  }
  // 判斷是否拼湊成功
  public boolean isFinish() {
    for (int i = 0; i < (level * level) - 1; i++) {
      int x = buttons[i].getBounds().x;
      int y = buttons[i].getBounds().y;
      // 根據座標位置判斷是否拼湊成功 0+0 0+1 ..
      if (y / 100 * level + x / 100 != i)
        return false;
    }
    return true;
  }
  // 事件監聽類
  public class PintuListener extends MouseAdapter {
    @Override
    public void mousePressed(MouseEvent e) {
      JButton button = (JButton) e.getSource();// 獲得滑鼠按的方格按鈕
      int x = button.getBounds().x;// 獲得該方格按鈕的橫座標
      int y = button.getBounds().y;// 獲得該方格按鈕的縱座標
      int nullDir_X = emptyPanel.getBounds().x;// 得到空方格的橫座標
      int nullDir_Y = emptyPanel.getBounds().y;// 得到空方格的縱座標
      move(x,nullDir_X,nullDir_Y,button);
      if (isFinish()) {// 進行是否完成的判斷
        panel.remove(emptyPanel);// 移除最後一個小方塊
        panel.add(buttons[(level * level) - 1]);// 移除最後一個小方塊
        JOptionPane.showMessageDialog(null,"恭喜你,完成拼圖\r\n用時為:" + (System.currentTimeMillis() - startTime) / 1000 + "S");
        for (int i = 0; i < picCount; i++) {// 迴圈撤消滑鼠事件
          buttons[i].removeMouseListener(listener);
        }
        StartFrame();
      }
      repaint();
    }
  }
  // 建立方格圖示組
  public Icon[] creatIcon(String srcImageFile) {
    ImageIcon bi = new ImageIcon(this.getClass().getClassLoader().getResource(srcImageFile));
    // 讀取源影象
    Image image = bi.getImage();
    int index = 0;
    int x = 0,y = 0;
    Icon[] icon = new Icon[level * level];// 根據窗體大小建立圖示數量
    for (int i = 0; i < level; i++) {
      for (int j = 0; j < level; j++) {
        // 從原影象上獲取一個方形位置
        ImageFilter cropFilter = new CropImageFilter(x,100);
        // 擷取方形影象
        Image img = Toolkit.getDefaultToolkit()
            .createImage(new FilteredImageSource(image.getSource(),cropFilter));
        icon[index++] = new ImageIcon(img);
        x += 100;
      }
      y += 100;
      x = 0;
    }
    return icon;
  }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。