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

📄 imagerevertunitpane.java

📁 Java版拼图游戏
💻 JAVA
字号:
/*
 * @(#)ImageRevertUnitPane.java 1.0 03/08/22
 * Copyright 2003 Entao Zhang, All rights reserved.
 */

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.Random;
import java.io.File;

/**
 * 拼图类游戏嵌入功能面板实现.(并临时挂接扫雷).
 */
public class ImageRevertUnitPane extends AbstractUnitPane {
	//存入拼图使用的图像.通过getImage()返回.
	private Image img;
	//默认图像文件打开路径.
	private String path;
	//用于图像遍历的数组.
	private File imageFiles[];
	//保存遗像遍历的当前值.
	private int imageIndex=0;
	//图像文件的最大最小长宽值,超出会自动缩放.太小会打开失败.
	private int minImageWidth=200, minImageHeight=200;
	private int maxImageWidth=800, maxImageHeight=600;
	//当前游戏模式是否是图像游戏方式,是否图像已加载.
	public boolean imageMode=true,isImageLoaded=false;
	//是否对图象自动进行大小调整.是否播放背景音乐.
	private boolean adjust=false, sound=false;
	//播放音乐的类
	private PlaySound playSound;
	
	public ImageRevertUnitPane(boolean isApplet,URL codeBase){
		super(isApplet);
		playSound=new PlaySound(this,codeBase);
		entry();
		chooseGameMode("restorable");
	}

	//下边几个构造函数自动进入游戏准备状态.
	public ImageRevertUnitPane(boolean isApplet,URL codeBase,String gameMode){
		super(isApplet);
		playSound=new PlaySound(this,codeBase);
		entry();
		chooseGameMode(gameMode);
	}

	public ImageRevertUnitPane(boolean isApplet,URL codeBase,String gameMode,
				Image img,int gridX,int gridY){
		super(isApplet);
		entry();
		playSound=new PlaySound(this,codeBase);
		chooseGameMode(gameMode);
		entryInit(img,gridX,gridY);
	}

	public ImageRevertUnitPane(boolean isApplet,URL codeBase,String gameMode,
				File fileName,int gridX,int gridY){
		super(isApplet);
		playSound=new PlaySound(this,codeBase);
		entry();
		chooseGameMode(gameMode);
		entryInit(fileName,gridX,gridY);
	}

	public ImageRevertUnitPane(boolean isApplet,URL codeBase,String gameMode,
				URL url,int gridX,int gridY){
		super(isApplet);
		playSound=new PlaySound(this,codeBase);
		entry();
		chooseGameMode(gameMode);
		entryInit(url,gridX,gridY);
	}

