0

所以我正在制作一个用户友好的 GUI 界面的井字游戏。我几乎完成了游戏,但我的 checkWin 功能似乎有问题。到目前为止,一切正常,直到我添加了 checkWin 函数和与之关联的参数。在我实现 checkWin 功能之前,你会按下一个按钮,它会被标记为 X,然后会有一个自动的计算机移动,它会在没有 X 的板上随机放置一个 O。代码发布在下面。当我运行代码并按下按钮时,小程序会冻结,如果没有结束任务,您甚至无法退出它, ctrl-alt-del ... 同样,在 checkWin 函数之前一切正常,现在我面临一个运行时错误。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class TicGUI extends JFrame 
    {

  JFrame frame = new JFrame("TicTacToe");                    //Global frame and grid button variables 
  JButton[][] buttons = new JButton[3][3];
  JButton start = new JButton("Start");              //Create start/reset buttons for game
  JButton reset = new JButton("Reset");
  JOptionPane turn;
  int moveCounter = 9;
  boolean gameWon = false;


 public TicGUI()                                        //Tic tac default constructor which adds and dimensions Jframe
   {
     super();
     frame.setSize(350, 450);
     frame.setDefaultCloseOperation(EXIT_ON_CLOSE);        //Setting dimension of Jframe and setting parameters
     frame.setVisible(true);
     frame.setResizable(false);

   }

  private void checkWin(int row, int col)
    {
      if(buttons[row][0].getText()==buttons[row][1].getText()&& buttons[row][1].getText()==buttons[row][2].getText())
        {
          gameWon = true;
          System.out.println(buttons[row][0].getText()+ " wins!!!");         
        }
    else  if(buttons[0][col].getText()==buttons[1][col].getText()&& buttons[1][col].getText()==buttons[2][col].getText())
       {
          gameWon = true;
          System.out.println(buttons[row][0].getText()+ " wins!!!");
       }
    }
  private void compTurn(int count)
   { 
    int randomMove=count;
    Random num = new Random();
    randomMove = num.nextInt(randomMove)+1;

     while(gameWon ==false)
      {
       for(int i = 0; i < 3; i++)                      //Create grid of buttons for tic tac toe game
        {
         for(int j = 0; j < 3; j++) 
          {                 
           if(buttons[i][j].isEnabled()==true)
            {
               randomMove--;

             if(randomMove==0 )
              {
                buttons[i][j].setText("O");
                buttons[i][j].setEnabled(false);
                moveCounter--;
                checkWin(i, j);
              }
             } 

            }
          }
        }
      }

private void initialize()             //Initialize tic tac toe game board
   {
      JPanel mainPanel = new JPanel(new BorderLayout());         //create main panel container to put layer others on top
      JPanel menu = new JPanel(new BorderLayout());
      JPanel game = new JPanel(new GridLayout(3,3));                     //Create two more panels with layouts for buttons

      frame.add(mainPanel);                                         //add main container panel to frame

      mainPanel.setPreferredSize(new Dimension(325,425));
      menu.setPreferredSize(new Dimension(300,50));                     //Setting dimensions of panels
      game.setPreferredSize(new Dimension(300,300));

      mainPanel.add(menu, BorderLayout.NORTH);                   //Add two panels to the main container panel             
      mainPanel.add(game, BorderLayout.SOUTH);

      menu.add(start, BorderLayout.WEST);                //Add both start/reset buttons to menu container panel
      menu.add(reset, BorderLayout.EAST);

      start.addActionListener(new myActionListener());
      reset.addActionListener(new myActionListener());

   for(int i = 0; i < 3; i++)                      //Create grid of buttons for tic tac toe game
     {
      for(int j = 0; j < 3; j++) 
        {

         buttons[i][j] = new JButton();                //Instantiating buttons 
         buttons[i][j].setText("");
         buttons[i][j].setVisible(true);

         game.add(buttons[i][j]); 
         buttons[i][j].addActionListener(new myActionListener());        //Adding response event to buttons
        }
     }

  }

 private class myActionListener implements ActionListener
   {      //Implementing action listener for buttons
     public void actionPerformed(ActionEvent a) 
      {
       //Display X's or O's on the buttons  
       if(a.getSource() == buttons[0][0])                  //Checking which button is pressed
         {
           buttons[0][0].setText("X");
           buttons[0][0].setEnabled(false);
           moveCounter--;
           compTurn(moveCounter);
           checkWin(0,0);
         } 
       else if(a.getSource() == buttons[0][1])
         {
           buttons[0][1].setText("X");
           buttons[0][1].setEnabled(false);
           moveCounter--;
           compTurn(moveCounter);
           checkWin(0,1);
         } 
       else if(a.getSource() == buttons[1][0])
        {
          buttons[1][0].setText("X");  
          buttons[1][0].setEnabled(false);
          moveCounter--;
          compTurn(moveCounter);
          checkWin(1,0);
        } 
       else if(a.getSource() == buttons[1][1])
        {
          buttons[1][1].setText("X");
          buttons[1][1].setEnabled(false);
          moveCounter--;
          compTurn(moveCounter);
          checkWin(1,1);
        }
       else if(a.getSource() == buttons[1][2])
        {
          buttons[1][2].setText("X");
          buttons[1][2].setEnabled(false);
          moveCounter--;
          compTurn(moveCounter); 
          checkWin(1,2);
        } 
       else if(a.getSource() == buttons[2][2])
        {
         buttons[2][2].setText("X");
         buttons[2][2].setEnabled(false);
         moveCounter--;
         compTurn(moveCounter);
         checkWin(2,2);
        } 
       else if(a.getSource() == buttons[0][2])
        {
         buttons[0][2].setText("X");
         buttons[0][2].setEnabled(false);
         moveCounter--;
         compTurn(moveCounter);
         checkWin(0,2);
        }
       else if(a.getSource() == buttons[2][1])
        {
         buttons[2][1].setText("X");
         buttons[2][1].setEnabled(false);
         moveCounter--;
         compTurn(moveCounter);
         checkWin(2,1);
        }
       else if(a.getSource() == buttons[2][0])
        {
         buttons[2][0].setText("X");
         buttons[2][0].setEnabled(false);
         moveCounter--;
         compTurn(moveCounter);
         checkWin(2,0);
        }
       else if(a.getSource() == start)
         {
           turn = new JOptionPane("Do you want to go first?\n",JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);
           start.setEnabled(false);
         }
       else if(a.getSource() == reset)
         {
            for(int i = 0; i < 3; i++)
             { 
               for(int j = 0; j < 3; j++)
                {
                   buttons[i][j].setText(""); 
                   buttons[i][j].setEnabled(true);
                   gameWon = false;
                }
             }
           }
       }
     }

 public static void main(String[] args)
    {
      TicGUI game = new TicGUI();         //main method and instantiating tic tac object and calling initialize function
      game.initialize();
    }
 }
