dimanche 27 mars 2016

Can't Check for the Winner in Connect 4 GUI?

So.. I am having trouble checking for the winner in Connect 4. I tried using if statements and for loop but don't know why it isn't checking for winner yet.

I did try returning it true in the IsWin method.. but what it would do is, it would fill every square with Red Color once clicked and it would pop a Message "Player One Won" every I click on the square.

So.. Please help me fix this issue as soon as possible.

My Code So far (full Code, Checking winner in the IsWIN Method):

  private Color playerColor = Color.red;

  private class clikMeButtonListener implements ActionListener{
    public void actionPerformed(ActionEvent event) {

      if (event.getSource() == clickMeOne 
            || event.getSource() == clickMeTwo
            || event.getSource() == clickMeThree
            || event.getSource() == clickMeFour
            || event.getSource() == clickMeFive
            || event.getSource() == clickMeSix
            || event.getSource() == clickMeSeven
         ) {

        JButton button = (JButton)event.getSource();

        int column = 0;
        switch ( button.getName() ) {

          case "clickMeOne" : column = 0; break;
          case "clickMeTwo" : column = 1; break;
          case "clickMeThree" : column = 2; break;
          case "clickMeFour" : column = 3; break;
          case "clickMeFive" : column = 4; break;
          case "clickMeSix" : column = 5; break;
          case "clickMeSeven" : column = 6; break;
        }

        int lastEmptyIndex = -1;

        for ( int i = 0; i < slots[column].length; i++ ) {          
          if ( slots[column][i].getBackground() != Color.white ) {            
            break;
          }
          else {            
            lastEmptyIndex = i;
          }
        }

        if ( lastEmptyIndex != -1 ) {

          slots[column][lastEmptyIndex].setBackground(playerColor);

          if ( IsWin() ) {

            String message = playerColor == Color.red ? " Player One Won!" : " Player Two Won!";
            JOptionPane.showMessageDialog(null, message, " Results ", JOptionPane.INFORMATION_MESSAGE);
          }
          else {

            playerColor = playerColor == Color.red ? Color.yellow : Color.red;  
          }      
        }
      } 
    }

    public boolean IsWin() {   

        int count = 0;

        for (int a = 0; a < 7; a++) {
          for (int b = 0; b < 7; b++) {         
            if (slots[a][b].equals(playerColor)) {
              count++;
              if (count == 4) {              
                return false;
              }            
            } else {
              count = 0;
            }
          }      
        }
        return false;      
      }
    }
}

Aucun commentaire:

Enregistrer un commentaire