如何在对角连接4中检查获胜者?

时间:2016-03-28 19:40:28

标签: java eclipse algorithm if-statement for-loop

所以我在一个名为connect 4的游戏中对角线检查胜利者有问题。我没有任何垂直和水平检查的问题。所以..请你帮我检查对角线?

到目前为止

代码:

import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.LineBorder;

public class connectFourDesign extends JPanel { 

  private static final long serialVersionUID = 1L;   

  // Welcome Screen
  private JLabel lblWelcome;

  // Buttons for Welcome Screen
  private JButton playButton;
  private JButton helpButton; 
  private JButton quitButton;  

  // Game Modes  
  private JButton onePlayer;
  private JButton twoPlayer;

  // Go Back Button
  private JButton goBack;    

  private JButton clickMeOne;
  private JButton clickMeTwo;
  private JButton clickMeThree;
  private JButton clickMeFour;
  private JButton clickMeFive;
  private JButton clickMeSix;
  private JButton clickMeSeven;  

  // Grid xSize,ySize and 2D Array
  private int ysize = 7;
  private int xsize = 8;
  private JButton[][] slots;  

  public static void main(String[] args) {

    JFrame frame = new JFrame(" Connect Four ");
    frame.setSize(500, 500);
    frame.getContentPane().add(new connectFourDesign());
    frame.setVisible(true);
    frame.setResizable(false);
  }  

  public connectFourDesign () { 

    setBackground(Color.black);        

    lblWelcome = new JLabel (" Connect 4 ", SwingConstants.CENTER);    
    lblWelcome.setFont(new Font("Astron Boy Rg", Font.ITALIC, 90));
    lblWelcome.setForeground(Color.white);
    add(lblWelcome);
    lblWelcome.setVisible(true);

    playButton = new JButton (" Play ");
    playButton.setFont(new Font("Astron Boy Rg", Font.ITALIC, 75));
    playButton.setBackground(Color.black);
    playButton.setForeground(Color.GREEN);
    add(playButton);
    playButton.setVisible(true);
    playButton.addActionListener(new playButtonListener());

    onePlayer = new JButton (" 1 Player ");
    onePlayer.setFont(new Font("Astron Boy Rg", Font.ITALIC, 55));
    onePlayer.setBackground(Color.black);
    onePlayer.setForeground(Color.GREEN);
    add(onePlayer);
    onePlayer.setVisible(false);
    onePlayer.addActionListener(new onePlayerButtonListener());

    twoPlayer = new JButton (" 2 Player ");
    twoPlayer.setFont(new Font("Astron Boy Rg", Font.ITALIC, 55));
    twoPlayer.setBackground(Color.black);
    twoPlayer.setForeground(Color.GREEN);
    add(twoPlayer);
    twoPlayer.setVisible(false);
    twoPlayer.addActionListener(new twoPlayerButtonListener());     

    helpButton = new JButton ( " Help ");
    helpButton.setFont(new Font("Astron Boy Rg", Font.ITALIC, 75));
    helpButton.setBackground(Color.black);
    helpButton.setForeground(Color.magenta);
    add(helpButton);
    helpButton.setVisible(true);
    helpButton.addActionListener(new helpListener()); 

    quitButton = new JButton ( " Quit ");
    quitButton.setFont(new Font("Astron Boy Rg", Font.ITALIC, 75));
    quitButton.setBackground(Color.black);
    quitButton.setForeground(Color.orange);
    add(quitButton);
    quitButton.setVisible(true); 
    quitButton.addActionListener(new CloseListener());     

    goBack = new JButton ( " Go Back "); 
    goBack.setFont(new Font("Astron Boy Rg", Font.ITALIC, 60));
    goBack.setBackground(Color.black);
    goBack.setForeground(Color.BLUE);
    add(goBack);
    goBack.setVisible(false); 
    goBack.addActionListener(new goBackButtonListener());

    clickMeOne = new JButton ();
    clickMeOne.setFont(new Font("Astron Boy Rg", Font.ITALIC, 20));
    clickMeOne.setBackground(Color.gray);
    clickMeOne.setForeground(Color.CYAN);
    clickMeOne.setName("clickMeOne");
    add(clickMeOne);
    clickMeOne.setVisible(false); 
    clickMeOne.addActionListener(new clikMeOneButtonListener());

    clickMeTwo = new JButton ();
    clickMeTwo.setFont(new Font("Astron Boy Rg", Font.ITALIC, 20));
    clickMeTwo.setBackground(Color.gray);
    clickMeTwo.setForeground(Color.CYAN);
    clickMeTwo.setName("clickMeTwo");
    add(clickMeTwo);
    clickMeTwo.setVisible(false); 
    clickMeTwo.addActionListener(new clikMeOneButtonListener());

    clickMeThree = new JButton ();
    clickMeThree.setFont(new Font("Astron Boy Rg", Font.ITALIC, 20));
    clickMeThree.setBackground(Color.gray);
    clickMeThree.setForeground(Color.CYAN);
    clickMeThree.setName("clickMeThree");
    add(clickMeThree);
    clickMeThree.setVisible(false); 
    clickMeThree.addActionListener(new clikMeOneButtonListener());

    clickMeFour = new JButton ();
    clickMeFour.setFont(new Font("Astron Boy Rg", Font.ITALIC, 20));
    clickMeFour.setBackground(Color.gray);
    clickMeFour.setForeground(Color.CYAN);
    clickMeFour.setName("clickMeFour");
    add(clickMeFour);
    clickMeFour.setVisible(false); 
    clickMeFour.addActionListener(new clikMeOneButtonListener());

    clickMeFive = new JButton ();
    clickMeFive.setFont(new Font("Astron Boy Rg", Font.ITALIC, 20));
    clickMeFive.setBackground(Color.gray);
    clickMeFive.setForeground(Color.CYAN);
    clickMeFive.setName("clickMeFive");
    add(clickMeFive);
    clickMeFive.setVisible(false); 
    clickMeFive.addActionListener(new clikMeOneButtonListener());

    clickMeSix = new JButton ();
    clickMeSix.setFont(new Font("Astron Boy Rg", Font.ITALIC, 20));
    clickMeSix.setBackground(Color.gray);
    clickMeSix.setForeground(Color.CYAN);
    clickMeSix.setName("clickMeSix");
    add(clickMeSix);
    clickMeSix.setVisible(false);  
    clickMeSix.addActionListener(new clikMeOneButtonListener());

    clickMeSeven = new JButton ();
    clickMeSeven.setFont(new Font("Astron Boy Rg", Font.ITALIC, 20));
    clickMeSeven.setBackground(Color.gray);
    clickMeSeven.setForeground(Color.CYAN);
    clickMeSeven.setName("clickMeSeven");
    add(clickMeSeven);
    clickMeSeven.setVisible(false); 
    clickMeSeven.addActionListener(new clikMeOneButtonListener());

    clickMeOne.setIcon(new ImageIcon("kdevelop_down.png"));   
    clickMeTwo.setIcon(new ImageIcon("kdevelop_down.png"));
    clickMeThree.setIcon(new ImageIcon("kdevelop_down.png"));
    clickMeFour.setIcon(new ImageIcon("kdevelop_down.png"));
    clickMeFive.setIcon(new ImageIcon("kdevelop_down.png"));
    clickMeSix.setIcon(new ImageIcon("kdevelop_down.png"));
    clickMeSeven.setIcon(new ImageIcon("kdevelop_down.png"));

    clickMeOne.setBorder(new LineBorder(Color.black));
    clickMeTwo.setBorder(new LineBorder(Color.black)); 
    clickMeThree.setBorder(new LineBorder(Color.black)); 
    clickMeFour.setBorder(new LineBorder(Color.black)); 
    clickMeFive.setBorder(new LineBorder(Color.black)); 
    clickMeSix.setBorder(new LineBorder(Color.black)); 
    clickMeSeven.setBorder(new LineBorder(Color.black));    

    validate();

  }

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

