【问题标题】:Java TicTacToe game winCondition?Java井字游戏winCondition?
【发布时间】:2014-05-21 18:06:47
【问题描述】:

如何为我的井字游戏设定获胜条件?我还需要做到这一点,当玩家完成时,它会询问他们是否想再玩一次。如果你想出办法,你能告诉我为什么会这样。这是我的代码:

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

    @SuppressWarnings("serial")
    public class game extends JFrame{

    JFrame gameWindow = new JFrame("Tic-Tac-Toe");
    private JButton buttons[] = new JButton[9];
    private String mark = "";
    private int count = 0;

    public static void main(String[] args){
        new game();
    }

    public game(){

        HandlerClass handler = new HandlerClass();

        // Sets buttons on the screen
        for(int i = 0; i < buttons.length; i++){
            buttons[i] = new JButton(mark);
            buttons[i].addActionListener(handler);
            gameWindow.add(buttons[i]);
        }

        // Sets the looks of the window
        gameWindow.setLayout(new GridLayout(3,3));
        gameWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gameWindow.setSize(300,300);
        gameWindow.setVisible(true);

    }

    private class HandlerClass implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent event) {

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

            if(count % 2 == 0){
                mark = "X";
                click.setBackground(Color.YELLOW);
            }else{
                mark = "O";
                click.setBackground(Color.CYAN);
            }

            click.setText(mark);
            click.setEnabled(false);


            System.out.println(count + "\n" + (count % 2));
            count++;
        }

    }
}

【问题讨论】:

  • 您如何跟踪所有 X 和 Os 的放置位置?
  • 你必须遍历你的按钮。如果按钮位于二维 [3][3] 数组中,则可能更容易实现和理解逻辑。
  • @jschabs 这是用click.setText(mark) 完成的,混合模型和视图....

标签: java arrays swing tic-tac-toe


【解决方案1】:

试试这个方法找出获胜者。

我已经提到了所有的获胜位置。您必须检查每次点击的所有位置。

public String getWinner() {
    int[][] winPositions = new int[][] { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }, 
                                         { 0, 3, 6 }, { 1, 4, 7 }, { 2, 7, 8 }, 
                                         { 0, 4, 8 }, { 2, 4, 6 } };

    for (int[] positions : winPositions) {
        if (buttons[positions[0]].getText().length() > 0
                && buttons[positions[0]].getText().equals(buttons[positions[1]].getText())
                && buttons[positions[1]].getText().equals(buttons[positions[2]].getText())) {
            return buttons[positions[0]].getText();
        }
    }

    return null;
}

最后将其添加到您的actionPerformed() 方法中。

    public void actionPerformed(ActionEvent event) {

        ...

        String winner = getWinner();
        if (winner != null) {
            System.out.println(winner + " is winner");
            gameWindow.dispose();
        }
    }

【讨论】:

    猜你喜欢
    • 2015-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多