Java24点小游戏含GUI

Java小游戏_24点(双模式含GUI)

  • 编辑器:eclipse 2020-09
  • JDK:11.0.8
  • 大二的Java程设选的游戏类题目,就选择了个较简单的24点小游戏,想多捞点分,弄了个双模式GUI,话不多说,直接上码(底部带有相关图片的地址)。
  1. Begin24.java
package aqiyyds;

import java.awt.Color;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.*;

public class Begin24 implements ActionListener,MouseListener {//行为,鼠标监听器
	MainGUI mainMenu;
	String name="";
	JFrame jf=new JFrame("24点游戏-游戏模式");
	JLayeredPane l=jf.getLayeredPane();//运用层级面板,便于背景图片与按钮的显示
	
	JButton b1=new JButton(new ImageIcon("sign/pass.png"));
	JButton b2=new JButton(new ImageIcon("sign/return.png"));
	JButton bO1=new JButton(new ImageIcon("sign/+.png"));
	JButton bO2=new JButton(new ImageIcon("sign/-.png"));
	JButton bO3=new JButton(new ImageIcon("sign/×.png"));
	JButton bO4=new JButton(new ImageIcon("sign/÷.png"));
	JButton bO5=new JButton(new ImageIcon("sign/(.png"));
	JButton bO6=new JButton(new ImageIcon("sign/).png"));
	JButton bO7=new JButton(new ImageIcon("sign/=.png"));
	JButton bO8=new JButton(new ImageIcon("sign/clear.png"));
	
	Card[] card=new Card[] {new Card(), new Card(), new Card(), new Card()};//创建四张扑克
	FindExpression fe=new FindExpression();//运算
	Judge ce=new Judge();//判断规范
	JLabel JLbExpression=new JLabel("");//表达式显示
	String expression;
	JLabel JLbTime=new JLabel("Time : ");//计时器显示
	static Timer timer;
	int time;
	boolean canEnterNumber;	//标志:是否能继续添加数字
	
