⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sweepmineunitpane.java

📁 Java版拼图游戏
💻 JAVA
字号:
/*
 * @(#)ImageRevertUnitPane.java 1.0 03/08/05
 * Copyright 2003 张恩涛, All rights reserved.
 */
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
//播放音乐的问题??
//import java.applet.AudioClip;
import java.util.Random;
import java.io.File;
/**
 * 自助拼图游戏.
 */
public class SweepMineUnitPane extends AbstractUnitPane {
	protected Image img;
	protected String path=isApplet()?null:System.getProperty("user.dir");
	//public Component button[];
	public int buttonN[],swap=-1,sum=0;

	protected int minImageWidth=100, minImageHeight=100;
	protected int maxImageWidth=750, maxImageHeight=460;
	public int MIN_GRIDAXIS=3,MAX_GRIDAXIS=16;
	public int x=4,y=4,gridLength=x*y;

	public boolean isConfused=false,isBuilded=false;//,clueFlag=false;
	public boolean imageMode=true,isImageLoaded=false;
	public JScrollPane jp=new JScrollPane();

	public ComponentsManager cm;
	public ImageRevertEventListener cellAL;
	protected ConfuseArray confuse;
	protected ImageDivision division;

	public SweepMineUnitPane(boolean isApplet){
		super(isApplet);
		entry();
	}

	public SweepMineUnitPane(boolean isApplet,Image img,int gridX,int gridY){
		super(isApplet);
		entry();
		entryInit(img,gridX,gridY);
	}

	public SweepMineUnitPane(boolean isApplet,File fileName,int gridX,int gridY){
		super(isApplet);
		entry();
		entryInit(fileName,gridX,gridY);
	}

	public SweepMineUnitPane(boolean isApplet,URL url,int gridX,int gridY){
		super(isApplet);
		entry();
		entryInit(url,gridX,gridY);
	}

