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

How I check the color is match or not? (memory game with match color)

我有 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

您可以扩展按钮 class 以能够保存其颜色的记录,然后每次都获取它以进行比较。

按钮需要记录它的颜色,或者无论如何都必须记录。

一般建议兄弟: 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;
      }

希望这对您有所帮助..