	public Begin24(MainGUI mainMenu) {
		this.mainMenu=mainMenu;
		JLabel bg=new JLabel(new ImageIcon("sign/Begin24.jpg"));
		bg.setBounds(0,0,800,600);
		
		b1.setBounds(100,500,160,40);
		b1.setBorderPainted(false);
		b1.setContentAreaFilled(false);
		b1.setRolloverIcon(new ImageIcon("sign/clpass.png"));
		b1.addMouseListener(this);
		
		b2.setBounds(320,500,160,40);
		b2.setBorderPainted(false);
		b2.setContentAreaFilled(false);
		b2.setRolloverIcon(new ImageIcon("sign/clreturn.png"));
		b2.addMouseListener(this);
		
		bO1.setBounds(460,250,40,40);
		bO1.setBorderPainted(false);
		bO1.setContentAreaFilled(false);
		bO1.setRolloverIcon(new ImageIcon("sign/cl+.png"));
		bO1.addMouseListener(this);
		
		bO2.setBounds(510,250,40,40);
		bO2.setBorderPainted(false);
		bO2.setContentAreaFilled(false);
		bO2.setRolloverIcon(new ImageIcon("sign/cl-.png"));
		bO2.addMouseListener(this);
		
		bO3.setBorderPainted(false);
		bO3.setContentAreaFilled(false);
		bO3.setRolloverIcon(new ImageIcon("sign/cl×.png"));
		bO3.setBounds(560,250,40,40);
		bO3.addMouseListener(this);
		
		bO4.setBorderPainted(false);
		bO4.setContentAreaFilled(false);
		bO4.setRolloverIcon(new ImageIcon("sign/cl÷.png"));
		bO4.setBounds(610,250,40,40);
		bO4.addMouseListener(this);
		
		bO5.setBorderPainted(false);
		bO5.setContentAreaFilled(false);
		bO5.setRolloverIcon(new ImageIcon("sign/cl(.png"));
		bO5.setBounds(410,250,40,40);
		bO5.addMouseListener(this);
		
		bO6.setBorderPainted(false);
		bO6.setContentAreaFilled(false);
		bO6.setRolloverIcon(new ImageIcon("sign/cl).png"));
		bO6.setBounds(660,250,40,40);
		bO6.addMouseListener(this);
		
		bO7.setBorderPainted(false);
		bO7.setContentAreaFilled(false);
		bO7.setRolloverIcon(new ImageIcon("sign/cl=.png"));
		bO7.setBounds(540,330,40,40);
		bO7.addMouseListener(this);
		
		bO8.setBorderPainted(false);
		bO8.setContentAreaFilled(false);
		bO8.setRolloverIcon(new ImageIcon("sign/clclear.png"));
		bO8.setBounds(540,500,160,40);
		bO8.addMouseListener(this);
		
		JLbExpression.setForeground(Color.BLACK);
		JLbExpression.setBounds(40,200,400,50);
		JLbExpression.setFont(new Font("Arial", Font.BOLD, 50));
		JLbTime.setForeground(Color.WHITE);
		JLbTime.setBounds(20,20,400,50);
		JLbTime.setFont(new Font("Arial", Font.BOLD, 30));
		
		l.add(bg, new Integer(0));
		l.add(b1, new Integer(10));
		l.add(b2, new Integer(10));
		l.add(bO1, new Integer(10));
		l.add(bO2, new Integer(10));
		l.add(bO3, new Integer(10));
		l.add(bO4, new Integer(10));
		l.add(bO5, new Integer(10));
		l.add(bO6, new Integer(10));
		l.add(bO7, new Integer(10));
		l.add(bO8, new Integer(10));
		l.add(JLbExpression, new Integer(10));
		l.add(JLbTime, new Integer(10));
		
		jf.setResizable(false);
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		jf.setSize(800,600);
		jf.setLocationRelativeTo(null);
		jf.setVisible(true);
		start();
	}
	public void start() {//准备扑克组件,进行初始化
		fe.setNumbers(new int[] {0,0,0,0});
		canEnterNumber=true;
		l.remove(card[0]);
		l.remove(card[1]);
		l.remove(card[2]);
		l.remove(card[3]);
		while (fe.getExpression()[0].equals("无解\n                       第1页 / 共1页")) {//判断空就随机更新四张扑克
			JLbExpression.setText("");//用户输入表达式初始化
			expression="";
			for (int i=0; i<4; i++) {
				card[i]=new Card((int)(Math.random()*13+1), (int)(Math.random()*4));
				for (int j=0; j<i; j++) {
					if (card[i].getNumber()==card[j].getNumber() && card[i].getVariety().equals(card[j].getVariety())) {
						continue;
					}
				}
			}
			fe.setNumbers(new int[] {card[0].getNumber(), card[1].getNumber(), card[2].getNumber(), card[3].getNumber()});
		}
		card[0].setBounds(new Rectangle(60, 300, 71, 96));
		card[0].setVisible(true);
		card[1].setBounds(new Rectangle(140, 300, 71, 96));
		card[1].setVisible(true);
		card[2].setBounds(new Rectangle(220, 300, 71, 96));
		card[2].setVisible(true);
		card[3].setBounds(new Rectangle(300, 300, 71, 96));
		card[3].setVisible(true);
		card[0].addMouseListener(this);
		card[1].addMouseListener(this);
		card[2].addMouseListener(this);
		card[3].addMouseListener(this);
		card[0].setEnabled(true);//按钮确认提示
		card[1].setEnabled(true);
		card[2].setEnabled(true);
		card[3].setEnabled(true);
		l.add(card[0], new Integer(10));
		l.add(card[1], new Integer(10));
		l.add(card[2], new Integer(10));
		l.add(card[3], new Integer(10));
		timer=new Timer(1000, this);//设置监听频率为1000ms
		time=card[0].getTime()+card[1].getTime()+card[2].getTime()+card[3].getTime();
		JLbTime.setForeground(Color.WHITE);
		JLbTime.setText("Time : "+time);
		timer.start();//时间计时器开始
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		// TODO Auto-generated method stub
		if (e.getSource()==b1) {
			timer.stop();
			start();
		}
		if(e.getSource()==b2) {
			mainMenu.setVisible(true);
			timer.stop();
			jf.dispose();
		}
		if (canEnterNumber) {
			for (int i=0; i<4; i++) {
				if (e.getSource()==card[i]) {
					JLbExpression.setText(JLbExpression.getText()+card[i].getNumber());
					expression+=card[i].getNumber();
					card[i].setEnabled(false);
					canEnterNumber=false;
				}
			}
		}
		if (e.getSource()==bO1) {
			JLbExpression.setText(JLbExpression.getText()+"+");
			expression+="+";
			canEnterNumber=true;
		}
		if (e.getSource()==bO2) {
			JLbExpression.setText(JLbExpression.getText()+"-");
			expression+="-";
			canEnterNumber=true;
		}
		if (e.getSource()==bO3) {
			JLbExpression.setText(JLbExpression.getText()+"×");
			expression+="*";
			canEnterNumber=true;
		}
		if (e.getSource()==bO4) {
			JLbExpression.setText(JLbExpression.getText()+"÷");
			expression+="/";
			canEnterNumber=true;
		}
		if (e.getSource()==bO5) {
			JLbExpression.setText(JLbExpression.getText()+"(");
			expression+="(";
			canEnterNumber=true;
		}
		if (e.getSource()==bO6) {
			JLbExpression.setText(JLbExpression.getText()+")");
			expression+=")";
			canEnterNumber=true;
		}
		if (e.getSource()==bO7 && !card[0].isEnabled() && !card[1].isEnabled() && !card[2].isEnabled() && !card[3].isEnabled()) {
			ce.setExpression(expression);
			canEnterNumber=true;
			if (!ce.isCorrect()) {
				JOptionPane.showMessageDialog(null,"表达式输入有误,请重新输入","24点游戏-游戏模式",JOptionPane.INFORMATION_MESSAGE);
				JLbExpression.setText("");
				expression="";
				card[0].setEnabled(true);
				card[1].setEnabled(true);
				card[2].setEnabled(true);
				card[3].setEnabled(true);
				return;
			}
			timer.stop();
			if (Math.pow(ce.getDoubleResult()-24,2)<0.000001){//判断精度
				right();
			} 
			else {
				fault();
			}
		}
		if (e.getSource()==bO8) {
			canEnterNumber=true;
			JLbExpression.setText("");
			expression="";
			card[0].setEnabled(true);
			card[1].setEnabled(true);
			card[2].setEnabled(true);
			card[3].setEnabled(true);
		}
	}

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

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

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

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

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		time-=1;
		JLbTime.setText("Time : "+time);
		if (time==15) {
			JLbTime.setForeground(Color.RED);
		}
		if (time<=0) {
			timeIsUp();
		}
	}
	void right() {//正确窗口
		JOptionPane.showMessageDialog(null,"回答正确","24点游戏-游戏模式",JOptionPane.PLAIN_MESSAGE);
		start();
	}

	void fault() {//错误窗口
		JOptionPane.showMessageDialog(null,"回答错误","24点游戏-游戏模式",JOptionPane.PLAIN_MESSAGE);
		start();
	}

	void timeIsUp() {//时间结束窗口
		timer.stop();
		JOptionPane.showMessageDialog(null,"时间到","24点游戏-游戏模式",JOptionPane.PLAIN_MESSAGE);
		start();
	}
}

  1. Card.java
package aqiyyds;

import java.awt.*;
import javax.swing.*;

public  class Card extends JButton {
	int number,variety;
	//给扑克编号,便于练习模式的扑克二维排布
	static String[] VARIETY=new String[]{"黑桃", "红桃", "梅花", "方块"};
	int 黑桃=0;
	int 红桃=1;
	int 梅花=2;
	int 方块=3;
	//只允许一次覆盖
	final private static Icon back=new ImageIcon("image/card/back.png");
	final private static Icon clback=new ImageIcon("image/clcard/back.png");
	private Icon cover,Clcover;

	public Card() {
		super(back);
		cover=back;
		Clcover=clback;
		setRolloverIcon(clback);
		setBorderPainted(false);
		setContentAreaFilled(false);
	}

	public Card(int number) {
		this(number,0);
	}

	public Card(int number, int variety) {
		super(new ImageIcon("image/card/"+VARIETY[variety]+"/"+number+".png"));
		this.number=number;
		this.variety=variety;
		setBorderPainted(false);
		setContentAreaFilled(false);
		if (number<1 || number>13) {
			setIcon(back);
			this.number=0;
			cover=back;
			Clcover=clback;
			setRolloverIcon(clback);
		} else
			cover=getIcon();
			Clcover=new ImageIcon("image/clcard/"+VARIETY[variety]+"/"+number+".jpg");
			setRolloverIcon(Clcover);
	}

	public int getNumber() {
		return number;
	}

	public String getVariety() {
		return VARIETY[variety];
	}
	//含有10以上的扑克,时间增加15秒
	public int getTime() {
		if (number>10) {
			return 30;
		} else
		if (number>0) {
			return 15;
		} else
			return 0;
	}

	public void setBack() {
		setIcon(back);
		setRolloverIcon(clback);
	}
}
  1. FindExpression.java
package aqiyyds;

import java.util.*;

public class FindExpression {
	//以防除法,定义双精度类型结果24
	private double expressionResult = 24;
	
	//练习模式的每页最大行数
	private int maxLine = 10;
	
	//判断计算出错
	private boolean error = true;
	
	//记录四数
	private double numbers[] = new double[4];
	
	public FindExpression() {

	}
	
	//设定方法:用数组存四个数,检测错误
	public void setNumbers(double[] n) {
		if(n.length == 4) {
			error = false;
			numbers = n;
		}
		else
			error = true;
	}	
	public void setNumbers(int[] n) {
		if (n.length == 4) {
			error = false;
			for (int i = 0; i < 4; i++) {
				numbers[i] = n[i];
			}
		} 
		else
			error = true;
	}
	
	//设定每页行数
	public void setMaxLine(int n) {
		if(n > 0) {
			maxLine = n;
		}
	}
	
	//返回每页行数
	public int getMaxLine() {
		return maxLine;
	}
	
	//设定结果
	public void setExpressionResult(double n) {
		expressionResult = n;
	}
	
	//返回结果
	public double getExpressionResult() {
		return expressionResult;
	}
	
	//返回符合条件的表达式
	public String[] getExpression() {
		if (!error) {
			String[] expression=calculate(numbers);
			int n = 0;
			int max=(expression.length-1)/maxLine+1;
			String output[]=new String[max];
			for (int i=0; i<expression.length; i++) {
				if (i%maxLine==0) {
					output[n]="";
				}
				output[n]+=(expression[i]+"\n");
				if ((i+1)%maxLine==0 || i==expression.length-1) {
					output[n]+="                       第"+(++n)+"页 / 共"+max+"页";
				}
			}
			return output;
		} else
			return new String[]{"出错了,输入有误"};
	}
	// cal24(),输出结果为24的表达式 
	private String[] calculate(double[] n) {
		if (n.length != 4)
			return new String[]{"Error"};
		double[] n1 = new double[3];//第一次运算数
		double[] n2 = new double[2];//第二次运算数
		String[] resultString=new String[100]	; 
		int count = 0;
		boolean isRepeat = false;//判断是否重复
		String output = "";
		for (int t1 = 0; t1 < 6; t1++) {//第一次挑选被运算的两个数,共C 4 3 = 6种
			for (int c1 = 0; c1 < 6; c1++) {//运算方式共6种
				for (int t2 = 0; t2 < 3; t2++) {//第二次挑选被运算的两个数,共C 3 2 = 3种
					for (int c2 = 0; c2 < 6; c2++) {
						for (int c3 = 0; c3 < 6; c3++) {//第三次运算
							//测试1 2 3 4 
							
							if ((c1 / 3 == c2 / 3 && (c1 % 3) * ( c2 % 3) != 0) || 
									(c2 / 3 == c3 / 3 && (c2 % 3) * (c3 % 3) != 0) || 
									(c1 / 3 == c3 / 3 && (c1 % 3) * (c3 % 3) != 0 && t2 == 2)) {	
								continue;
							}
							n1 = cal1(n,t1,c1);
							n2 = cal2(n1,t2,c2);
							double result = cal(n2[0],n2[1],c3);
							//处理有除法的情况下的精度问题
							if ((result - expressionResult) < 0.00000001 && (expressionResult - result) < 0.00000001) {
								resultString[count] = calString(n,t1,c1,t2,c2,c3) + "=" + (int)expressionResult;
								for (int i = 0; i < count; i++) {	
									isRepeat=false;
									//equals方法去除完全重复的表达式
									if (resultString[i].equals(resultString[count])) { 
										isRepeat=true;
										break;
									}
								}
								if (c1 == c2 && c2 == c3 && c1 % 3 == 0 && t1 + t2 != 0) {	 
									isRepeat = true;
								}
								if (!isRepeat) {
									count++;
								}
								
							}
						}
					}
				}
			}
		}
		if (count == 0)
			return new String[]{"无解"};
		String[] resultReturn=new String[count];
		System.arraycopy(resultString,0,resultReturn,0,count);
		return resultReturn;
	}

	//cal1(),将4个数计算一次后返回3个数 
	private double[] cal1(double[] n, int t, int c) {	//t为原来的t1,c为原来的c1
		double[] m=new double[3];
		switch (t) {
		case 0:
			m[1] = n[2];
			m[2] = n[3];
			m[0] = cal(n[0],n[1],c);
			break;
		case 1:
			m[1] = n[1];
			m[2] = n[3];
			m[0] = cal(n[0],n[2],c);
			break;
		case 2:
			m[1] = n[1];
			m[2] = n[2];
			m[0] = cal(n[0],n[3],c);
			break;
		case 3:
			m[1] = n[0];
			m[2] = n[3];
			m[0] = cal(n[1],n[2],c);
			break;
		case 4:
			m[1] = n[0];
			m[2] = n[2];
			m[0] = cal(n[1],n[3],c);
			break;
		default:
			m[1] = n[0];
			m[2] = n[1];
			m[0] = cal(n[2],n[3],c);	
		}
		return m;
	}

	//cal2(),将3个数计算一次后返回2个数 
	private double[] cal2(double[] n, int t, int c) {	//t为原来的t2,c为原来的c2
		double[] m = new double[2];
		switch (t) {
		case 0:
			m[1] = n[2];
			m[0] = cal(n[0],n[1],c);
			break;
		case 1:
			m[1] = n[1];
			m[0] = cal(n[0],n[2],c);
			break;
		default:
			m[1] = n[0];
			m[0] = cal(n[1],n[2],c);
		}
		return m;
	}

	//cal(),将2个数计算后返回结果 * 
	private double cal(double n1, double n2, int c) {	//n1,n2为运算数,c为运算类型
		switch (c) {
		case 0:
			return n1 + n2;
		case 1:
			return n1 - n2;
		case 2:
			return n2 - n1;
		case 3:
			return n1 * n2;
		case 4:
			if (n2 == 0)
				return 9999;	//使计算结果必不为24
			else
				return n1 / n2;
		default:
			if (n1 == 0)
				return 9999;	//同上
			else
				return n2 / n1;
		}
	}

	//calString(),输出表达式
	private String calString(double[] n, int t1, int c1, int t2, int c2, int c3) {
		String[] nString = new String[4];
		switch (t1) {
		case 0:
			nString[0] = calString2(""+(int)n[0],""+(int)n[1],c1);
			nString[1] = ""+(int)n[2];
			nString[2] = ""+(int)n[3];
			break;
		case 1:
			nString[0] = calString2(""+(int)n[0],""+(int)n[2],c1);
			nString[1] = ""+(int)n[1];
			nString[2] = ""+(int)n[3];
			break;
		case 2:
			nString[0] = calString2(""+(int)n[0],""+(int)n[3],c1);
			nString[1] = ""+(int)n[1];
			nString[2] = ""+(int)n[2];
			break;
		case 3:
			nString[0] = calString2(""+(int)n[1],""+(int)n[2],c1);
			nString[1] = ""+(int)n[0];
			nString[2] = ""+(int)n[3];
			break;
		case 4:
			nString[0] = calString2(""+(int)n[1],""+(int)n[3],c1);
			nString[1] = ""+(int)n[0];
			nString[2] = ""+(int)n[2];
			break;
		default:
			nString[0] = calString2(""+(int)n[2],""+(int)n[3],c1);
			nString[1] = ""+(int)n[0];
			nString[2] = ""+(int)n[1];
		}
		//特定情况下加上括号:加减运算在前,乘除在后
		if ((c2 / 3 > c1/3 && (t2 != 2 || c2 / 3 == c3 / 3)) || ((c3 / 3 > c1 / 3 + c2 / 3) && t2 == 2) || (c3 == 1 && c1 / 3 == 0))	
			nString[0] = '('+nString[0]+')';
		switch (t2) {
		case 0:
			nString[0]=calString2(nString[0],""+nString[1],c2);
			nString[1]=nString[2];
			break;
		case 1:
			nString[0]=calString2(nString[0],nString[2],c2);
			break;
		default:
			nString[3]=nString[0];
			nString[0]=calString2(nString[1],nString[2],c2);
			nString[1]=nString[3];
		}
		//特定情况下加上括号
		if (c3 / 3 > c2 / 3 || (c3 == 2 && nString[0].indexOf('+') >= 0))	
			nString[0] = '('+nString[0]+')';
		return calString2(nString[0],nString[1],c3);
	}

	//calString2(),根据符号输出一部运算表达式
	private String calString2(String n1, String n2, int c) {
		switch (c) {
		case 0:
			return n1+'+'+n2;
		case 1:
			return n1+'-'+n2;
		case 2:
			return n2+'-'+n1;
		case 3:
			return n1+'*'+n2;
		case 4:
			return n1+'/'+n2;
		default:
			return n2+'/'+n1;
		}
	}
}
  1. Judge.java
package aqiyyds;

import java.util.StringTokenizer;

public class Judge {
	private String expression;//纪录表达式
	private boolean isCorrect;//判断表达式规范
	private double result;//纪录表达式结果
	//初始化对象Work()
	public Judge() {
		expression = "";
		isCorrect = false;
	}
	// setExpression(String<表达式>),输入表达式
	public void setExpression(String input) {
		expression = input;
		isCorrect = check();
		if (isCorrect) {
			result = calStep1();
		} else
			result = 0;
	}

	//getExpression(),输出表达式 
	public String getExpression() {
		return expression;
	}

	//check(),判断表达式规范与否,并自动修正
	private boolean check() {
		char t,tt = expression.charAt(0);
		int left = 0,right = 0;		//计算左右括号,计算修正位数
		boolean hasNum = false;
		StringBuffer s = new StringBuffer(expression); //定义可变字符串
		if (tt == '+' || tt == '-' || tt == '.') {
			s.insert(0,'0');
			right++;
		} else
		if (tt == ')' || tt == '*' || tt == '/') {
			return false;
		}
		for (int i = 0; i < expression.length(); i++) {
			t = tt;
			if (i != expression.length()-1) {
				tt = expression.charAt(i+1);
			} else 
				tt = 'E';//截止位置代表14
			if (t >= '0' && t <= '9') {
				hasNum=true;
				if (tt == '(') {
					s.insert(i+right+1,'*');
					right++;
				}
			} else
			if (t == '(') {
				left++;
				if (tt == '.' || tt == '+' || tt == '-') {
					s.insert(i+right+1,'0');
					right++;
				} else
				if (tt=='*' || tt=='/' || tt==')') {
					return false;
				}
			} else
			if (t == ')') {
				left--;
				if (tt >= '0' && tt <= '9') {
					s.insert(i+right+1,'*');
					right++;
				} else
				if (tt == '.') {
					return false;
				}
			} else
			if (t == '+') {
				if (tt == '+' || tt == '-') {
					s.deleteCharAt(i+right);
					right--;
				} else
				if (tt == '.') {
					s.insert(i+right+1,'0');
					right++;
				} else
				if (tt == '*' || tt == '/' || tt == ')') {
					return false;
				}
			} else
			if (t == '-') {
				if (tt == '+') {
					s.replace(i+right,i+right+2,"-");
					right--;
				} else
				if (tt == '-') {
					s.replace(i+right,i+right+2,"+");
					right--;
				} else
				if (tt == '.') {
					s.insert(i+right+1,'0');
					right++;
				} else
				if (tt == '*' || tt == '/' || tt == ')') {
					return false;
				}
			} else
			if (t == '*' || t == '/') {
				if (tt == ')' || tt == '+' || tt == '-' || tt == '*' || tt == '/') {
					return false;
				}
			} else
			if (t == '.') {
				if (tt == '.') {
					return false;
				} else
				if ( tt < '0' || tt > '9') {
					s.insert(i+right+1,'0');
					right++;
				}
			} else return false;
		} 
		if (left == 0 && hasNum && (expression.indexOf('(') <= expression.indexOf(')'))) {
			expression = s.substring(0);//截去初始位,赋值给表达式
			return true;
		} else
		return false;
	}

	//isCorrect(),返回表达式是否规范
	public boolean isCorrect() {
		return isCorrect;
	}

	//isCorrect(int<数字个数>),返回表达式是否规范
	public boolean isCorrect(int n) {
		if (isCorrect&&this.getNumbers().length==n) {
			return true;
		}
		return false;
	}

	//getNumbers(),返回表达式中数字
	public int[] getNumbers() {
		if (isCorrect) {
			StringTokenizer t = new StringTokenizer(expression,"+-*/()");//分割表达式
			int[] n = new int[t.countTokens()];
			for (int i = 0; i < n.length; i++) {	//若再使用t.countTokens()会有问题,原因不太了解
				n[i] = Integer.parseInt(t.nextToken());//将字符串转为整整传入n
			}
			return n;
		}
		return new int[]{0};
	}

	//getDoubleNumbers(),返回表达式中数字
	public double[] getDoubleNumbers() {
		if (isCorrect) {
			StringTokenizer t=new StringTokenizer(expression,"+-*/()");
			double[] n=new double[t.countTokens()];
			for (int i=0; i<n.length; i++) {	//若再使用t.countTokens()会有问题,原因不太了解
				n[i]=Double.parseDouble(t.nextToken());
			}
			return n;
		}
		return new double[]{0};
	}

	//getResult(),计算表达式的结果,返回int类型 
	public int getResult() {
		if (isCorrect) {
			return (int)result;
		}
		return 0;
	}

	//getDoubleResult(),计算表达式的结果,返回double类型
	public double getDoubleResult() {
		if (isCorrect) {
			return result;
		}
		return 0;
	}

	//calStep1(),计算表达式的第一步,剥除括号
	private double calStep1() {
		int startIndex,endIndex;
		StringBuffer s = new StringBuffer(expression);
		while (s.substring(0).indexOf('(') != -1) {
			endIndex = s.substring(0).indexOf(')');
			startIndex = s.substring(0).lastIndexOf('(',endIndex);
			s.replace(startIndex,endIndex+1,""+calStep2(s.substring(startIndex+1,endIndex)));//将括号内部的算式替换为第二步计算-先乘除再加减
			if (!isCorrect) {
				return 0;
			}
		}
		return calStep2(s.substring(0));
	}

	//calStep2(),计算表达式的第二步,先乘除后加减
	private double calStep2(String expression2) {
		boolean isOdd=true;
		StringTokenizer s = new StringTokenizer(expression2,"+-",true);//通过"+-"分割表达式进行计算
		expression2 = "";
		while (s.hasMoreTokens()) {//确定还有无分割符号"+-"
			if (isOdd) {
				expression2 += (""+calStep3(s.nextToken()));
				isOdd=false;
			}
			else {
				expression2 += s.nextToken();
				isOdd=true;
			}
			if (!isCorrect) {
				return 0;
			}
		}
		return calStep3(expression2);
	}

	//calStep3(),计算表达式的第三步,也就是最后一步,计算加减乘除
	private double calStep3(String expression2) {
		StringTokenizer s = new StringTokenizer(expression2,"+-*/",true);
		double n = Double.parseDouble(s.nextToken());//将s分割字符串转为双精度进行计算
		double nTmp;
		char operator;
		while (s.hasMoreTokens()) {
			operator = s.nextToken().charAt(0);//利用字符操作数进行判断计算
			nTmp = Double.parseDouble(s.nextToken());
			switch (operator) {
				case '+' :
					n += nTmp;
					break;
				case '-' :
					n -= nTmp;
					break;
				case '*' :
					n *= nTmp;
					break;
				default :
					if (nTmp == 0) {
						isCorrect = false;
						return 0;
					} else
						n /= nTmp;
			}
		}
		return n;
	}

	//compareNumbers(int[]<需对比的数组>),比较表达式中的数字是否与给出的数相同
	public boolean compareNumbers(int[] n) {
		if (isCorrect) {
			int[] m = getNumbers();
			if (m.length == n.length) {//利用数组正序排序方法判断得到的表达式数字和要比较的数字是否相同
				java.util.Arrays.sort(n);
				java.util.Arrays.sort(m);
				for (int i = 0; i < n.length; i++) {
					if (n[i] != m[i]) {
						return false;
					}
				}
				return true;
			} else
				return false;
		}
		return false;
	}
}

  1. MainGUI.java
package aqiyyds;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.*;
import java.io.*;


import java.io.BufferedInputStream;
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import javazoom.jl.decoder.JavaLayerException; 
import javazoom.jl.player.*; 
//背景音乐调试
class Play0 extends Thread{
    Player player;
    String music;
    public Play0(String file) {
        this.music = file;
    }
     public void run() {
        try {
            play();     
        } catch (FileNotFoundException | JavaLayerException e) {
             e.printStackTrace();
        }
    }
    public void play() throws FileNotFoundException, JavaLayerException { 
        BufferedInputStream buffer = new BufferedInputStream(new FileInputStream(music)); 
        player = new Player(buffer); 
        player.play(); 
    } 
}

public class MainGUI extends JFrame implements MouseListener {
	
	//修饰主页五大按钮
	JButton b1=new JButton(new ImageIcon("sign/开始游戏.png"));
	JButton b2=new JButton(new ImageIcon("sign/练习模式.png"));
	JButton b3=new JButton(new ImageIcon("sign/游戏规则.png"));
	JButton b4=new JButton(new ImageIcon("sign/结束游戏.png"));
	//JButton b5=new JButton(new ImageIcon("sign/op-music.png"));
	
	public static void main(String[] args) 
	{
		new MainGUI();
		new Play0("music/程响 - 四季予你.wav").start();
	}
	public MainGUI() {
		//调用父类构造方法创建标题
		super("24点游戏");
		
		//新建层次面板l放背景和组件
		JLayeredPane l=getLayeredPane();
		
		//主屏幕组件
		JLabel bc=new JLabel(new ImageIcon("sign/24main.jpg"));
		bc.setBounds(0,0,800,600);
		
		//自定义按钮背景,不需要边框,并透明
		b1.setBorderPainted(false);
		b1.setContentAreaFilled(false);
		b1.setRolloverIcon(new ImageIcon("sign/点击开始游戏.png"));
		b1.setBounds(100,300,160,40);
		b1.addMouseListener(this);
		
		b2.setBorderPainted(false);
		b2.setContentAreaFilled(false);
		b2.setRolloverIcon(new ImageIcon("sign/点击练习模式.png"));
		b2.setBounds(100,350,160,40);
		b2.addMouseListener(this);
	
		b3.setBorderPainted(false);
		b3.setContentAreaFilled(false);
		b3.setRolloverIcon(new ImageIcon("sign/点击游戏规则.png"));
		b3.setBounds(100,400,160,40);
		b3.addMouseListener(this);
		
		b4.setBorderPainted(false);
		b4.setContentAreaFilled(false);
		b4.setRolloverIcon(new ImageIcon("sign/点击结束游戏.png"));
		b4.setBounds(100,450,160,40);
		b4.addMouseListener(this);
		/**
		b5.setBorderPainted(false);
		b5.setContentAreaFilled(false);
		b5.setRolloverIcon(new ImageIcon("sign/cl-music.png"));
		b5.setBounds(700,0,40,40);
		b5.addMouseListener(this);
		**/
		l.add(bc, new Integer(0));
		l.add(b1, new Integer(10));
		l.add(b2, new Integer(10));
		l.add(b3, new Integer(10));
		l.add(b4, new Integer(10));
		//l.add(b5, new Integer(10));
		
		//addMouseListener(this);
		//固屏
		setResizable(false);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(800,600);
		setLocationRelativeTo(null);
		setVisible(true);
	}
	
	@Override
	public void mouseClicked(MouseEvent e) {
		//Play0 play0 = new Play0("music/不才 _ 三体宇宙 - 夜航星(Night Voyager).mp3");
		// TODO Auto-generated method stub
		if (e.getSource()==b1) {
			System.out.println("开始游戏被点击!");
			setVisible(false);	
			new Begin24(this);
			//new Play0("music/不才 _ 三体宇宙 - 夜航星(Night Voyager).mp3").start();
		}
		if (e.getSource()==b2) {
			System.out.println("练习模式被点击!");
			setVisible(false);
			new Practice(this);
		}

		if (e.getSource()==b3) {
			System.out.println("游戏规则被点击!");
			
			//JButton b01=new JButton(new ImageIcon("sign/return.png"));
			JFrame gr=new JFrame("24点游戏-游戏规则");			
			JLabel bc2=new JLabel(new ImageIcon("sign/n游戏规则.jpg"));
			bc2.setBounds(0,0,800,600);
			
			gr.add(bc2);
			
			gr.setResizable(true);
			//gr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			gr.setSize(800,600);
			gr.setLocation(450,200);
			gr.setVisible(true);
			
		}
		if (e.getSource()==b4) {
			System.out.println("结束游戏被点击!");
			System.exit(0);
		}
		/**if (e.getSource()==b5) {
			System.out.println("音频控制被点击!");
			
		}**/
	}

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

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

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

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

  1. Practice.java
package aqiyyds;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Practice implements ActionListener,MouseListener {
	int time;
	Card[][] card;
	boolean[][] isSelected;
	Timer t;
	int cardSelected=0;
	JButton b1=new JButton(new ImageIcon("sign/select.png"));
	JButton b2=new JButton(new ImageIcon("sign/reset.png"));
	JButton b3=new JButton(new ImageIcon("sign/return.png"));
	FindExpression fe=new FindExpression();
	JFrame f=new JFrame("24点游戏-练习模式");
	MainGUI mainMenu;

	public Practice(MainGUI mainMenu) {
		this.mainMenu=mainMenu;
		JLayeredPane l=f.getLayeredPane();
		t=new Timer(2, this);
		card=new Card[13][4];
		isSelected=new boolean[13][4];
		time=0;
		
		//页面布局
		JLabel bg=new JLabel(new ImageIcon("sign/小黄人.jpg"));
		bg.setBounds(0,0,800,600);
		l.add(bg, new Integer(0));
		l.add(b1, new Integer(10));
		l.add(b2, new Integer(10));
		l.add(b3, new Integer(10));
		b1.setBorderPainted(false);
		b1.setContentAreaFilled(false);
		b1.setRolloverIcon(new ImageIcon("sign/clselect.png"));
		b1.setBounds(550,220,160,40);
		b1.addMouseListener(this);
		b2.setBorderPainted(false);
		b2.setContentAreaFilled(false);
		b2.setRolloverIcon(new ImageIcon("sign/clreset.png"));
		b2.setBounds(550,280,160,40);
		b2.addMouseListener(this);
		b3.setBorderPainted(false);
		b3.setContentAreaFilled(false);
		b3.setRolloverIcon(new ImageIcon("sign/clreturn.png"));
		b3.setBounds(550,340,160,40);
		b3.addMouseListener(this);		
		for (int i=0; i<card.length; i++) {
			for (int j=0; j<4; j++) {
				isSelected[i][j]=false;
				card[i][j]=new Card(i+1,j);
				l.add(card[i][j], new Integer(10+i+j*13));
				card[i][j].setBounds(new Rectangle(100+i, 100+j*100, 71, 96));
				card[i][j].setVisible(true);
			}
		}
		f.setResizable(false);
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.setSize(800,600);
		f.setLocationRelativeTo(null);
		f.setVisible(true);
		t.start();
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getSource()==t) {
			t.stop();
			if (time==15*(card.length-1)) {
				for (int i=0; i<card.length; i++) {
					for (int j=0; j<4; j++) {
						card[i][j].addMouseListener(this);
					}
				}
				return;
			}
			time++;
			for (int i=time/15+1; i<card.length; i++) {
				for (int j=0; j<4; j++) {
					card[i][j].setBounds(new Rectangle(100+time, 100+j*100, 71, 96));//绘画矩形框放置扑克牌
				}
			}
			t.setInitialDelay((int)Math.pow((time+1)/100,2)+2);//对扑克牌显示进行延迟处理
			t.restart();//重启定时器
		}
	}

	public void mouseClicked(MouseEvent e) {
		//确认,寻找答案 
		if (e.getSource()==b1 && cardSelected==4) {
			int[] number=new int[4];
			int count=0;
			for (int i=0; i<card.length; i++) {
				for (int j=0; j<4; j++) {
					if (isSelected[i][j]) {
						number[count++]=card[i][j].getNumber();
					}
				}
			}
			fe.setNumbers(number);
			showMessage(fe.getExpression());//调用FindExpression类中的getExpression()方法进行计算
			return;
		}
		//重置
		if (e.getSource()==b2) {
			for (int i=0; i<card.length; i++) {
				for (int j=0; j<4; j++) {
					card[i][j].setBounds(new Rectangle(99+i*15, 100+j*100, 71, 96));
					isSelected[i][j]=false;
				}
			}
			cardSelected=0;
			return;
		}
		//返回主菜单
		if (e.getSource()==b3) {
			mainMenu.setVisible(true);
			f.dispose();
		}
		//牌的选择
		for (int i=0; i<card.length; i++) {
			for (int j=0; j<4; j++) {
				if (e.getSource()==card[i][j]) {
					if (isSelected[i][j]) {
						card[i][j].setBounds(new Rectangle(99+i*15, 100+j*100, 71, 96));
						isSelected[i][j]=false;
						cardSelected--;
					} else if (cardSelected<4) {
						card[i][j].setBounds(new Rectangle(99+i*15, 75+j*100, 71, 96));
						isSelected[i][j]=true;
						cardSelected++;
					}
					break;
				}
			}
		}
	}

	public void mouseEntered(MouseEvent e) {
	}

	public void mouseExited(MouseEvent e) {
	}

	public void mouseReleased(MouseEvent e) {
	}

	public void mousePressed(MouseEvent e) {
	}

	public void showMessage(String[] output) {
		for (int i=0; i<output.length; i++) {
					JOptionPane.showMessageDialog(f,output[i],"24点游戏-练习模式-结果",JOptionPane.PLAIN_MESSAGE);
		}
	}

}

点我提取图片
提取码 77ds
第一次写博客,如有不周,请见谅,将多多改正!谢谢!

你可能感兴趣的:(24点小游戏,javaGUI,java,游戏)