	//初始化.
	public void entry(){
		//changeLookAndFeel("windows");
		x=5; y=5;
		if (!isApplet()){
			setPath(new File(System.getProperty("user.dir")+"/image"));
		}
		if (sound && playSound!=null)
			playSound.loadAndPlay(0);
		setMenus(createMenu());
		Action action=new DefaultKeyAction();
		getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
				KeyStroke.getKeyStroke("ENTER"),"ENTER");
		getActionMap().put("ENTER",action);
	}
	
	//重载以接受几种不同形式的arguments用于图形方式的游戏加载.
	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;
		if (imageMode)
			buildMainPanel(gridX,gridY);
		return true;
	}

	//选择游戏类型.
	public void chooseGameMode(String gameMode){
		if (gameMode.equals("restorable")){
			cm=new RestorableButtonManager(this);
		}else if (gameMode.equals("random")){
			cm=new RandomButtonManager(this);
		}else if (gameMode.equals("inPairs")){
			cm=new InPairsButtonManager(this);
		}else if (gameMode.equals("digital")){
			cm=new DigitalButtonManager(this);
			imageMode=false;
			setAxisLength(3,16);
			setGridSize(6,6);
			return;
		}else if (gameMode.equals("sweepmine")){
			cm=new SweepMineButtonManager(this);
			imageMode=false;
			setAxisLength(8,30);
			setGridSize(16,16);
			return;
		}else{
			return;
		}
		imageMode=true;
		setAxisLength(3,16);
		setGridSize(5,5);
	}

	//生成菜单
	protected JMenu[] createMenu(){
		class MenuActionListener implements ActionListener{
			public void actionPerformed(ActionEvent e) {
				String action=e.getActionCommand();
				if (action=="开始"){
					beConfused();
				}else if (action=="上一幅"){
					fileNavigate(true);
				}else if (action=="下一幅"){
					fileNavigate(false);
				//去掉结束功能
				}else if (action=="结束"){
					System.exit(0);
				}else if (action=="打开"){
					openImageFile();
				}else if (action=="自动调整图像大小"){
					adjust=!adjust;
				}else if (action=="是否播放背景音乐"){
					sound=!sound;
					if (!sound)
						playSound.stop();
					else
						playSound.start();
				}else if (action=="选择背景音乐"){
					if (sound) playSound.chooseSound();
				}else if (action=="Look&Feel"){
					chooseLookAndFeel();
				}else if (action=="关于"){
					showAboutDialog();
				}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");
					}
				}
			}
		}
		MenuActionListener menuAL=new MenuActionListener();
		JMenu m=new JMenu("游戏");
		JMenu m2=new JMenu("设置");
		JMenu m3=new JMenu("帮助");
		JMenuItem item;
		ButtonGroup bg;

		item=new JMenuItem("开始");
		item.addActionListener(menuAL);
		item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F2,0));
		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);
			m.addSeparator();
			item=new JMenuItem("上一幅");
			item.addActionListener(menuAL);
			item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP,0));
			m.add(item);
			item=new JMenuItem("下一幅");
			item.addActionListener(menuAL);
			item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN,0));
			m.add(item);
			m.addSeparator();
			item=new JMenuItem("结束");
			item.addActionListener(menuAL);
			item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,
					ActionEvent.ALT_MASK));
			m.add(item);
		}

		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);
		}

		m2.addSeparator();		
		if (!isApplet()){
			item=new JCheckBoxMenuItem("自动调整图像大小",adjust);
			item.addActionListener(menuAL);
			m2.add(item);
		}
		item=new JCheckBoxMenuItem("是否播放背景音乐",sound);
		item.addActionListener(menuAL);
		m2.add(item);
		m2.addSeparator();
		item=new JMenuItem("选择背景音乐");
		item.addActionListener(menuAL);
		m2.add(item);
		m2.addSeparator();
		item=new JMenuItem("Look&Feel");
		item.addActionListener(menuAL);
		m2.add(item);

		item=new JMenuItem("关于");
		item.addActionListener(menuAL);
		m3.add(item);

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

	//重载父类的该方法.
	protected void buildMainPanel(int gridX, int gridY){
		if (imageMode && !isImageLoaded){
			setConfused(false);
			clearMainPanel();
			return;
		}
		super.buildMainPanel(gridX,gridY);
	}
	
	//重载父类的该方法.
	public void beConfused(){
		if (imageMode && !isImageLoaded) return;
		super.beConfused();
	}

	//返回成员img.
	public Image getImage(){
		return img;
	}

	//默认的键盘Acton.	
	protected class DefaultKeyAction extends AbstractAction{
	   	public void actionPerformed(ActionEvent e) {
			if (isBuilded()){
				if (!isConfused())
					questionToStart();
			}else{
				openImageFile();
			}
		}
	}

	//打开图像文件对话框.
	protected void openImageFile(){
		if (isApplet()) return;
		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) {
			setPath(c.getSelectedFile());
			entryInit(c.getSelectedFile(),x,y);
		}
	}
	
	//设置当前文件路径及路径的图像文件列表.
	private void setPath(File f){
		if (isApplet()) return;
		path=f.getPath();
		File f2=f.isDirectory()? f: f.getParentFile();
		imageFiles=f2.listFiles(
					new java.io.FileFilter(){
			public boolean accept(File f){
				return f.getName().toLowerCase().endsWith(".jpg")
					|| f.getName().toLowerCase().endsWith(".gif")
					|| f.getName().toLowerCase().endsWith(".png");
			}
		});
		imageIndex=0;
		for (int i=0; i<imageFiles.length; i++){
			if (path.equals(imageFiles[i].getPath()))
				imageIndex=i;
		}
	}
	
	//依次选择上一个或下一个图像文件.返回是否选择成功.
	public boolean fileNavigate(boolean reverse){
		if ( !isApplet() && imageMode && imageFiles!=null){
			if (reverse){
				if (imageIndex==0) return false;
				imageIndex--;
			}else{
				if (imageIndex==(imageFiles.length-1)) return false;
				imageIndex++;
			}
			entryInit(imageFiles[imageIndex],x , y);
			return true;
		}else return false;
	}
	
	//调整图像的大小到规定的限定.
	protected Image imageSizeAdjust(Image src){
		int w,h;
		if (src==null ||(w=src.getWidth(null)) <minImageWidth
					||(h=src.getHeight(null))<minImageHeight ){
			return null;
		}
		if (adjust && (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;
	}

	//改变L&F.
	protected void chooseLookAndFeel(){
		String [] landf = {"Metal L&F(默认)", "Windows L&F"};
		String select = (String)JOptionPane.showInputDialog(this,
			"请选择想要使用的L&F外观:","选择Look&Feel",
			JOptionPane.QUESTION_MESSAGE, null, landf, landf[0]);
		if (select!=null) changeLookAndFeel(select=="Metal L&F(默认)"?
			"metal":"windows");
	}

	protected 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);
			}
			if (!isApplet()){
				Window ancestor=SwingUtilities.getWindowAncestor(this);
				if (ancestor!=null){
					ancestor.pack();
				}
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	private void showAboutDialog(){
		JPanel option=new JPanel(new GridLayout(8,1,0,0));
		option.add(new JLabel("版权所有: Entao(Kinno) Zhang"));
		option.add(new JLabel());
		option.add(new JLabel("开发中版本,详细资料见project_information"));
		option.add(new JLabel("和readme文件"));
		option.add(new JLabel());
		option.add(new JLabel("Author: Entao(Kinno) Zhang"));
		option.add(new JLabel("Email : granp@163.com"));
		option.add(new JLabel("Date  : 03/08/20 - 03/08/26"));
		JOptionPane.showMessageDialog(this,option,"关于",JOptionPane.INFORMATION_MESSAGE);
	}
}

⌨️ 快捷键说明

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