4

3 回答 3

0

您需要使用以下内容:

buttons[row][0].getText().equals(buttons[row][1].getText())

代替:

buttons[row][0].getText()==buttons[row][1].getText()

这也适用于您的 checkWin 方法中的所有其他字符串比较。

于 2014-02-16T02:44:30.720 回答
0

你checkWon中的循环无法在游戏完成时结束,但你可以完成游戏,因为while循环阻塞了它

于 2014-02-16T05:34:39.657 回答
0

问题似乎在于 AI(“compTurn()”)正在运行一个无限循环,并且从未给玩家一个实际的转弯。相反,它不断尝试轮到它。为了解决这个问题,添加一个调节变量(我在下面的示例修复中添加了“int whoTurn”)。

不过,这只能解决运行时错误。另一个问题是,在 MacOS 设备上(我在 MacOS X 上测试过),按钮是在后台缓冲区之前绘制的,因此结果是空白后台缓冲区和无法玩的游戏。解决这个问题的方法是在绘制backbuffer之后绘制按钮,或者只是在绘制backbuffer代码之后复制+粘贴按钮的代码。

还有另一个问题,而“开始按钮完全没用,并且不会以任何方式影响游戏。我在下面的示例代码中删除了它。

最后一个问题是您的“checkWin”方法很简单,但经常出错。我已经用更长、更准确的获胜检查系统取代了它。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.JOptionPane;

