Java 对 Tic Tac Toe 程序没有意义

标签 java swing logic

这是我过去几周在 APCS 的业余项目,我几乎已经完成了。我基本上是用 swing 制作一个简单的 gui,它有一个按钮网格并显示像 tic tac toe 这样的图像。然而我就是无法让胜利序列发挥作用。我已经使用网上找到的方法了,还是不行;事实上,这甚至没有意义。我有 1 个打印语句来测试值,它打印了 4 次。我完全迷失了。需要注意的是,我是在我的家用电脑上执行此操作,因此我的电脑上没有图像,但我认为这不会影响程序...?

这是代码(我认为问题出在 gameover() 中)

int XgoesFirst=0;
int[] press= {0,0,0,0,0,0,0,0,0};
int count=0;
int over=0;
String Xmess=("Cross for you laymens out there");
String Omess=("Naught for you laymens out there");
String rowWinner="";
String diagWinner="";
String columnWinner="";

private class CellButtonHandler implements ActionListener{
    public void actionPerformed(ActionEvent e)
    {

        ImageIcon xImage = new ImageIcon("images.jpg");

        JButton pressed=(JButton)(e.getSource());       
            if(gameover()){
                if(XgoesFirst==0){
                    pressed.setIcon(xImage);

                    pressed.setText(Xmess);
                    XgoesFirst=XgoesFirst+1;
                    press[count]+=1;
                    over++;
                }else if(XgoesFirst==1){
                    pressed.setIcon(new ImageIcon("O.jpg",""));

                    pressed.setText(Omess);
                    XgoesFirst=XgoesFirst-1;
                    press[count]+=1;
                    over++;
                }
            }
            count++;
            System.out.println(gameover());
        }
    }
}


