【问题标题】:Trying to start a new Tic Tac Toe game after clicking on a menu bar item单击菜单栏项后尝试开始新的井字游戏
【发布时间】:2019-08-29 20:17:02
【问题描述】:

我有一个使用 java GUI 制作的井字游戏,并试图通过让用户单击菜单栏项来实现重新启动游戏的方法。

请让我知道我可以尝试哪些其他方法来获得有效的重启功能。

到目前为止,我尝试的是在单击菜单栏项时调用 playGame() 方法,但这不起作用,因为 playGame 方法中的 while 循环使它卡住了。


public TicTacToe()
       {
           /* Create JFrame and set up the size and visibility */
           frame = new JFrame("Tic Tac Toe");
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

           /* Create menu bar*/
           JMenuBar menubar = new JMenuBar();
           JMenu game = new JMenu("Game");
           newGame = new JMenuItem("New Game");
           quit = new JMenuItem("Quit");

           newGame.addActionListener(new ActionListener() 
           {
               public void actionPerformed(ActionEvent evt) {
                   newGameActionPerformed(evt);
                }
           });

           quit.addActionListener(new ActionListener() 
           {
               public void actionPerformed(ActionEvent evt) {
                   quitActionPerformed(evt);
                }
           });

           game.add(newGame);
           game.add(quit);
           menubar.add(game);
           frame.setJMenuBar(menubar);

           /* Add text area to frame. */
           frame.add(scrollableTextArea);
           frame.setLocationRelativeTo(null);
           frame.setSize(400,400);
           frame.setVisible(false); 
       }

       private void quitActionPerformed(ActionEvent evt){
           System.exit(0);
       }

       private void newGameActionPerformed(ActionEvent evt) {
           clearBoard();
       }
public void playGame()
       {
          frame.setVisible(true); 
          clearBoard(); // clear the board
          // loop until the game ends
          while (winner==EMPTY) { // game still in progress
             while (playerWent == false){
                if (topRight.getModel().isPressed()){
                    topRight.setText(player);
                    topRight.setEnabled(false);
                    playerWent = true;
                 } 
                 else if (topMid.getModel().isPressed()){
                    topMid.setText(player);
                    topMid.setEnabled(false);
                    playerWent = true;
                    }
                 else if (topLeft.getModel().isPressed()){
                    topLeft.setText(player);
                    topLeft.setEnabled(false);
                    playerWent = true;
                    }
                 else if (midRight.getModel().isPressed()){
                    midRight.setText(player);
                    midRight.setEnabled(false);
                    playerWent = true;
                    }
                 else if (center.getModel().isPressed()){
                    center.setText(player);
                    center.setEnabled(false);
                    playerWent = true;
                    }
                 else if (midLeft.getModel().isPressed()){
                    midLeft.setText(player);
                    midLeft.setEnabled(false);
                    playerWent = true;
                    }
                 else if (botRight.getModel().isPressed()){
                    botRight.setText(player);
                    botRight.setEnabled(false);
                    playerWent = true;
                    }
                 else if (botMid.getModel().isPressed()){
                    botMid.setText(player);
                    botMid.setEnabled(false);
                    playerWent = true;
                    }
                 else if (botLeft.getModel().isPressed()){
                    botLeft.setText(player);
                    botLeft.setEnabled(false);
                    playerWent = true;
                    }  
             } 
             numFreeSquares--;            // decrement number of free squares

             // see if the game is over
             if (haveWinner()) {
                winner = player; // must be the player who just went
                if (winner.equals(PLAYER_X)){
                    gameState.setText("Player X wins");
                    return;
                } else {
                    gameState.setText("Player O wins");
                    return;
                }
            }
             else if (numFreeSquares==0) {
                winner = TIE; // board is full so it's a tie
                gameState.setText("Tie game");
                return;
                }


             // change to other player (this won't do anything if game has ended)
             if (player==PLAYER_X) {
                player=PLAYER_O;
                gameState.setText("Game in progress, Player O's turn");
                playerWent = false;
            }
             else {
                player=PLAYER_X;
                gameState.setText("Game in progress, Player X's turn");
                playerWent = false;
            }
          }
       }

【问题讨论】:

  • 始终添加标签和/或提及您在构建应用程序时使用的 GUI 框架。可能性包括 Swing、SWT、JavaFX、Vaadin 等。我猜测并添加了“Swing”标签。
  • 这不起作用,因为 playGame 方法中的 while 循环使它卡住了。 - 并且不需要 while 循环。开始游戏时您需要做的就是设置玩家(X 或 O)。然后,当您单击按钮时,您设置按钮的值,然后检查游戏是否结束。如果游戏结束,您会显示一条消息。如果游戏没有结束,则设置下一个玩家(o 或 X),依此类推。所以所有的游戏逻辑基本上都在添加到每个按钮的 MouseListener 中,程序只是坐在那里,直到单击按钮之前什么都不做。
  • @camickr 哇,鼠标监听器的工作就像一个魅力,非常感谢!
  • @JasonGao 鼠标监听器的工作就像一个魅力 - 哎呀。我的意思是说代码应该在您添加到每个按钮的ActionListener 中。单击按钮时不应使用 MouseListener。

标签: java swing user-interface


【解决方案1】:

循环将覆盖您尝试实现的重启功能。我的建议是你尝试重构你的代码以工作事件驱动。简而言之:事件驱动编程是响应(并确认)用户输入的用户界面。你可以通过一个管理游戏回合的类来做到这一点。

这里有一些示例代码供参考,我已将其用于我自己的井字游戏项目(JavaFX 框架):

 private void playersGameProcess() {
        //Looping through the button field to add mouseclick events, if there is pressed on a button the game's state switches between CROSS and NOUGHT.
        for (int i = 0; i < buttons2D.length; i++) {
            for (int j = 0; j < buttons2D[i].length; j++) {
                Button button = buttons2D[i][j];
                buttons2D[i][j].setOnMouseClicked(event -> {
                    if (game.getGameState() == "X" && button.getId() == null) {
                        game.incrementTurnCount();
                        System.out.println("Turn: " + game.getTurnCount());
                        notification.setText("It's nought's turn!");
                        game.setGameState("O");
                        button.setId("buttonClickX");
                        checkWinningConditions("X");
                    } else if (game.getGameState() == "O" && button.getId() == null) {
                        game.incrementTurnCount();
                        System.out.println("Turn: " + game.getTurnCount());
                        notification.setText("It's cross's turn!");
                        button.setId("buttonClickO");
                        game.setGameState("X");
                        checkWinningConditions("O");
                    }
                });
            }
        }
    }

【讨论】:

  • 不要使用 "==" 进行字符串比较。相反,您应该使用 equals(...) 方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多