class TicGUI extends JFrame 
{

JButton[][] buttons = new JButton[3][3];
JFrame frame = new JFrame("TicTacToe");                    //Global frame and grid button variables
JButton reset = new JButton("Reset");             //Create reset button for game
JOptionPane turn;
int moveCounter = 9;
boolean gameWon = false;
int WhoseTurn = 1;

public TicGUI()                                        //Tic tac default constructor which adds and dimensions Jframe
{
 super();
 frame.setSize(350, 355);
 frame.setDefaultCloseOperation(EXIT_ON_CLOSE);        //Setting dimension of Jframe and setting parameters
 frame.setVisible(true);
 frame.setResizable(false);
 JButton[][] buttons = new JButton[3][3];
 JFrame frame = new JFrame("TicTacToe");                    //Global frame and grid button variables 
 JButton reset = new JButton("Reset");             //Create reset button for game
 JOptionPane turn;

}

private void checkWin(int row, int col)
{
    try {
    if (buttons[0][2].getText()==buttons[1][2].getText()&& buttons[1][2].getText()==buttons[2][2].getText()&& buttons[2][2].getText()==buttons[0][2].getText()&& buttons[1][2].getText()!="")
   {
      gameWon = true;
      WhoseTurn = 0;
      System.out.println(buttons[1][2].getText()+ " wins!!!");
      JOptionPane.showMessageDialog(frame, buttons[1][2].getText()+ " wins!!!");
   }
    if (buttons[0][1].getText()==buttons[1][1].getText()&& buttons[1][1].getText()==buttons[2][1].getText()&& buttons[2][1].getText()==buttons[0][1].getText()&& buttons[1][1].getText()!="")
   {
      gameWon = true;
      WhoseTurn = 0;
      System.out.println(buttons[1][1].getText()+ " wins!!!");
      JOptionPane.showMessageDialog(frame, buttons[1][1].getText()+ " wins!!!");
   }
    if (buttons[0][0].getText()==buttons[1][0].getText()&& buttons[1][0].getText()==buttons[2][0].getText()&& buttons[2][0].getText()==buttons[0][0].getText()&& buttons[1][0].getText()!="")
   {
      gameWon = true;
      WhoseTurn = 0;
      System.out.println(buttons[1][0].getText()+ " wins!!!");
      JOptionPane.showMessageDialog(frame, buttons[1][0].getText()+ " wins!!!");
   }
    if (buttons[2][0].getText()==buttons[2][1].getText()&& buttons[2][1].getText()==buttons[2][2].getText()&& buttons[2][2].getText()==buttons[2][0].getText()&& buttons[2][1].getText()!="")
   {
      gameWon = true;
      WhoseTurn = 0;
      System.out.println(buttons[2][1].getText()+ " wins!!!");
      JOptionPane.showMessageDialog(frame, buttons[2][1].getText()+ " wins!!!");
   }
    if (buttons[1][0].getText()==buttons[1][1].getText()&& buttons[1][1].getText()==buttons[1][2].getText()&& buttons[1][2].getText()==buttons[1][0].getText()&& buttons[1][1].getText()!="")
   {
      gameWon = true;
      WhoseTurn = 0;
      System.out.println(buttons[1][1].getText()+ " wins!!!");
      JOptionPane.showMessageDialog(frame, buttons[1][1].getText()+ " wins!!!");
   }
    if (buttons[0][0].getText()==buttons[0][1].getText()&& buttons[0][1].getText()==buttons[0][2].getText()&& buttons[0][2].getText()==buttons[0][0].getText()&& buttons[0][1].getText()!="")
   {
      gameWon = true;
      WhoseTurn = 0;
      System.out.println(buttons[0][1].getText()+ " wins!!!");
      JOptionPane.showMessageDialog(frame, buttons[0][1].getText()+ " wins!!!");
   }
   if (buttons[0][0].getText()==buttons[1][1].getText()&& buttons[1][1].getText()==buttons[2][2].getText()&& buttons[2][2].getText()==buttons[0][0].getText()&& buttons[1][1].getText()!="")
   {
      gameWon = true;
      WhoseTurn = 0;
      System.out.println(buttons[1][1].getText()+ " wins!!!");
      JOptionPane.showMessageDialog(frame, buttons[1][1].getText()+ " wins!!!");
   }
   if (buttons[0][2].getText()==buttons[1][1].getText()&& buttons[1][1].getText()==buttons[2][0].getText()&& buttons[2][0].getText()==buttons[0][2].getText()&& buttons[1][1].getText()!="")
   {
      gameWon = true;
      WhoseTurn = 0;
      System.out.println(buttons[1][1].getText()+ " wins!!!");
      JOptionPane.showMessageDialog(frame, buttons[1][1].getText()+ " wins!!!");
   }
    }catch(Exception e) {
        gameWon = true;
      WhoseTurn = 0;
      System.out.println("Stalemate");
      JOptionPane.showMessageDialog(frame, "Stalemate");
    }
}

private void compTurn(int count)
{ 
int randomMove=count;
Random num = new Random();
randomMove = num.nextInt(randomMove)+1;

 while(gameWon ==false & WhoseTurn ==2)
  {
   for(int i = 0; i < 3; i++)                      //Create grid of buttons for tic tac toe game
    {
     for(int j = 0; j < 3; j++) 
      {                 
       if(buttons[i][j].isEnabled()==true)
        {
           randomMove--;

         if(randomMove==0 )
          {
            buttons[i][j].setText("O");
            buttons[i][j].setEnabled(false);
            moveCounter--;
            checkWin(i, j);
            WhoseTurn = 1;
          }
         } 

        }
      }
    }
  }

private void initialize()             //Initialize tic tac toe game board
{
  JPanel mainPanel = new JPanel(new BorderLayout());         //create main panel container to put layer others on top
  JPanel menu = new JPanel(new BorderLayout());
  JPanel game = new JPanel(new GridLayout(3,3));                     //Create two more panels with layouts for buttons

  frame.add(mainPanel);                                         //add main container panel to frame

  mainPanel.setPreferredSize(new Dimension(325,425));
  menu.setPreferredSize(new Dimension(300,50));                     //Setting dimensions of panels
  game.setPreferredSize(new Dimension(300,300));

  mainPanel.add(menu, BorderLayout.NORTH);                   //Add two panels to the main container panel             
  mainPanel.add(game, BorderLayout.SOUTH);

  //Add both start/reset buttons to menu container panel
  menu.add(reset, BorderLayout.NORTH);

  reset.addActionListener(new myActionListener());

for(int i = 0; i < 3; i++)                      //Create grid of buttons for tic tac toe game
 {
  for(int j = 0; j < 3; j++) 
    {

     buttons[i][j] = new JButton();                //Instantiating buttons 
     buttons[i][j].setText("");
     buttons[i][j].setVisible(true);

     game.add(buttons[i][j]); 
     buttons[i][j].addActionListener(new myActionListener());        //Adding response event to buttons
    }
 }

}

private class myActionListener implements ActionListener
{      //Implementing action listener for buttons
 public void actionPerformed(ActionEvent a) 
  {
   //Display X's or O's on the buttons
   if(gameWon == false)
   {
   if(a.getSource() == buttons[0][0])                  //Checking which button is pressed
     {
       buttons[0][0].setText("X");
       buttons[0][0].setEnabled(false);
       WhoseTurn = 2;
       moveCounter--;
       compTurn(moveCounter);
       checkWin(0,0);
     } 
   else if(a.getSource() == buttons[0][1])
     {
       buttons[0][1].setText("X");
       buttons[0][1].setEnabled(false);
       WhoseTurn = 2;
       moveCounter--;
       compTurn(moveCounter);
       checkWin(0,1);
     } 
   else if(a.getSource() == buttons[1][0])
    {
      buttons[1][0].setText("X");  
      buttons[1][0].setEnabled(false);
      WhoseTurn = 2;
      moveCounter--;
      compTurn(moveCounter);
      checkWin(1,0);
    } 
   else if(a.getSource() == buttons[1][1])
    {
      buttons[1][1].setText("X");
      buttons[1][1].setEnabled(false);
      WhoseTurn = 2;
      moveCounter--;
      compTurn(moveCounter);
      checkWin(1,1);
    }
   else if(a.getSource() == buttons[1][2])
    {
      buttons[1][2].setText("X");
      buttons[1][2].setEnabled(false);
      WhoseTurn = 2;
      moveCounter--;
      compTurn(moveCounter); 
      checkWin(1,2);
    } 
   else if(a.getSource() == buttons[2][2])
    {
     buttons[2][2].setText("X");
     buttons[2][2].setEnabled(false);
     WhoseTurn = 2;
     moveCounter--;
     compTurn(moveCounter);
     checkWin(2,2);
    } 
   else if(a.getSource() == buttons[0][2])
    {
     buttons[0][2].setText("X");
     buttons[0][2].setEnabled(false);
     WhoseTurn = 2;
     moveCounter--;
     compTurn(moveCounter);
     checkWin(0,2);
    }
   else if(a.getSource() == buttons[2][1])
    {
     buttons[2][1].setText("X");
     buttons[2][1].setEnabled(false);
     WhoseTurn = 2;
     moveCounter--;
     compTurn(moveCounter);
     checkWin(2,1);
    }
   else if(a.getSource() == buttons[2][0])
    {
     buttons[2][0].setText("X");
     buttons[2][0].setEnabled(false);
     WhoseTurn = 2;
     moveCounter--;
     compTurn(moveCounter);
     checkWin(2,0);
    }
   }
   if(a.getSource() == reset)
     {
        for(int i = 0; i < 3; i++)
         { 
           for(int j = 0; j < 3; j++)
            {
                gameWon = false;
               buttons[i][j].setText(""); 
               buttons[i][j].setEnabled(true);
               moveCounter = 9;
               WhoseTurn = 1;

            }
         }
       }
  }
 }

public static void main(String[] args)
{
  TicGUI game = new TicGUI();         //main method and instantiating tic tac object and calling initialize function
  game.initialize();
 }
}

如果您仍然有问题,请询问!

  • 范杰斯

JEF1056 [音乐艺术家、.Net 程序员、学生]

https://itunes.apple.com/us/artist/jef1056/id1139804160 https://play.google.com/store/music/artist/JEF1056?id=Aovo6cz54vkx2ekexyl7eom6nwy

于 2016-11-24T22:02:33.440 回答