Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 17 of 17

Thread: Java matching colours game (second click not working)

  1. #1
    Junior Member
    Join Date
    Mar 2019
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Java matching colours game (second click not working)

    Im trying to create a matching buttons game using Java, when a button is clicked on the grid, it should be uncovered, and then you get a second click and this should be uncovered as well. If they both match, both buttons should become black, if not then they should be covered to their initial blank colours (so grey).

    Right now, the first button is covered and not the second.

    Can someone help?
    Last edited by cloud__; March 27th, 2019 at 08:17 AM.

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Java matching colours game (second click not working)

    Could you add the import statements so the code can be compiled for testing?

    Source was removed March 27 from above: Last edited by cloud__; Yesterday at 09:17 AM.
    NOTE: Source is posted in posts #14 and #17
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Sep 2018
    Location
    Virginia
    Posts
    284
    My Mood
    Cool
    Thanks
    0
    Thanked 38 Times in 36 Posts

    Default Re: Java matching colours game (second click not working)

    It appears that if the player guesses incorrectly, the the colors shown are moved to a different button next time. Is that correct?

    Regards,
    Jim

  4. #4
    Junior Member
    Join Date
    Mar 2019
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java matching colours game (second click not working)

    Hi, I have added the imports

    --- Update ---

    Quote Originally Posted by Norm View Post
    Could you add the import statements so the code can be compiled for testing?
    I've just added the imports now

    --- Update ---

    Quote Originally Posted by jim829 View Post
    It appears that if the player guesses incorrectly, the the colors shown are moved to a different button next time. Is that correct?

    Regards,
    Jim
    Nope, so if the player guesses incorrectly, the buttons are coloured back to blank, and the true colours don't change. (So it's not a very hard game to win at)

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Java matching colours game (second click not working)

    How are you trying to debug the code to see why it works the way it does?
    Add some print statements that show the values of variables when they are used and changed. The print out should help.

    Another thing that helps is good comments. The code has no comments making it hard to understand what it is trying to do and how it is going to do it.
    If you don't understand my answer, don't ignore it, ask a question.

  6. #6
    Junior Member
    Join Date
    Mar 2019
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java matching colours game (second click not working)

    I've tried debugging, I put print statements to print out the grid number of the second clicked button and it prints the number correctly. Im just stuck here as to why the second button doesn't change colour like the first does.

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Java matching colours game (second click not working)

    Add some comments describing the logic of the program:
    For example:
    How is the buttonState variable used? What values should it have and when?
    How is colorPicked used?

    Describe what the button states should be and how their colors should change.
    What happens when the first button is clicked?
    What should happen when the next button is clicked?
    If you don't understand my answer, don't ignore it, ask a question.

  8. #8
    Junior Member
    Join Date
    Mar 2019
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java matching colours game (second click not working)

    How is the buttonState variable used? It is set to 1 or 0, 1 if flip is set to true, and 0 if flip is set to false. This buttonState sets whether the blank side or the real colour of the button is shown (so hidden colour)

    What values should it have and when? it should have 0 when the button is black, so when it matches another button. it should be 1 when the real colour is showing

    Describe what the button states should be and how their colors should change. So, the player clicks on two buttons, if they match then they should turn to black, if not then they should be blank. So if match = state should be 0, else should be null (so blank).

    What happens when the first button is clicked? The colour of the button is revealed, the turn increases by 1, and the label changes.

    What should happen when the next button is clicked? The colour of the button is revealed, if it matches with the 1st button then both buttons should become black, if no match then they should be back to blank.

    I'm very stuck here, I dont know why the second button doesnt change colour.

  9. #9
    Member
    Join Date
    Sep 2018
    Location
    Virginia
    Posts
    284
    My Mood
    Cool
    Thanks
    0
    Thanked 38 Times in 36 Posts

    Default Re: Java matching colours game (second click not working)

    I believe the problem you are having has to do with the Event Dispatch Thread. When ever you update the GUI you need to do it within the EDT. If you do the following the current problem should go away.

    @Override
       public void actionPerformed(ActionEvent e) {
     
    	  SwingUtilities.invokeLater(() ->
    	  {
    		 objectMain.buttonClicked(buttonNumber);
    	  });
    	  if (buttonState == 0) {
    		 flip(true);
    	  }
    	  drawButton();
       }

    If you are not using Java 8+ then you will need to wrap the buttonClicked() method call inside a Runnable interface and pass that to the EDT as above.

    However, that is just the first of your issues. You also need to display the colors for a few moments before reverting to the background colors. This will allow the player to see the second color chosen. I suggest you read about painting and also about the Event Dispatch System. Check out the tutorials in my signature below and elsewhere on the web.

    Regards,
    Jim

  10. #10
    Junior Member
    Join Date
    Mar 2019
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java matching colours game (second click not working)

    Yep, this does it. How would I delay it? Im fairly new to Java :/ Thank you.

  11. #11
    Member
    Join Date
    Sep 2018
    Location
    Virginia
    Posts
    284
    My Mood
    Cool
    Thanks
    0
    Thanked 38 Times in 36 Posts

    Default Re: Java matching colours game (second click not working)

    Quite frankly, I'm not certain considering your various buttonState, etc variables and how they interact. I would normally use a Thread.sleep() in the appropriate location. Let me think about it. But the logic is basically as follows:

    click first button and hold on that color.
    click second button and hold on that color.
    wait, say 500 milliseconds.
    then do the comparison and set both appropriately depending on match status.

    What you may want to do is come up with a simple two button program focusing just on that above. Once you understand
    what is going on, incorporate that into the main color game. Experimenting with different parts of a big program is pretty much
    standard practice when coding.

    Here are a few suggestions for other areas of your program.

    mainGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Allows the program to stop nicely when closing the window.

    And you don't need to have your actionListener in the ColorButton class. That is not normally the way you do it since the idea is to listen in the main program for events from other objects. Say you have the actionListener in your main class. You can do the following.
    	@Override
        	public void actionPerformed(ActionEvent e) 
        	{
        		//objectMain.buttonClicked(buttonNumber);  <-- couldn't do this in main because you don't know which button was clicked
                   ColorButton cb = (ColorButton) e.getSource();<-- but this works fine.  It provides the source of the click (i.e which button).
     
     
        		if (cb.buttonState == 0) 
        		{
        			cb.flip(true);
        		}
        		cb.drawButton();
        	}

    Regards,
    Jim

    --- Update ---

    I got my test version to work. What I did was start a separate driver thread which basically sat around monitoring the buttonState and then taking the appropriate action. When the state reached a certain point it set backgrounds and reset all the appropriate state. But the EDT (Event Dispatch Thread) does come into play because you do a lot of stuff while still in the EDT. Here is what I believe contributes to the problem.

    When the system repaints the mainGUI, it is done via an event and does so in the EDT. The actionListener processes events in the same EDT. These must run serially since they're queued in the same thread. Since you stay in the EDT via the button click to do you comparisons and then set the background the background can't be repainted properly until you leave the EDT. This tends to get things out of sync.

    Regards,
    Jim

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Java matching colours game (second click not working)

    I would change the definitions of methods and variables so that this code:
       		if (cb.buttonState == 0) 
        		{
        			cb.flip(true);
        		}
    looked like this:
        		if (cb.buttonState == ChangeColor) 
        		{
        			cb.setColor(HiddenColor);
        		}
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Member
    Join Date
    Sep 2018
    Location
    Virginia
    Posts
    284
    My Mood
    Cool
    Thanks
    0
    Thanked 38 Times in 36 Posts

    Default Re: Java matching colours game (second click not working)

    Definitely! And I also remembered that Colors should be compared with equals. The OP got away with it because the comparisons are static final instances.

    Regards,
    Jim

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Java matching colours game (second click not working)

    We've lost the source code???
    I guess the OP has split.
    Here is my version:
    /* http://www.javaprogrammingforums.com/whats-wrong-my-code/41805-java-matching-colours-game-second-click-not-working.html
     
    When a button is clicked on the grid, it should be uncovered, and then you get a second click and this should be uncovered as well. 
    If they both match, both buttons should become black, if not then they should be covered to their initial blank colours (so grey).
     
    Right now, the first button is covered and not the second.
     
    Note:  Needs lots of comments re the logic / should use enums
    */
     
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.GridLayout;
    import java.util.Random;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.UIManager;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.*;
     
    @SuppressWarnings("serial")
     
    public class OOCW2Last {
        class RandomX {                    //<<<<<<<<< For debugging
           int val = -1;
           public int nextInt(int y) {
              val++;
              if(val > y)
                 val = 0;
              return val;
           }
        } // end testing class
     
        enum WhatColor {Original, Real, Black};       //<<<<<<<< added
     
        	public static final int WIDTH = 4;     //  Changed height???
        	public static final int HEIGHT = 4;    //  5 gave 5x5 square ????
        	public static final int COLOURS = 4;
        	public static final int MAX_PER_COLOUR = 4;
        	public static final int BUT_SIZE = 100;
     
        	int player1Score = 0;
        	int butNumber1 = -1;
        	int butNumber2 = -1;
        	int player2Score = 0;
        	public int turn = 1;       //???? WHAT values???
        	int player = 0;
        	boolean matchedColours;
         int i = 0;  
         JLabel topLabel = new JLabel("Player 0 score: " +player1Score+" choose your first square");
         JLabel botLabel = new JLabel("Player 1 score: " +player2Score+" wait for your turn ");
     
         ColorButton[] arrayButtons = new ColorButton[WIDTH*HEIGHT];
        	Random rand = new Random();
     
          //------------------------------------------------------
        	public static void main(String[] args) 
        	{
     
        		OOCW2Last main = new OOCW2Last();
        	    main.createGUI();
        	}
     
        	public void createGUI()
        	{
     
        	 	 try {
        			   UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName() );
        			 } catch (Exception e) {
        			            e.printStackTrace();
        			 }
     
        		JPanel panelMain = new JPanel();
        		JFrame mainGUI = new JFrame();
             mainGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //<<<<<<<<<<<<
     
     
        		Color[] colors = new Color[8];
     
        	    colors[0] = Color.blue;
        	    colors[1] = Color.yellow;
        	    colors[2] = Color.cyan;
        	    colors[3] = Color.red;
        	    colors[4] = Color.orange;
        	    colors[5] = Color.green;
        	    colors[6] = Color.white;
        	    colors[7] = Color.pink;
     
        	    topLabel.setBackground(Color.GREEN);
        	    topLabel.setOpaque(true);
     
        	    botLabel.setBackground(Color.RED);
        	    botLabel.setOpaque(true);
     
        	    panelMain.setLayout(new GridLayout(WIDTH,HEIGHT));   //  rows, columns
     
     
               for (int i = 0; i < WIDTH*HEIGHT; i++) 
               {
                   arrayButtons[i] = new ColorButton(i, BUT_SIZE, BUT_SIZE, this);            
                   panelMain.add(arrayButtons[i]);
               }
     
               int x = MAX_PER_COLOUR;
               int y = WIDTH*HEIGHT;
               int z;
     
               for (int i = 0; i < COLOURS; i++)
               {
                  	while(x > 0)
                  	{
                  		z = rand.nextInt(y);
                  		while (arrayButtons[z].colorPicked == true){
                  			z = rand.nextInt(y);
                  		}
                  		arrayButtons[z].realButtonColor = colors[i];   
                  		arrayButtons[z].colorPicked = true;
                  		x --;
                  	}
               x = MAX_PER_COLOUR;
               }
     
               mainGUI.getContentPane().add(topLabel, BorderLayout.NORTH);
        	    mainGUI.getContentPane().add(botLabel, BorderLayout.SOUTH);
        	    mainGUI.getContentPane().add(panelMain,BorderLayout.CENTER);
     
        	    mainGUI.pack();
        	    mainGUI.setResizable(false);
        	    mainGUI.setVisible(true);
        	}
     
        	public void message(JLabel botLabel, JLabel topLabel)
        	{	
        		if(turn == 1)		
        		{
        			if(player == 0)
        			{
        				topLabel.setText("Player 0 score: " +player1Score+" choose your first square");
        				botLabel.setText("Player 1 score: " +player2Score+ " wait for your turn ");
        			}
        			else
        			{
        				topLabel.setText("Player 0 score: " +player1Score+" wait for your turn ");
        				botLabel.setText("Player 1 score: " +player2Score+ " choose your first square ");
        			}
     
        		}
     
        		if(turn == 2)		
        		{
        			if(player == 0)
        			{
        				topLabel.setText("Player 0 score: " +player1Score+" choose your second square");
        				botLabel.setText("Player 1 score: " +player2Score+ " wait for your turn ");
        			}
        			else
        			{
        				topLabel.setText("Player 0 score: " +player1Score+" wait for your turn ");
        				botLabel.setText("Player 1 score: " +player2Score+ " choose your second square");
        			}
     
        		}
     
        		if(turn == 3)		
        		{
        			if(player == 0)
        			{
        				if(matchedColours)
        				{
     
        					topLabel.setText("Player 0 score: " +player1Score+" Well Done! Click a square to continue");
        					botLabel.setText("Player 1 score: " +player2Score+ " wait for your turn ");
        				}
        				else
        				{
        					topLabel.setText("Player 0 score: " +player1Score+" Failed! Click a square to continue");
        					botLabel.setText("Player 1 score: " +player2Score+ " wait for your turn ");
        				}
        			}
        			else
        			{
        				if(matchedColours)
        				{
        					topLabel.setText("Player 0 score: " +player2Score+ " wait for your turn ");
        					botLabel.setText("Player 1 score: " +player1Score+" Well Done! Click a square to continue");
        				}
        				else
        				{
        					topLabel.setText("Player 0 score: " +player2Score+ " wait for your turn ");
        					botLabel.setText("Player 1 score: " +player1Score+" Failed! Click a square to continue");
        				}
        			}	
        		}
        	}
     
        	public boolean buttonClicked(int iButton)
        	{		
        		message(botLabel, topLabel);
             System.out.println("bC "+iButton + ", turn="+turn +", btn1="+butNumber1 + ", btn2="+butNumber2); //<<<
             boolean changeColor = true;             // <<<<<<<<< ADDED
     
        		if(turn==1)
        		{
        			butNumber1 = iButton;
        			turn++;
        			message(botLabel, topLabel);
        		}
     
        		else if(turn==2)
        		{
        			turn++;
        			butNumber2 = iButton;
        			message(botLabel, topLabel);
     
        			if(arrayButtons[butNumber1].realButtonColor == (arrayButtons[butNumber2].realButtonColor))
        			{
        				matchedColours = true;
        				arrayButtons[butNumber1].setColor(WhatColor.Black); //flip(false);
        				arrayButtons[butNumber2].setColor(WhatColor.Black); //flip(false);
        				message(botLabel, topLabel);
                   changeColor = false;
        			}
        			else
        			{
        				butNumber2 = iButton;
        				matchedColours = false;
                   //  Need to wait some before changing the colors<<<<<<<<<<<<<<<
        				arrayButtons[butNumber1].setColor(WhatColor.Original); //setBackground(null);
    //    			   arrayButtons[butNumber2].setColor(WhatColor.Original); //setBackground(null);  /**issue may be here, something to do with butNumber2**/
                    (new WaitThenSetColor(butNumber2)).execute();      //<<< second will show for a short time
    //               changeColor = false;      Now want color to be changed so user can see for a few seconds
       				message(botLabel, topLabel);
     
        			}
        			turn = 1;
        		}
        		else if(turn==3)             //????? when
        		{
        			message(botLabel, topLabel);
        		}
             return changeColor;
        	}
     
          class WaitThenSetColor extends SwingWorker<String, Object> {
             int btnId;
             public WaitThenSetColor(int btnId){
                this.btnId = btnId;
             }
              @Override
              public String doInBackground() {
                  try{Thread.sleep(1000);}catch(Exception x){}
                  return "";
              }
     
               @Override
              protected void done() {
                  try {
           				arrayButtons[btnId].setColor(WhatColor.Original);
                  } catch (Exception ignore) {
                  }
              }
          }
     
     
     
       //--------------------------------------------------------------------
       class ColorButton extends JButton implements ActionListener
        {
        	OOCW2Last objectMain;
        	int buttonNumber; 
        	Color realButtonColor;
        	Color drawColor;
        	JFrame guiFrame = new JFrame();
        	int buttonState = 0;                   //????? what values?
        	boolean colorPicked = false;
     
     
        	public ColorButton(int buttonN, int height, int width,
        					OOCW2Last mainClassObject) 
        		{
        		 	 try {
        			    UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName() );
        			 } catch (Exception e) {
        			    e.printStackTrace();
        			 }
     
        			objectMain = mainClassObject;
        			buttonNumber = buttonN;
     
        			this.setBackground(drawColor);
     
        			setMinimumSize( 
        				new Dimension(width, height) );
        			setPreferredSize( 
        				new Dimension(width, height) );
     
        		    addActionListener(this);    
        		}
     
     //   	public void flip(Boolean b)                // Sets real color or sets color black   <<<<  Should be two different methods: setReal and setBlack
          public void setColor(WhatColor wc)
        	{	
    //    		if (b == true) 
             switch(wc) {
             case Real:
        		{
        			drawColor = realButtonColor;
        			buttonState = 1;                                 //??? what does this mean
        			this.setBackground(realButtonColor);
                System.out.println("setColor real "+ buttonNumber + " to " + realButtonColor +", state=1"); //<<<<<<<
       		}	
             break;
     //   		if (b == false) 
             case Black:
        		{
        			drawColor = Color.BLACK;   /*grey*/
        			buttonState = 0;                   //????
        			this.setBackground(Color.BLACK);
                System.out.println("setColor black "+buttonNumber + " to black, state=0"); //<<<<<<<
                // Should this deactivate this button?
                removeActionListener(this);             //<<<<<<<<<<<<<
        		}
             break;
             case Original:
                System.out.println("setColor original "+buttonNumber + ", state="+buttonState); //<<<<<<<
                setBackground(null);
                break;
            }
        	}
     
        	public void setButtonColor(Color realColor)
        	{
        		setBackground(realColor);
        	}
     
        	public void drawButton()
        	{
        		if (buttonState != 0)                        //????
        		{
        			setButtonColor(drawColor);
        		}
        	}
     
        	@Override
        	public void actionPerformed(ActionEvent e) 
        	{
             System.out.println("aP " + buttonNumber + ", state="+buttonState + ", rBtnColor="+realButtonColor);     //<<<<<<<<
        		boolean changeColor = objectMain.buttonClicked(buttonNumber);
     
        		if (buttonState == 0 && changeColor)                //????
        		{
        			setColor(WhatColor.Real); //flip(true);                      //???? only call
        		}
     
     
        		drawButton();
        	}
     
        }
     
    }
    /*
    Running: java.exe -client OOCW2Last
     
    aP 0, state=0, rBtnColor=java.awt.Color[r=0,g=0,b=255]
    bC 0, turn=1, btn1=-1, btn2=-1
    flip true 0 to java.awt.Color[r=0,g=0,b=255], state=1
     
    aP 4, state=0, rBtnColor=java.awt.Color[r=255,g=255,b=0]       << does not match
    bC 4, turn=2, btn1=0, btn2=-1
             >>>set background null
    flip true 4 to java.awt.Color[r=255,g=255,b=0], state=1   <<<<<< should not happen
     
    Running: java.exe -client OOCW2Last
     
    aP 1, state=0, rBtnColor=java.awt.Color[r=0,g=0,b=255]
    bC 1, turn=1, btn1=-1, btn2=-1
    flip true 1 to java.awt.Color[r=0,g=0,b=255], state=1
     
    aP 2, state=0, rBtnColor=java.awt.Color[r=0,g=0,b=255]      <<<<<<< Matches
    bC 2, turn=2, btn1=1, btn2=-1
    flip false 1 to black, state=0                    <<<<< called from bC
    flip false 2 to black, state=0
    flip true 2 to java.awt.Color[r=0,g=0,b=255], state=1      <<<<<<< should not happen   called from aP
     
    0 error(s)
     
    Running: java.exe -client OOCW2Last    <<<<<<<<<< Using Random colors <<<<<<<<<<
     
    aP 1, state=0, rBtnColor=java.awt.Color[r=0,g=255,b=255]
    bC 1, turn=1, btn1=-1, btn2=-1
    setColor real 1 to java.awt.Color[r=0,g=255,b=255], state=1
     
    aP 5, state=0, rBtnColor=java.awt.Color[r=0,g=255,b=255]
    bC 5, turn=2, btn1=1, btn2=-1
    setColor black 1 to black, state=0
    setColor black 5 to black, state=0
     
    aP 0, state=0, rBtnColor=java.awt.Color[r=255,g=255,b=0]
    bC 0, turn=1, btn1=1, btn2=5
    setColor real 0 to java.awt.Color[r=255,g=255,b=0], state=1
    aP 4, state=0, rBtnColor=java.awt.Color[r=255,g=255,b=0]
    bC 4, turn=2, btn1=0, btn2=5
    setColor black 0 to black, state=0
    setColor black 4 to black, state=0
     
    aP 2, state=0, rBtnColor=java.awt.Color[r=0,g=255,b=255]
    bC 2, turn=1, btn1=0, btn2=4
    setColor real 2 to java.awt.Color[r=0,g=255,b=255], state=1
    aP 6, state=0, rBtnColor=java.awt.Color[r=255,g=255,b=0]
    bC 6, turn=2, btn1=2, btn2=4
    setColor original 2, state=1
    setColor real 6 to java.awt.Color[r=255,g=255,b=0], state=1
    setColor original 6, state=1
     
    aP 3, state=0, rBtnColor=java.awt.Color[r=255,g=0,b=0]
    bC 3, turn=1, btn1=2, btn2=6
    setColor real 3 to java.awt.Color[r=255,g=0,b=0], state=1
    aP 7, state=0, rBtnColor=java.awt.Color[r=0,g=255,b=255]
    bC 7, turn=2, btn1=3, btn2=6
    setColor original 3, state=1
    setColor real 7 to java.awt.Color[r=0,g=255,b=255], state=1
    setColor original 7, state=1
     
    0 error(s)
    */
    If you don't understand my answer, don't ignore it, ask a question.

  15. #15
    Member
    Join Date
    Sep 2018
    Location
    Virginia
    Posts
    284
    My Mood
    Cool
    Thanks
    0
    Thanked 38 Times in 36 Posts

    Default Re: Java matching colours game (second click not working)

    Hmm! I actually spent a lot of time looking at this and doing some testing. Some kind of explanation would be nice.

    Regards,
    Jim

  16. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Java matching colours game (second click not working)

    Put this into Google:
    Java matching colours game (second click not working)
    and there is a link to SO that gives a Page not found >>> Did someone post and then delete?
    https://stackoverflow.com/questions/...-matching-game
    3 days ago - I'm currently trying to create a matching buttons game using Java, when a ... But in my code, the first button is covered, but not the second. ... int WIDTH = 4; public static final int HEIGHT = 4; public static final int COLOURS = 4; ...
    If you don't understand my answer, don't ignore it, ask a question.

  17. #17
    Member
    Join Date
    Sep 2018
    Location
    Virginia
    Posts
    284
    My Mood
    Cool
    Thanks
    0
    Thanked 38 Times in 36 Posts

    Default Re: Java matching colours game (second click not working)

    Hah! I just came back on to tell you the same thing. I did Google on his class name -- OOCW2Last. Found a hit at StackOverflow but the page has been deleted. Perhaps this was an assignment and all traces are being removed. Of course, I have the original code.

    Regards,
    Jim

    --- Update ---

    For those following this thread, the posted code had been deleted by the OP. Here is the original code for your reading pleasure and so you may follow the thread.

    Regards,
    Jim

    mport java.awt.*;
    import java.util.*;
     
    import javax.swing.*;
     
    public class OOCW2Last {
     
       public static final int WIDTH		  = 4;
       public static final int HEIGHT		  = 4;
       public static final int COLOURS		  = 4;
       public static final int MAX_PER_COLOUR = 4;
       public static final int BUT_SIZE		  = 100;
       int					   player1Score	  = 0;
       int					   butNumber1	  = -1;
       int					   butNumber2	  = -1;
       int					   player2Score	  = 0;
       public int			   turn			  = 1;
       int					   player		  = 0;
       boolean				   matchedColours;
       int					   i			  = 0;
       JLabel				   topLabel		  = new JLabel(
             "Player 0 score: " + player1Score + " choose your first square");
       JLabel				   botLabel		  =
             new JLabel("Player 1 score: " + player2Score + " wait for your turn ");
     
       ColorButton[]		   arrayButtons	  = new ColorButton[WIDTH * HEIGHT];
       Random				   rand			  = new Random();
     
       public static void main(String[] args) {
     
    	  OOCW2Last main = new OOCW2Last();
    	  main.createGUI();
       }
     
       public void createGUI() {
     
    	  try {
    		 UIManager.setLookAndFeel(
    		       UIManager.getCrossPlatformLookAndFeelClassName());
    	  }
    	  catch (Exception e) {
    		 e.printStackTrace();
    	  }
     
    	  JPanel panelMain = new JPanel();
    	  JFrame mainGUI = new JFrame();
     
    	  Color[] colors = new Color[8];
     
    	  colors[0] = Color.blue;
    	  colors[1] = Color.yellow;
    	  colors[2] = Color.cyan;
    	  colors[3] = Color.red;
    	  colors[4] = Color.orange;
    	  colors[5] = Color.green;
    	  colors[6] = Color.white;
    	  colors[7] = Color.pink;
     
    	  topLabel.setBackground(Color.GREEN);
    	  topLabel.setOpaque(true);
     
    	  botLabel.setBackground(Color.RED);
    	  botLabel.setOpaque(true);
     
    	  panelMain.setLayout(new GridLayout(WIDTH, HEIGHT));
     
    	  for (int i = 0; i < WIDTH * HEIGHT; i++) {
    		 arrayButtons[i] = new ColorButton(i, BUT_SIZE, BUT_SIZE, this);
    		 panelMain.add(arrayButtons[i]);
    	  }
     
    	  int x = MAX_PER_COLOUR;
    	  int y = WIDTH * HEIGHT;
    	  int z;
     
    	  for (int i = 0; i < COLOURS; i++) {
    		 while (x > 0) {
    			z = rand.nextInt(y);
    			while (arrayButtons[z].colorPicked == true) {
    			   z = rand.nextInt(y);
    			}
    			arrayButtons[z].realButtonColor = colors[i];
    			arrayButtons[z].colorPicked = true;
    			x--;
    		 }
    		 x = MAX_PER_COLOUR;
    	  }
     
    	  mainGUI.getContentPane().add(topLabel, BorderLayout.NORTH);
    	  mainGUI.getContentPane().add(botLabel, BorderLayout.SOUTH);
    	  mainGUI.getContentPane().add(panelMain, BorderLayout.CENTER);
     
    	  mainGUI.pack();
    	  mainGUI.setResizable(false);
    	  mainGUI.setVisible(true);
       }
     
       public void message(JLabel botLabel, JLabel topLabel) {
    	  if (turn == 1) {
    		 if (player == 0) {
    			topLabel.setText("Player 0 score: " + player1Score
    			      + " choose your first square");
    			botLabel.setText(
    			      "Player 1 score: " + player2Score + " wait for your turn ");
    		 }
    		 else {
    			topLabel.setText(
    			      "Player 0 score: " + player1Score + " wait for your turn ");
    			botLabel.setText("Player 1 score: " + player2Score
    			      + " choose your first square ");
    		 }
     
    	  }
     
    	  if (turn == 2) {
    		 if (player == 0) {
    			topLabel.setText("Player 0 score: " + player1Score
    			      + " choose your second square");
    			botLabel.setText(
    			      "Player 1 score: " + player2Score + " wait for your turn ");
    		 }
    		 else {
    			topLabel.setText(
    			      "Player 0 score: " + player1Score + " wait for your turn ");
    			botLabel.setText("Player 1 score: " + player2Score
    			      + " choose your second square");
    		 }
     
    	  }
     
    	  if (turn == 3) {
    		 if (player == 0) {
    			if (matchedColours) {
     
    			   topLabel.setText("Player 0 score: " + player1Score
    			         + " Well Done! Click a square to continue");
    			   botLabel.setText("Player 1 score: " + player2Score
    			         + " wait for your turn ");
    			}
    			else {
    			   topLabel.setText("Player 0 score: " + player1Score
    			         + " Failed! Click a square to continue");
    			   botLabel.setText("Player 1 score: " + player2Score
    			         + " wait for your turn ");
    			}
    		 }
    		 else {
    			if (matchedColours) {
    			   topLabel.setText("Player 0 score: " + player2Score
    			         + " wait for your turn ");
    			   botLabel.setText("Player 1 score: " + player1Score
    			         + " Well Done! Click a square to continue");
    			}
    			else {
    			   topLabel.setText("Player 0 score: " + player2Score
    			         + " wait for your turn ");
    			   botLabel.setText("Player 1 score: " + player1Score
    			         + " Failed! Click a square to continue");
    			}
    		 }
    	  }
       }
     
       public void buttonClicked(int iButton) {
    	  message(botLabel, topLabel);
     
    	  if (turn == 1) {
    		 butNumber1 = iButton;
    		 turn++;
    		 message(botLabel, topLabel);
    	  }
     
    	  else if (turn == 2) {
    		 turn++;
    		 butNumber2 = iButton;
    		 message(botLabel, topLabel);
     
    		 if (arrayButtons[butNumber1].realButtonColor == (arrayButtons[butNumber2].realButtonColor)) {
    			matchedColours = true;
    			arrayButtons[butNumber1].flip(false);
    			arrayButtons[butNumber2].flip(false);
    			message(botLabel, topLabel);
    		 }
    		 else {
    			butNumber2 = iButton;
    			matchedColours = false;
    			arrayButtons[butNumber1].setBackground(null);
    			arrayButtons[butNumber2].setBackground(
    			      null); /**
    			              * issue may be here, something to do with butNumber2
    			              **/
    			message(botLabel, topLabel);
     
    		 }
    		 turn = 1;
    	  }
    	  else if (turn == 3) {
    		 message(botLabel, topLabel);
    	  }
     
       }
     
    }

    And the ColorButton class

    import java.awt.*;
    import java.awt.event.*;
     
    import javax.swing.*;
     
    public class ColorButton extends JButton implements ActionListener {
       OOCW2Last objectMain;
       int		 buttonNumber;
       Color	 realButtonColor;
       Color	 drawColor;
       JFrame	 guiFrame	 = new JFrame();
       int		 buttonState = 0;
       boolean	 colorPicked = false;
     
       public ColorButton(int buttonN, int height, int width,
             OOCW2Last mainClassObject) {
    	  try {
    		 UIManager.setLookAndFeel(
    		       UIManager.getCrossPlatformLookAndFeelClassName());
    	  }
    	  catch (Exception e) {
    		 e.printStackTrace();
    	  }
     
    	  objectMain = mainClassObject;
    	  buttonNumber = buttonN;
     
    	  this.setBackground(drawColor);
     
    	  setMinimumSize(new Dimension(width, height));
    	  setPreferredSize(new Dimension(width, height));
     
    	  addActionListener(this);
       }
     
       public void flip(Boolean b) {
    	  if (b == true) {
    		 drawColor = realButtonColor;
    		 buttonState = 1;
    		 this.setBackground(realButtonColor);
    	  }
    	  if (b == false) {
    		 drawColor = Color.BLACK; /* grey */
    		 buttonState = 0;
    		 this.setBackground(Color.BLACK);
    	  }
       }
     
       public void setButtonColor(Color realColor) {
    	  setBackground(realColor);
       }
     
       public void drawButton() {
    	  if (buttonState != 0) {
    		 setButtonColor(drawColor);
    	  }
       }
     
       @Override
       public void actionPerformed(ActionEvent e) {
    	  objectMain.buttonClicked(buttonNumber);
     
    	  if (buttonState == 0) {
    		 flip(true);
    	  }
     
    	  drawButton();
       }
     
    }

Similar Threads

  1. Need help finishing on Matching Game Memory Matching Game
    By Hernanhe1 in forum Member Introductions
    Replies: 1
    Last Post: April 25th, 2013, 05:29 PM
  2. Matching Game
    By Hernanhe1 in forum What's Wrong With My Code?
    Replies: 11
    Last Post: April 25th, 2013, 04:52 PM
  3. Matching Game Help
    By nubshat in forum What's Wrong With My Code?
    Replies: 3
    Last Post: March 2nd, 2013, 03:15 PM
  4. Matching Pairs game - something's not right?
    By sambar89 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: November 9th, 2011, 02:54 PM