如何检查颜色是否匹配? (具有匹配颜色的记忆游戏)

时间:2018-07-19 14:44:39

标签: java swing awt graph-drawing

我有2个数组,用于颜色和按钮

private JButton[] buttons = new JButton[16];
private Color[] c={
    Color.red,Color.yellow,Color.black,Color.magenta,
    Color.blue,Color.green,Color.cyan,Color.pink,
    Color.green,Color.black,Color.red,Color.pink,
    Color.magenta,Color.blue,Color.cyan,Color.yellow
};

布局是

DrawingPanel c=new DrawingPanel();
c.setLayout(new GridLayout(4,4));

当我单击2按钮时,将删除2按钮,那么如何检查2种颜色(按钮背面的颜色)匹配?

public class bl implements ActionListener{
    public void actionPerformed(ActionEvent e){
        Component c = (Component)e.getSource();
        Color c1=Color.black,c2=Color.black;
        if(clickCount == 2){
            c.hide();
            c1 = c.getBackground();
            clickCount--;
        }if(clickCount ==1){
            c.hide();
            c2 = c.getBackground();
            clickCount--;
        }
        if(clickCount == 0 ){
            if(bx == by){
                System.out.println("Corret");
                clickCount=2;
            }
        }else{
            c.show();
        }
    }
} 

Full code

1 个答案:

答案 0 :(得分:0)

您可以扩展Button类,使其能够保留其颜色记录,然后每次获取它进行比较。

该按钮需要保持其颜色或必须记录的颜色的记录。

一般建议兄弟: 1.为变量赋予有意义的名称:

    DrawingPanel c=new DrawingPanel();        
    c.setLayout(new GridLayout(4,4));

这更好,并使您的代码更容易阅读:

    DrawingPanel drawingPanel = new DrawingPanel();
    drawingPanel.setLayout(new GridLayout(4,4));
  1. 在任何地方添加描述性注释也无济于事,使代码更易于阅读。

要扩展Button,您可以执行以下操作:

    public class ColourButton extends JButton{

    private final String colourOfButton;

    public ColourButton(String colourOfButton){

    this.colourOfButton = colourOfButton;
    }

    public String getColour(){
     return colourOfButton;            
     }

      }

然后使用类似的方法检查颜色是否匹配:

     public boolean hasColourMatch(ColourButton colourButton1, ColourButton colourButton2){
          if(colourButton1.getColour().equals(colourButton2.getColour())){
            return true;         
           }
            return false;
      }

希望这会有所帮助。