      if (event.getSource() == onePlayer) {

        lblWelcome.setVisible(false);
        playButton.setVisible(false);
        helpButton.setVisible(false); 
        quitButton.setVisible(false);
        twoPlayer.setVisible(false);
        onePlayer.setVisible(true);
        goBack.setVisible(false);

        Thread thread =new Thread() {

          public void run() {
            onePlayer.setText(" Game Starts In ");
            onePlayer.setFont(new Font("Astron Boy Rg", Font.ITALIC, 40));
            onePlayer.setBackground(Color.black);
            onePlayer.setForeground(Color.BLUE);
            try {
              Thread.sleep(1000);                        
            }catch (Exception e) {
            }
            onePlayer.setText("3");
            try {
              Thread.sleep(1000);                        
            }catch (Exception e) {
            }
            onePlayer.setText("2");
            try {
              Thread.sleep(1000);                        
            }catch (Exception e) {
            }
            onePlayer.setText("1");  
            try {
              Thread.sleep(1000);                        
            }catch (Exception e) {
            }   

            setLayout(new GridLayout(xsize, ysize));
            slots = new JButton[xsize - 1][ysize];

            for (int column = 0; column < ysize; column++) {
              for (int row = 0; row < xsize - 1; row++) {
                slots[row][column] = new JButton();
                slots[row][column].setHorizontalAlignment(SwingConstants.CENTER); 
                slots[row][column].setBackground(Color.GREEN);
                slots[row][column].setBorder(new LineBorder(Color.black));                      
                add(slots[row][column]);
              }
            }  

            lblWelcome.setVisible(false);
            remove(lblWelcome);
            playButton.setVisible(false);
            remove(playButton);
            helpButton.setVisible(false);
            remove(helpButton);
            quitButton.setVisible(false);
            remove(quitButton);
            goBack.setVisible(false);
            remove(goBack);
            onePlayer.setVisible(false);
            remove(onePlayer);
            twoPlayer.setVisible(false);
            remove(twoPlayer);

            clickMeOne.setVisible(true);
            clickMeTwo.setVisible(true);
            clickMeThree.setVisible(true);
            clickMeFour.setVisible(true);
            clickMeFive.setVisible(true);
            clickMeSix.setVisible(true);
            clickMeSeven.setVisible(true); 

          }
        };
        thread.start();        
      }
    }
  }

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

      if (event.getSource() == twoPlayer) {

        lblWelcome.setVisible(false);
        playButton.setVisible(false);
        helpButton.setVisible(false); 
        quitButton.setVisible(false);
        twoPlayer.setVisible(true);
        onePlayer.setVisible(false);
        goBack.setVisible(false);


        Thread thread =new Thread() {

          public void run() {
            twoPlayer.setText(" Game Starts In ");
            twoPlayer.setFont(new Font("Astron Boy Rg", Font.ITALIC, 40));
            twoPlayer.setBackground(Color.black);
            twoPlayer.setForeground(Color.blue);
            try {
              Thread.sleep(1000);                        
            }catch (Exception e) {
            }
            twoPlayer.setText("3");
            try {
              Thread.sleep(1000);                        
            }catch (Exception e) {
            }
            twoPlayer.setText("2");
            try {
              Thread.sleep(1000);                        
            }catch (Exception e) {
            }
            twoPlayer.setText("1");  
            try {
              Thread.sleep(1000);                        
            }catch (Exception e) {
            }   

            setLayout(new GridLayout(xsize, ysize));
            slots = new JButton[xsize - 1][ysize];

            for (int column = 0; column < ysize; column++) {
              for (int row = 0; row < xsize - 1; row++) {
                slots[row][column] = new JButton();
                slots[row][column].setHorizontalAlignment(SwingConstants.CENTER); 
                slots[row][column].setBackground(Color.GREEN);
                slots[row][column].setBorder(new LineBorder(Color.black));                      
                add(slots[row][column]);
              }
            }  

            lblWelcome.setVisible(false);
            remove(lblWelcome);
            playButton.setVisible(false);
            remove(playButton);
            helpButton.setVisible(false);
            remove(helpButton);
            quitButton.setVisible(false);
            remove(quitButton);
            goBack.setVisible(false);
            remove(goBack);
            onePlayer.setVisible(false);
            remove(onePlayer);
            twoPlayer.setVisible(false);
            remove(twoPlayer);


            clickMeOne.setVisible(true);
            clickMeTwo.setVisible(true);
            clickMeThree.setVisible(true);
            clickMeFour.setVisible(true);
            clickMeFive.setVisible(true);
            clickMeSix.setVisible(true);
            clickMeSeven.setVisible(true);  

          }
        };
        thread.start();        
      }
    }
  }

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

      if (event.getSource() == playButton) {         

        lblWelcome.setVisible(true);
        playButton.setVisible(false);
        helpButton.setVisible(false); 
        quitButton.setVisible(false); 
        onePlayer.setVisible(true);
        twoPlayer.setVisible(true);
        goBack.setVisible(true);        
      }
    }
  }


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

      if (event.getSource() == goBack) {         

        lblWelcome.setVisible(true);
        playButton.setVisible(true);
        helpButton.setVisible(true); 
        quitButton.setVisible(true); 
        onePlayer.setVisible(false);
        twoPlayer.setVisible(false);
        goBack.setVisible(false);        
      }
    }
  }

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

      if (event.getSource() == quitButton) { 

        int quitTheGame = JOptionPane.showConfirmDialog(null, " Are You Sure You Want to Leave The Game? ", " Quit? "
                                                          , JOptionPane.YES_NO_OPTION);        

        if (quitTheGame == JOptionPane.YES_OPTION)  {
          System.exit(0);
        }        
      }
    }
  }

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

      if (event.getSource() == helpButton) {           
        JOptionPane.showMessageDialog(null, " 1) Choose who plays first.", " Help ", JOptionPane.INFORMATION_MESSAGE);

      }
    }
  } 

  private Color playerColor = Color.red;
  private class clikMeOneButtonListener 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 b = (JButton)event.getSource();

        int column = 0;
        switch ( b.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 lastEmptyIdx = -1;

        for ( int i = 0; i < slots[column].length; i++ ) {

          if ( slots[column][i].getBackground() != Color.green ) {

            break;
          }
          else {

            lastEmptyIdx = i;
          }
        }

        if ( lastEmptyIdx != -1 ) {

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

          if ( IsWin(column, lastEmptyIdx) ) {

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

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

    public boolean IsWin(int column, int row) {   

      boolean result = false;

      // horizontal
      boolean found = false;

      int counter = 0;

      for ( int i = 0; i < slots.length; i++ ) {

        if ( slots[i][row].getBackground().equals(playerColor)) { 

          counter++;

          if ( found == true ) {

            if ( counter == 4 ) { // win \o/
              result = true;          
              break;
            }         
          }        
          else {

            found = true;
          }
        }
        else {

          if ( found == true ) { // reset counter

            counter = 0;
          }

          found = false;
        }
      }

      // vertical 
      for ( int i = 0; i < slots.length; i++ ) {          
        if ( slots[column][i].getBackground().equals(playerColor)) { 

          counter++;

          if ( found == true ) {

            if ( counter == 4 ) { // win \o/
              result = true;          
              break;
            }         
          }        
          else {

            found = true;
          }
        }
        else {

          if ( found == true ) { // reset counter

            counter = 0;
          }

          found = false;
        }
      }

      // diagonal
      // TODO      

      return result;
    }
  }
}

更新:

 for ( int i = 0; i < slots.length; i++ ) {          
          if ( slots[column][i].getBackground().equals(playerColor)) { 

        counter++;  
        column ++;

        if (column >= slots.length - 1){
            found = false;
            break;
        }

        if ( found == true ) {

          if ( counter == 4 ) { // win \o/
            result = true;          
            break;
          }         
        }        
        else {

          found = true;
        }
      }
      else {

        if ( found == true ) { // reset counter

          counter = 0;
        }

        found = false;
      }        

     }

1 个答案:

答案 0 :(得分:0)

您的检查不仅要增加插槽窗格的一个方向(i),还需要增加或减少这个所谓的检查对角线代码中的column到真的沿着对角线检查。

如果该方的列数少于4列,您也可能知道不会有朝向某个方向的对角线胜利。

<小时/> **编辑*:您真的应该阅读语言概念,特别是尝试理解超出语法的概念!为了理解发生了什么,调试器是一个必不可少的工具。如果您有一个特定的算法(例如,您需要深入了解的IsWin()方法),请使用纸张和铅笔并执行“手动”操作。这将为您提供更多关于可能出现的错误的提示。 SO的问题。然而,对问题重复的引用完全显示了解决方案的外观。您需要了解并将其转移到特定的代码环境中。

为了进一步帮助您,请在下面找到与您的代码逻辑一起使用的IsWin()版本。您只需要提供当前的playerColor作为另一个参数。然后它将指出最后一步是否导致胜利。 (因为之前不可能获胜,否则之前会有人表示!)。因此,您只需要检查最后一次移动是否在任何方向上完成了四个序列。代码未经过真正优化。仍有缩短的空间。但也许您应该首先了解自己在做什么,并从代码中删除不必要的垃圾......

建议代码:

    public boolean IsWin(final int column, final int row, final Color playerColor) {

        boolean won = true;
        // vertical
        if (row < slots[column].length - 3) {
            for (int i = 0; i < 4; i++ ) {
                if ( !slots[column][row + i].getBackground().equals(playerColor)) {
                    won = false;
                    break;
                }
            }
            if (won) {
                return won;
            }
        }
        // to the left
        if (column >= 3) {
            // horizontal
            won = true;
            for (int i = 0; i < 4; i++ ) {
                if ( !slots[column - i][row].getBackground().equals(playerColor)) {
                    won = false;
                    break;
                }
            }
            if (won) {
                return won;
            }
            // diagonal
            if (row < slots[column].length - 3) {
                won = true;
                for (int i = 0; i < 4; i++ ) {
                    if ( !slots[column - i][row + i].getBackground().equals(playerColor)) {
                        won = false;
                        break;
                    }
                }
                if (won) {
                    return won;
                }
            }
        }
        // to the right
        if (slots.length - column > 3) {
            // horizontal
            won = true;
            for (int i = 0; i < 4; i++ ) {
                if ( !slots[column + i][row].getBackground().equals(playerColor)) {
                    won = false;
                    break;
                }
            }
            if (won) {
                return won;
            }
            // diagonal
            if (row < slots[column].length - 3) {
                won = true;
                for (int i = 0; i < 4; i++ ) {
                    if ( !slots[column + i][row + i].getBackground().equals(playerColor)) {
                        won = false;
                        break;
                    }
                }
                if (won) {
                    return won;
                }
            }
        }
        return false;
    }