井字游戏未能在正确的时机显示获胜者。

huangapple go评论80阅读模式
英文:

The Tic Tac Toe game does not show the winner at the right time

问题

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.border.EtchedBorder;

public class TicTocToe extends JFrame implements ActionListener {

    // ... (Same code as provided)

    private void showWinner() {
        if (findWinner()) {
            if (getPlayerName().equalsIgnoreCase("x")) {
                statusBar.setText("Winner is Player X");
            } else if (getPlayerName().equalsIgnoreCase("o")) {
                statusBar.setText("Winner is Player O");
            }
        } else if (!findWinner() && count == 9) {
            statusBar.setText("It was a draw, no one.");
        }

        // Remove the following lines to remove the need for an additional click
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board.length; j++) {
                board[i][j].removeActionListener(this);
            }
        }
    }

    // ... (Rest of the code remains the same)
}

Note: The provided code had HTML entities like &quot; which represent double quotes (") and &lt; which represent the less-than symbol (<). I've replaced them with actual double quotes and less-than symbols in the translated code.

英文:

my code is tic tac toe and i have problem with show winner.
i get winner but not when X or O in correct direction.
and show winner after click on button.

code :

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.border.EtchedBorder;

public class TicTocToe extends JFrame implements ActionListener {

	private static final long serialVersionUID = -7730552764304282715L;
	private static final Font BT_FONT = new Font(&quot;Segoe UI&quot;, 0, 30);
	private static final Font LB_FONT = new Font(&quot;Consolas&quot;, 0, 20);

	private JButton[][] board;
	private JLabel statusBar;
	private JPanel centerPanel, southPanel;
	private int turn = 0, count = 0;
	private String name;

	public static void main(String[] args) {
		EventQueue.invokeLater(() -&gt; new TicTocToe().setVisible(true));

	}

	public TicTocToe() {

		super(&quot;Tic Toc Toe&quot;);

		try {

			UIManager.setLookAndFeel(&quot;com.sun.java.swing.plaf.windows.WindowsLookAndFeel&quot;);
			initUI();

		} catch (Exception e) {
			e.printStackTrace();

		}

	}

	private void initUI() {

		initCenterPanel();
		initSouthPanel();

		add(centerPanel);
		add(southPanel, BorderLayout.SOUTH);

		pack();

		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setResizable(false);
		setLocationRelativeTo(null);

	}

	private void initCenterPanel() {

		centerPanel = new JPanel();

		board = new JButton[3][3];

		for (int i = 0; i &lt; board[0].length; i++) {

			for (int j = 0; j &lt; board[i].length; j++) {

				board[i][j] = new JButton(&quot;-&quot;);
				board[i][j].setFont(BT_FONT);
				board[i][j].setFocusPainted(false);
				board[i][j].setPreferredSize(new Dimension(80, 80));
				board[i][j].addActionListener(this);

				centerPanel.add(board[i][j]);

			}

		}

	}

	private void initSouthPanel() {

		southPanel = new JPanel();
		southPanel.setLayout(new BorderLayout());

		statusBar = new JLabel();
		statusBar.setFont(LB_FONT);
		statusBar.setText(&quot;Click On Button To Start&quot;);
		statusBar.setHorizontalAlignment(JLabel.CENTER);
		statusBar.setBorder(new EtchedBorder());

		southPanel.add(statusBar);
	}

	private void play(JButton button) {

		for (int i = 0; i &lt; board.length; i++) {

			for (int j = 0; j &lt; board[i].length; j++) {

				if (button.equals(board[i][j])) {

					count++;

					if (turn &lt; 1) {

						statusBar.setText(&quot;Player &quot; + &quot;O&quot; + &quot; Turn&quot;);
						button.setText(&quot;X&quot;);
						button.setEnabled(false);
						turn++;

					} else {

						statusBar.setText(&quot;Player &quot; + &quot;X&quot; + &quot; Turn&quot;);
						button.setText(&quot;O&quot;);
						button.setEnabled(false);
						turn--;

					}

				}

			}

		}

	}

	private String getPlayerName() {
		return (turn &lt; 1) ? &quot;X&quot; : &quot;O&quot;;

	}

	private boolean findWinner() {

		name = getPlayerName();

		for (int i = 0; i &lt; board.length; i++) {

			if (board[i][0].getText().equals(name) &amp;&amp; board[i][1].getText().equals(name)
					&amp;&amp; board[i][2].getText().equals(name))

				return true;

			for (int j = 0; j &lt; board[i].length; j++) {

				if (board[0][j].getText().equals(name) &amp;&amp; board[1][j].getText().equals(name)
						&amp;&amp; board[2][j].getText().equals(name))

					return true;

				if (board[0][0].getText().equals(name) &amp;&amp; board[1][1].getText().equals(name)
						&amp;&amp; board[2][2].getText().equals(name))

					return true;

				if (board[0][2].getText().equals(name) &amp;&amp; board[1][1].getText().equals(name)
						&amp;&amp; board[2][0].getText().equals(name))

					return true;

			}

		}

		return false;

	}

	private void showWinner() {

		for (int i = 0; i &lt; board.length; i++) {

			for (int j = 0; j &lt; board.length; j++) {

				if (findWinner()) {

					if (getPlayerName().equalsIgnoreCase(&quot;x&quot;)) {

						statusBar.setText(&quot;Winner is Player X&quot;);
						board[i][j].removeActionListener(this);
					}

					else if (getPlayerName().equalsIgnoreCase(&quot;o&quot;)) {

						statusBar.setText(&quot;Winner is Player O&quot;);
						board[i][j].removeActionListener(this);

					}

				} else if (!findWinner() &amp;&amp; count == 9) {

					statusBar.setText(&quot;It was a draw, no wone.&quot;);
					board[i][j].removeActionListener(this);

				}

			}
		}

	}

	public void actionPerformed(ActionEvent event) {

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

		play(button);
		showWinner();

	}

	public Dimension getPreferredSize() {
		return new Dimension(300, 320);

	}

	public Dimension getMinimumSize() {
		return getPreferredSize();

	}

}

井字游戏未能在正确的时机显示获胜者。

in this image Winner is X but wait for Player O

井字游戏未能在正确的时机显示获胜者。

and after click on other button show Winner.
i need show winner when X or O in correct Direction
and no wait for click on other button

答案1

得分: 2

我想我明白了。

当按钮被按下时,按以下顺序执行操作:

  1. 将状态栏更改为显示轮到下一位玩家
  2. 设置相关按钮文本以显示刚刚选择该按钮的玩家
  3. 禁用该按钮
  4. 更改轮换值以反映下一位玩家
  5. 基于当前玩家的名称检查是否有获胜者,但您已经将其更改为下一位玩家,而不是刚刚执行移动的玩家

当X进行获胜移动时,游戏在检查是否有获胜者之前会将当前玩家名称更改为O,因此它会检查是否O已经获胜。您需要重新排序操作:

  1. 更改按钮文本
  2. 禁用该按钮
  3. 基于当前玩家名称检查是否有获胜者,如果当前玩家获胜或者出现平局,则结束游戏
  4. 如果游戏仍在进行,现在是更改轮换值并更新状态栏以显示轮到下一位玩家的时候了。
英文:

I think I see it.

When a button is pressed, you do stuff in this order:

  1. change the status bar to say it's the next player's turn
  2. set the relevant button text to show the player who just picked that button
  3. disable the button
  4. change the turn value to reflect the next player
  5. check for a winner, based on the current player's name but you have already changed this to the next player, not the player who just made the move.

When X makes a winning move, the current player name is changed to O before the game checks for a winner, so it checks to see if O has won. You need to reorder stuff:

  1. change the button text
  2. disable the button
  3. check for a winner based on the current player name, end the game if the current player has won or if there is a draw
  4. if the game is still going, now is the time to change the turn value and update the status bar to show that it's the next player's turn.

huangapple
  • 本文由 发表于 2020年8月21日 05:03:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/63513096.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定