public boolean gameover(){
    if(cells[0].getText().equals(cells[1].getText()) && cells[1].getText().equals(cells[2].getText())){
        return true;
    }else{
        if(cells[3].getText().equals(cells[4].getText()) && cells[4].getText().equals(cells[5].getText())){
            return true;
        }else{ 
            if(cells[6].getText().equals(cells[7].getText()) && cells[7].getText().equals(cells[8].getText())){
                return true;
            }else{
                if(cells[0].getText().equals(cells[3].getText()) && cells[3].getText().equals(cells[6].getText())){
                    return true;
                }else{
                    if(cells[1].getText().equals(cells[4].getText()) && cells[4].getText().equals(cells[7].getText())){
                        return true}
                    else{
                        if(cells[2].getText().equals(cells[5].getText()) && cells[5].getText().equals(cells[8].getText())){
                            return true;
                        }else{
                            if((cells[0].getText().equals(cells[4].getText()) && cells[4].getText().equals(cells[8].getText())){
                                return true;
                            }else{
                                if(cells[2].getText().equals(cells[4].getText()) && cells[4].getText().equals(cells[6].getText())){
                                    return true;
                                }else{
                                    if (over>7){
                                        return false;
                                    }else{
                                        return true;
                                    }
                }

我不知道代码显示是怎么回事,但如果你告诉我如何修复它,我会重新做。

编辑完整代码:

import javax.swing.JFrame;
import java.awt.event.*; 
import javax.swing.Icon;
import javax.swing.ImageIcon;
import java.awt.*; 
import javax.swing.JButton;     
public class TicTacToe extends JFrame
{
private static final int WIDTH = 400;
private static final int HEIGHT = 300;
private Container content;
private JButton[] cells;
private CellButtonHandler[] cellHandlers;


public TicTacToe()
{
  //  JFrame frame = new JFrame();

    Container pane =getContentPane();
    pane.setLayout(new GridLayout(3,3));
    cells=new JButton[9];
    cellHandlers=new CellButtonHandler[9];
    for(int i=0; i<9;i++){
        cells[i]= new JButton("");
        cellHandlers[i]=new CellButtonHandler();
        cells[i].addActionListener(cellHandlers[i]);
    }
    for(int x=0;x<9;x++){   
        pane.add(cells[x]);
    }
    setTitle("Tic Tac Toe");
    setSize(WIDTH,HEIGHT);
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);

}
public static void main(String[]args)
{
    TicTacToe TicObj= new TicTacToe();
}
            int XgoesFirst=0;
            int[] press= {0,0,0,0,0,0,0,0,0};
            int count=0;
            int over=0;
            String Xmess=("Cross for you laymens out there");
            String Omess=("Naught for you laymens out there");
            String rowWinner="";
            String diagWinner="";
            String columnWinner="";

private class CellButtonHandler implements ActionListener{
    public void actionPerformed(ActionEvent e)
    {

        ImageIcon xImage = new ImageIcon("images.jpg");

        JButton pressed=(JButton)(e.getSource());





        if(gameover()){


                if(XgoesFirst==0){
                    pressed.setIcon(xImage);

                    pressed.setText(Xmess);
                    XgoesFirst=XgoesFirst+1;
                    press[count]+=1;
                    over++;
                }else if(XgoesFirst==1){
                    pressed.setIcon(new ImageIcon("O.jpg",""));

                    pressed.setText(Omess);
                    XgoesFirst=XgoesFirst-1;
                    press[count]+=1;
                    over++;
            }

        }
        count++;
        System.out.println(gameover());
    }
}

    public boolean gameover(){
    if(cells[0].getText().equals(cells[1].getText()) && cells[1].getText().equals(cells[2].getText())){
        return true;
    }else{
        if(cells[3].getText().equals(cells[4].getText()) && cells[4].getText().equals(cells[5].getText())){
        return true;
        }else{ 
            if(cells[6].getText().equals(cells[7].getText()) && cells[7].getText().equals(cells[8].getText())){
                return true;
            }else{
                if(cells[0].getText().equals(cells[3].getText()) && cells[3].getText().equals(cells[6].getText())){
                    return true;
                }else{
                if(cells[1].getText().equals(cells[4].getText()) && cells[4].getText().equals(cells[7].getText())){
                return true}
                else{
                if(cells[2].getText().equals(cells[5].getText()) && cells[5].getText().equals(cells[8].getText())){
                return true;
                }else{
                if((cells[0].getText().equals(cells[4].getText()) && cells[4].getText().equals(cells[8].getText())){
                return true;
                }else{
                if(cells[2].getText().equals(cells[4].getText()) && cells[4].getText().equals(cells[6].getText())){
                return true;
                }else{
                    if (over>7){
                        return false;
                    }else{
                        return true;
                    }
                }


                String winner= "nobody wins cause blame john wells";
    public boolean whoWon()
        {
            boolean rows= rowChecker();
            boolean coll= columnChecker();
            boolean diag= diagChecker();

            if(rows){
                winner=rowWinner;
            }else if(coll){
                winner=columnWinner;
            }else if(diag){
                winner=diagWinner;
            }


            Container pane =getContentPane();
            pane.removeAll();
            pane.repaint();
            JButton restart= new JButton(winner+" won click anywhere to restart");
        //restart.addActionListener(new Restart());

            pane.add(restart);
            return true;
        }
        public boolean rowChecker(){
            boolean temp=false;
            int p=0;
            if(cells[p].getText().equals(cells[p+1].getText())&&cells[p+1].getText().equals(cells[p+2].getText())){
                    temp=true;

                    rowWinner= cells[p].getText();
            }else{
                if(cells[p+3]!=null&&cells[p+3].getText().equals(cells[p+4].getText())&&cells[p+4].getText().equals(cells[p+5].getText())){
                    temp=true;
                    rowWinner= cells[p+3].getText();
                }else{
                    if(cells[p+6]!=null&&cells[p+6].getText().equals(cells[p+7].getText())&&cells[p+7].getText().equals(cells[p+8].getText())){
                        temp=true;
                        rowWinner= cells[p+6].getText();
                    }
            }
    }
    return temp;
}
public boolean diagChecker(){
    boolean temp1=false;
    int w=0;
    if(cells[w]!=null&&cells[w].getText().equals(cells[w+4].getText())&&cells[w+4].getText().equals(cells[w+8].getText())){
        temp1=true;
        diagWinner=cells[w].getText();
    }else{
        if(cells[w+2]!=null&&cells[w+2].getText().equals(cells[w+4].getText())&&cells[w+4].getText().equals(cells[w+6].getText())){
            temp1=true;
            diagWinner=cells[w+4].getText();
            }
    }
    return temp1;
}
    public boolean columnChecker(){
    boolean temp2=false;
    int h =0;
    if(cells[h]!=null&&cells[h].getText().equals(cells[h+3].getText())&&cells[h+3].getText().equals(cells[h+6].getText())){
        columnWinner=cells[h].getText();
        temp2=true;
    }else{
        if(cells[h+1]!=null&&cells[h+1].getText().equals(cells[h+4].getText())&&cells[h+4].getText().equals(cells[h+7].getText())){
            temp2=true;
            columnWinner=cells[h+1].getText();
            }else{
                if(cells[h+2]!=null&&cells[h+2].getText().equals(cells[h+5].getText())&&cells[h+5].getText().equals(cells[h+8].getText())){
                    temp2=true;
                    columnWinner=cells[h+2].getText();
                    }
                }
            }
            return temp2;
    }
//  private class restart implements ActionListener
}

现在我使用的旧方法仍然存在,重启部分还没有完成,但这就是一切。 (旧方法我只是无法让逻辑工作。我试图让它检测其中一个跳棋是否获胜或者游戏是否结束,但我就是无法让逻辑正确)

编辑获胜屏幕

NVM 我现在可以使用了,我只需要知道把它放在哪里,以便在结束时激活。

最佳答案

这是您的代码,其中添加了一些内容和注释。我现在没有时间解释一切,但稍后我会编辑这个答案并添加解释。看一下,如果有任何令人困惑或错误的地方,请告诉我。

目前仅支持玩一款游戏,然后您必须关闭并重新运行应用程序。哦,按钮只能按一次,因为我在按下按钮后删除了按钮的 MouseListener

<小时/>

工作代码

import javax.swing.JFrame;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.ImageIcon;
import javax.swing.SwingUtilities;
import javax.swing.JButton;

public class TicTacToe extends JFrame {
    
    // GUI constants
    private static final int WIDTH = 400; // display width
    private static final int HEIGHT = 300; // display height
    
    // TicTacToe layout constants
    private static final int NUM_ROWS = 3; // number of tic-tac-toe rows
    private static final int NUM_COLS = 3; // number of tic-tac-toe columns
    private static final int TOTAL_CELLS = NUM_ROWS * NUM_COLS;
    private static final int MAX_MOVES = NUM_ROWS * NUM_COLS; // max number of moves
    
    // TicTacToe image, message and default cell value constants
    private static final ImageIcon X_IMAGE = new ImageIcon("images.jpg", ""); // image for X
    private static final ImageIcon O_IMAGE = new ImageIcon("O.jpg", ""); // image for O
    private static final String GAME_ENDS_IN_TIE = "nobody wins cause blame john wells"; // tie message
    private static final String NON_PLAYER_CELL_VALUE = "-"; // "-" is a non player cell
    
    // Private TicTacToe members
    private JButton[] cells;
    private CellButtonHandler[] cellHandlers;
    private String gameWinner;
    private int xGoesFirst;
    // private int[] press = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    // private String xMess = "Cross for you laymens out there";
    // private String oMess = "Naught for you laymens out there";
    private String pOne;
    private String pTwo;
    // private int pOneWins;
    // private int pTwoWins;
    private int count = 0;
    
    /**
     * Default Constructor
     */
    public TicTacToe() {
        // JFrame frame = new JFrame();

        // SWING OPERATIONS
        Container pane = getContentPane();
        pane.setLayout(new GridLayout(NUM_ROWS, NUM_COLS));
        cells = new JButton[TOTAL_CELLS];
        cellHandlers = new CellButtonHandler[TOTAL_CELLS];
        for (int i = 0; i < TOTAL_CELLS; i++) {
            cells[i] = new JButton(NON_PLAYER_CELL_VALUE);
            cellHandlers[i] = new CellButtonHandler();
            cells[i].addActionListener(cellHandlers[i]);
            pane.add(cells[i]);
        }

        setTitle("Tic Tac Toe");
        setSize(WIDTH, HEIGHT);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        // END SWING OPERATIONS

        // CLASS OPERATIONS
        this.setGameWinner(GAME_ENDS_IN_TIE);
        this.xGoesFirst = 1;
        this.pOne = "X";
        this.pTwo = "O";
        // this.pOneWins = 0;
        // this.pTwoWins = 0;
        // END CLASS OPERATIONS

    } // public TicTacToe()
    
    /**
     * setGameWinner
     * 
     * @param who - the game winner as a String.
     */
    private void setGameWinner(String who) {
        this.gameWinner = who;
    } // private void setGameWinner(String who)
    
    /**
     * getGameWinner
     * 
     * @return the game winner
     */
    public String getGameWinner() {
        return this.gameWinner;
    } // public String getGameWinner()
    
    /**
     * Entry point of the program.
     * 
     * @param args - <code>String[]</code> of runtime arguments
     */
    public static void main(String[] args) {
        // Swing is not thread safe, use SwingUtilities#invokeLater
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TicTacToe();
            }
        });
    } // public static void main(String[] args)
    
    /**
     * CellButtonHandler
     */
    private class CellButtonHandler implements ActionListener {
        
        /**
         * actionPerformed
         */
        @Override
        public void actionPerformed(ActionEvent e) {
            JButton pressed = (JButton) e.getSource();
            
            pressed.setText(TicTacToe.this.getCurrentPlayer());
            // pressed.setIcon(TicTacToe.this.getCurrentPlayerIcon());

            TicTacToe.this.count++;

            if (TicTacToe.this.gameOverWin() || TicTacToe.this.gameOverTie()) {
                System.out.println(TicTacToe.this.getGameWinner());
            }
            
            for (MouseListener ml : pressed.getMouseListeners()) {
                pressed.removeMouseListener(ml);
            }
        } // public void actionPerformed(ActionEvent e)

    } // private class CellButtonHandler implements ActionListener
    
    /**
     * private String getCurrentPlayer()
     */
    private String getCurrentPlayer() {
        this.xGoesFirst = this.xGoesFirst * -1;

        if (this.xGoesFirst == -1) {
            return pOne;
        }

        return pTwo;
    } //    private String getCurrentPlayer()
    
    /**
     * getCurrentPlayerIcon
     */
    private ImageIcon getCurrentPlayerIcon() {
        this.xGoesFirst = this.xGoesFirst * -1;

        if (this.xGoesFirst == -1) {
            return X_IMAGE;
        }

        return O_IMAGE;
    } // private ImageIcon getCurrentPlayerIcon()

    /**
     * Checks if the game ended in a win.
     * 
     * @return true if someone has won the game.
     */
    private boolean gameOverWin() {
        if (rowChecker() || colomnChecker() || diagChecker()) {
            return true;
        }

        return false;
    } //    private boolean gameOverWin()
    
    /**
     * Checks if the game ended in a tie.
     * 
     * @return true if there are no more moves to be made.
     */
    private boolean gameOverTie() {
        if (this.count >= MAX_MOVES) {
            return true;
        }

        return false;
    } // private boolean gameOverTie()
    
    /**
     * Checks the rows for a win.
     * 
     * @return true if one of the rows contains three X's or three O's.
     */
    public boolean rowChecker() {
        int row = 0; // row variable
        int col = 0; // column variable
        String mark = ""; // string to hold the first
                            // button in a row's text value

        while (row != NUM_ROWS) {
            col = row * NUM_ROWS;
            mark = this.getCellText(col);

            if (mark.equals(NON_PLAYER_CELL_VALUE)) {
                row = row + 1;
                continue;
            }

            if (this.cellsAreEqual(mark, col + 1)
                    && this.cellsAreEqual(mark, col + 2)) {
                
                this.setGameWinner("Row Winner: " + mark);
                return true;
            }

            row = row + 1;
        }

        // no win across the rows so we return false
        return false;
    } // public boolean rowChecker()
    
    /**
     * Checks the diagonals for a win.
     * 
     * @return true if one of the diagonals contains three X's or three O's.
     */
    public boolean diagChecker() {
        int leftToRight = 0; // start at the top left box
        int rightToLeft = 0; // start at the top right box
        int step = 0; // the number of cells to step over
        String mark = ""; // string to hold the buttons mark

        // first we'll start by checking the top-left to
        // bottom-right diagonal
        leftToRight = 0;
        step = NUM_COLS + 1;
        mark = this.getCellText(leftToRight);

        if (!mark.equals(NON_PLAYER_CELL_VALUE)) {
            if (this.cellsAreEqual(mark, step)
                    && this.cellsAreEqual(mark, (step * 2))) {
                
                this.setGameWinner("Diagonal Winner: " + mark);
                return true;
            }
        }

        // next we'll check the top-right to bottom-left diagonal
        rightToLeft = NUM_COLS - 1;
        step = NUM_COLS - 1;
        mark = this.getCellText(rightToLeft);

        if (!mark.equals(NON_PLAYER_CELL_VALUE)) {
            if (this.cellsAreEqual(mark, rightToLeft + step)
                    && this.cellsAreEqual(mark, rightToLeft + (step * 2))) {
                
                this.setGameWinner("Diagonal Winner: " + mark);
                return true;
            }
        }

        // no win on the diagonals so we return false
        return false;
    } // public boolean diagChecker()

    /**
     * colomnChecker
     */
    public boolean colomnChecker() {
        int row = 0; // row variable
        int col = 0; // column variable
        String mark = ""; // string to hold the buttons mark

        while (col != NUM_COLS) {
            row = col;
            mark = getCellText(row);

            if (mark.equals(NON_PLAYER_CELL_VALUE)) {
                col = col + 1;
                continue;
            }

            if (this.cellsAreEqual(mark, row + 3)
                    && this.cellsAreEqual(mark, row + 6)) {
                
                this.setGameWinner("Column Winner: " + mark);
                return true;
            }

            col = col + 1;
        }

        // no win down the columns so we return false
        return false;
    } // public boolean colomnChecker()
    
    /**
     * getCellText
     */
    private String getCellText(int which) {
        return this.cells[which].getText();
    } // private String getCellText(int which)
    
    /**
     * cellsAreEqual
     */
    private boolean cellsAreEqual(String mark, int index) {
        return mark.equals(this.getCellText(index));
    } // private boolean cellsAreEqual(String mark, int index)

    // private class restart implements ActionListener
    
    
} // public class TicTacToe extends JFrame

关于Java 对 Tic Tac Toe 程序没有意义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27117489/

相关文章:

swift - 使用 UIView 模板通过排版创建动态尺寸的 PDF

ruby - 假设每天都运行备份,如何仅使用 100 个备份副本来保留过去 1 年的备份?

java - 可编辑的 JComboBox 没有默认选择

java - J菜单 : while trigger event from Jmenu for open dialoge (confirmbox) Joption yes/No option click twice to work

python - 如何在 Pandas 数据框中有效地查找交替 boolean 值的索引

java - 有没有办法从子包中访问类中 `args[0]`的值

java - 吉德oss : how to get checkbox in Jpopupmenu?

java - 具有共享主键的两个表之间的 OneToOne

java - 如何为 Ondemand 触发器安排 Quartz Scheduler 作业?

java - JSON `date(...)` 到 `java.Util.Date` 使用 `org.json`