1

Sorry from my bad english, not native speaker. I am working on a SimonSays Game on Java in a GUI. Im new to coding. I managed to make the aplication work on console, however its been a mess to make it work graphically. The program compares the LinkedLists from the generated sequence (secuenciaSimon) to the one entered by the user throught buttons (secuenciaUsuarioGUI) however, the problem is that the compare method is called by a click on any button so the LinkedList from the generated Sequence by simon is larger that the one introduced by the user.

Yellow Button Code

private void bAmarilloMousePressed(java.awt.event.MouseEvent evt) {
   secuenciaUsuarioGUI.add(3); //Adds  the selection to the LinkedList yellow=3
   System.out.println("Secuencua Usuario GUI:" + secuenciaUsuarioGUI.toString()); 
   comparaSecuencia();
   generaSecuencia();  //Adds another value to the LinkedList
}

Compare code

public boolean comparaSecuencia(){
    for (int i = 0; i < secuenciaSimon.size(); i++) {      

            //Here the pause should be

            if(secuenciaSimon.get(i) != secuenciaUsuarioGUI.get(i)){

                System.out.println("Not equal");
                 return false;
            }

    } 
    System.out.println("Equal");
    puntuacion += 100; //Score
    secuenciaUsuarioGUI.clear(); //Clears the LinkedList From the user
    return true;


}

TL;DR Need to wait for "n" inputs of a button on a GUI before running more code without freezing the program.

Thanks

4

1 回答 1

2

Use an int count variable, set it to 0, and increment it with each button press. Only do your action when the count is adequate, i.e., when it == 3.

For example

// this is a class field
private int count = 0;

// in the code where you create your GUI
button.addActionListener(new ActionListener(){
  public void actionPerformed(ActionEvent evt){
    count++;  // increment count
    // do something with the button pressed, add information to a list
    secuenciaUsuarioGUI.add(/* ?? something ?? */);
    if (count == 3) {  
      // check the sequence
      comparaSecuencia(); // ?? maybe this
      count = 0; // reset
    }
  }
});

A key concept is that you must make your code event-driven. You're not creating a linear console program and so much code that used to be in for loops are no longer in for loops, but rather you will increment counters or change your object's state when an event occurs and then react to that change in state.

Note: if you're listening for the user to press a JButton, don't use a MouseListener but rather an ActionListener.

于 2013-05-05T20:13:18.370 回答