javaswingawtgraph-drawing

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


I got 2 array,for color and button

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

and the Layout is

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

when I clicked 2 button,the 2 button will be remove, then how can I check the 2 color(the color is on button back) is match or not?

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


Solution

  • You could extend the Button class to be able to hold a record of its colour and then get it each time to compare.

    The button needs to keep a record of what colour it has, or something has to anyway.

    General advice bro: 1. Give your variables meaningful names:

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

    This is way better and makes your code far easier to read:

        DrawingPanel drawingPanel = new DrawingPanel();
        drawingPanel.setLayout(new GridLayout(4,4));
    
    1. It never hurts to add descriptive comments everywhere as well, makes code far easier to read.

    To extend Button you could go something like this:

        public class ColourButton extends JButton{
    
        private final String colourOfButton;
    
        public ColourButton(String colourOfButton){
    
        this.colourOfButton = colourOfButton;
        }
    
        public String getColour(){
         return colourOfButton;            
         }
    
          }
    

    Then use something like this to check for colour matches:

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

    Hope this helps..