	public void entry(){
		//是不是在该panel内部固定住Look&Feel?
		//changeLookAndFeel("windows");
		add(jp,BorderLayout.CENTER);
		setMenus(createMenu());
		division=new RectangleImageDivision();

		chooseGameMode("sweepmine");

		Action action=new DefaultKeyAction();
		getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("ENTER"),"ENTER");
		getActionMap().put("ENTER",action);
	}
	
	public boolean entryInit(File fileName,int gridX,int gridY){
		try{
			return entryInit(fileName.toURL(),gridX,gridY);
		}catch(MalformedURLException e){
			//num
			return false;
		}
	}

	public boolean entryInit(URL url,int gridX,int gridY){
		MediaTracker mt=new MediaTracker(this);
		Image imgTemp=getToolkit().getImage(url);
		mt.addImage(imgTemp,0);
		try {
			mt.waitForID(0);
		}catch (InterruptedException e) {}

		if ((mt.statusID(0,false) & MediaTracker.ERRORED) !=0
			||(imgTemp=imageSizeAdjust(imgTemp))==null){
			//num
			return false;
		}else{
			return entryInit(imgTemp ,gridX ,gridY);
		}
	}

	public boolean entryInit(Image img, int gridX, int gridY){
		this.img= img;
		if (img!=null) isImageLoaded=true;
		buildMainPanel(gridX,gridY);
		return true;
	}

	public void chooseGameMode(String gameMode){
		if (gameMode=="sweepmine"){
			cm=new SweepMineButtonManager(this);
			cellAL=new SweepMineButtonEventListener(this);
			confuse=new SweepMineConfuse();
			imageMode=false;
		}
		buildMainPanel(x,y);
	}

	protected JMenu[] createMenu(){
		class MenuActionListener implements ActionListener{
			public void actionPerformed(ActionEvent e) {
				String action=e.getActionCommand();
				if (action=="开始"){
					beConfused();
				//去掉结束功能
				}else if (action=="结束"){
					System.exit(0);
				//Look&Feel改成只对该panel有效
				}else if (action=="Look&Feel"){
					String [] landf = {"Metal L&F(默认)", "Windows L&F"};
					String select = (String)JOptionPane.showInputDialog(jp,
						"请选择想要使用的L&F外观:","Input Dialog",
						JOptionPane.QUESTION_MESSAGE, null, landf, landf[0]);
					if (select!=null) changeLookAndFeel(select=="Metal L&F(默认)"?
						"metal":"windows");
				}else if ("3*34*45*56*66*8自定".indexOf(action)>=0){
					if (action=="自定"){
						customGridSize();
					}else{
						String strX=action.substring(0,1);
						String strY=action.substring(action.length()-1);
						setGridSize(strX,strY);
					}
				}else if (action.endsWith("方式")){
					if (action=="正常方式"){
						chooseGameMode("restorable");
					}else if(action=="随意方式"){
						chooseGameMode("random");
					}else if(action=="记忆方式"){
						chooseGameMode("inPairs");
					}else if(action=="数字方式"){
						chooseGameMode("digital");
					}else if(action=="扫雷方式"){
						chooseGameMode("sweepmine");
					}
				}else if (action=="打开"){
					openImageFile();
				}
			}
		}
		//菜单美化问题
		MenuActionListener menuAL=new MenuActionListener();
		JMenu m=new JMenu("游戏");
		JMenu m2=new JMenu("设置");
		JMenuItem item;
		ButtonGroup bg;

		item=new JMenuItem("开始");
		item.addActionListener(menuAL);
		item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F2,0));//,ActionEvent.ALT_MASK));
		item.setEnabled(false);
		m.add(item);
		m.addSeparator();
		if (!isApplet()){
			item=new JMenuItem("打开");
			item.addActionListener(menuAL);
			item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,ActionEvent.ALT_MASK));
			m.add(item);
		}
		if (!isApplet()){
			m.addSeparator();
			m.addSeparator();
			item=new JMenuItem("结束");
			item.addActionListener(menuAL);
			item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,ActionEvent.ALT_MASK));
			m.add(item);
		}

		item=new JMenuItem("Look&Feel");
		item.addActionListener(menuAL);
		m2.add(item);
		m2.addSeparator();		

		JMenu m21=new JMenu("格数");
		m2.add(m21);
		bg=new ButtonGroup();
		JRadioButtonMenuItem radio;
		radio=new JRadioButtonMenuItem("自定");
		radio.addActionListener(menuAL);
		radio.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4,0));
		bg.add(radio);
		m21.add(radio);
		m21.addSeparator();		
		String[] radioName={"3*3","4*4","5*5","6*6","6*8"};
		for (int i=0; i<radioName.length; i++){
			radio=new JRadioButtonMenuItem(radioName[i]);
			radio.addActionListener(menuAL);
			m21.add(radio);
			bg.add(radio);
		}
		
		JMenu m22=new JMenu("方式");
		m2.add(m22);
		bg=new ButtonGroup();
		String radioName2[]={"正常方式","随意方式","记忆方式","数字方式","扫雷方式"};
		String key[]={"F5","F6","F7","F8","F9"};
		for (int i=0; i<radioName2.length; i++){
			radio=new JRadioButtonMenuItem(radioName2[i]);
			radio.addActionListener(menuAL);
			if (key[i]!=null)
				radio.setAccelerator(KeyStroke.getKeyStroke(key[i]));
			m22.add(radio);
			bg.add(radio);
		}

		JMenu[] ms={m,m2};
		return ms;
	}

	protected void buildMainPanel(int gridX, int gridY){
		if (imageMode && !isImageLoaded){
			jp.setViewportView(null);
			return;
		}
		x=gridX <MIN_GRIDAXIS ?MIN_GRIDAXIS :(gridX >MAX_GRIDAXIS ?
			MAX_GRIDAXIS :gridX);
		y=gridY <MIN_GRIDAXIS ?MIN_GRIDAXIS :(gridY >MAX_GRIDAXIS ?
			MAX_GRIDAXIS :gridY);
		gridLength=x*y;

		setConfused(false);
		buttonN=new int[gridLength];
		jp.setViewportView(cm.buildMainPanel());
		getMenus()[0].getMenuComponent(0).setEnabled(true);
		if (!isApplet()){
			Window root=SwingUtilities.getWindowAncestor(this);//getRoot(this);
			if (root!=null){
				root.pack();
			}
		}
		isBuilded=true;
	}
	
	public void beConfused(){
		if (!isBuilded ||(imageMode && !isImageLoaded)) return;
		jp.setVisible(false);
		if (isConfused() && swap!=-1){
			cm.swapStateChange(true);
		}
		for (int i=0; i<gridLength; i++) buttonN[i]=i;
		swap=confuse.runConfuse(buttonN,x,y);
		setConfused(true);
		sum=0;
		for (int i=0; i<gridLength; i++) 
			cm.componentStateChange(i);
		if (swap!=-1){
			cm.swapStateChange(false);
		}
		jp.setVisible(true);
	}

	public boolean isConfused(){
		return isConfused;
	}
	
	public void setConfused(boolean isConfused){
		this.isConfused=isConfused;
	}

	public void isDone(){
		for (int i=0; i<gridLength; i++){
			if (buttonN[i]!=i){
				return;
			}
		}
		done();
	}
	
	public void done(){ 
		setConfused(false);
		if (swap!=-1){
			cm.swapStateChange(true);
		}
		for (int i=0; i<gridLength; i++){
			cm.componentStateChange(i);
		}
		JOptionPane.showMessageDialog(this,"全部完成! 重新开始请按F2.","成功了!",
										JOptionPane.INFORMATION_MESSAGE);
	}

	public void setGridSize(String strX,String strY){
		try{
			int x2=Integer.parseInt(strX);
			int y2=Integer.parseInt(strY);
			x=x2;y=y2;
			buildMainPanel(x2,y2);
		}catch(Exception e2){}
	}

	public void customGridSize(){
		JTextField textX=new JTextField(String.valueOf(x),5);
		JTextField textY=new JTextField(String.valueOf(y),5);
		JPanel option=new JPanel(new GridLayout(2,2,0,5));
		option.add(new JLabel("行数:",JLabel.CENTER));
		option.add(textY);
		option.add(new JLabel("列数:",JLabel.CENTER));
		option.add(textX);
		int op=JOptionPane.showConfirmDialog(this,option,"自定义格数",
			JOptionPane.OK_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE);
		if (op==0){
			setGridSize(textX.getText(),textY.getText());
		}else{
			return;
		}
	}

	protected class DefaultKeyAction extends AbstractAction{
	   	public void actionPerformed(ActionEvent e) {
			if (isBuilded){
				if (!isConfused())
					questionToStart();
			}else openImageFile();
		}
	}

	public void questionToStart(){
		int select= JOptionPane.showConfirmDialog(this,
				"确定要开始吗?","开始游戏",JOptionPane.YES_NO_OPTION
				,JOptionPane.QUESTION_MESSAGE);
		if (select==0) beConfused();
	}

	public void openImageFile(){
		JFileChooser c = new JFileChooser(path);
		c.setDialogTitle("请选择一个图片:");
		c.setFileHidingEnabled(false);
		c.setAccessory(ImagePreview.createPreview(c));
		c.setFileFilter(new FileFilter(){
			public boolean accept(File f){
				return f.getName().toLowerCase().endsWith(".jpg")
					|| f.getName().toLowerCase().endsWith(".gif")
					|| f.getName().toLowerCase().endsWith(".png")
					|| f.isDirectory();
			}
			public String getDescription(){
				return "JPG & GIF & PNG Images";
			}
		});

		int rVal = c.showOpenDialog(this);
		if (rVal == JFileChooser.APPROVE_OPTION) {
			path=c.getSelectedFile().getPath();
			entryInit(c.getSelectedFile(),x,y);
		}
	}

	protected Image imageSizeAdjust(Image src){
		int w,h;
		if (src==null ||(w=src.getWidth(null)) <minImageWidth
					||(h=src.getHeight(null))<minImageHeight ){
			return null;
		}
		if (w > maxImageWidth ||h > maxImageHeight){
			return (double)w/maxImageWidth>(double)h/maxImageHeight ?
				(new ImageIcon(src.getScaledInstance(maxImageWidth, -1, Image.SCALE_DEFAULT)).getImage())
				:(new ImageIcon(src.getScaledInstance(-1,maxImageHeight, Image.SCALE_DEFAULT)).getImage());
		}
		return src;
	}

	public void changeLookAndFeel(String laf){
		try {
			UIManager.setLookAndFeel(laf=="metal"
				? UIManager.getCrossPlatformLookAndFeelClassName()
				:"com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
			Component root=SwingUtilities.getRoot(this);
			if (root!=null){
				SwingUtilities.updateComponentTreeUI(root);
			}
			//frame.pack();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -