JAVA实训-连连看(二)

今天主要任务是双消以及做相同判断的消除


1.相比昨天MainFrame类

  //我们将常量采用重构抽取出来  
    private static final int heigh = 800;  
    private static final int width = 700;  
    int buttonMes1=0;
    int buttonMes2=0;
    JButton button1=null;
    JButton button2=null;

我们的监听事件发生了变化

button.addActionListener(new ActionListener() {  
                public void actionPerformed(ActionEvent e) {  
                    // button.setVisible(false);  
                    JButton button = (JButton) e.getSource();  
                    if(button1 == null){
                    	//以前没点击过 
                    	button1=button;
                    	System.out.print("START");
                    }else{
                    	button2=button;
                    	int index1=button1.getY()/button1.getHeight()*gameData.cols+button1.getX()/button1.getWidth();
						int index2=button2.getY()/button2.getHeight()*gameData.rows+button2.getX()/button2.getWidth();
						if(GameRule.isConnext(gameData.data, index1, index2))
                    	{
							button2=button;
							button1.setVisible(false);
							button2.setVisible(false);
                    	
                    	}
						button1=null;
                    	button2=null;
                    }
                }  

  • 求index1,和index2 
  • 其实我们主要是通过按钮的位置来算的 
  • 由于按钮可能不在第二行所以我们算的时候需要考虑乘以一个行数或者列数


2.书写方便

同时

    为了后面的书写我们将this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

     后的部分抽取     为initButton(gameData);  

注:这里我们 

扫描二维码关注公众号,回复: 1661976 查看本文章
  • final GameData gameData=new GameData();  
  • 是因为下面的监听器我们是使用了匿名类, 匿名类如果需要访问外部常量需要定义成final


我们这里涉及到了相同相处的数据处理,新定义一个

GameRule类

package com.icss.linkgame.data;


public class GameRule {	
	/** 判断数组DATA中 制定的两位置之间的图形能否消除 
	 * @param data 数据 
	 * @param index1 第一个位置的数值 
	 * @param index2 第二个位置的数值 
	 * @return
	 */
	public static boolean isConnext(int data[],int index1,int index2)
	{
		if(index1 == index2)
		{
			System.out.print("1");
			return false;
		}
		if(data[index1] == data[index2])
		{
			return true;
		}
		System.out.print("1");
		return false;
		
	}
}


猜你喜欢

转载自blog.csdn.net/qq_37457202/article/details/80667673