【问题标题】:Java not making sense with Tic Tac Toe programJava 对井字游戏没有意义
【发布时间】:2014-11-25 01:50:38
【问题描述】:

这是我过去几周在 APCS 中的副项目,我几乎完成了。我基本上是在用 swing 制作一个简单的 gui,它有一个按钮网格并显示像井字游戏这样的图像。但是,我就是无法让获胜序列发挥作用。我已经使用了我在网上找到的方法,但仍然无法正常工作;事实上,它甚至没有意义。我有 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 我现在让它工作了,我只需要知道将它放在哪里,以便它在结束时激活。

【问题讨论】:

  • PC 上没有图像文件会抛出FileNotFoundException
  • 将每个选项卡更改为 4 个空格。
  • 你的gameover() 方法太糟糕了!
  • 在放弃修改逻辑后,我重新编写了游戏结束方法,所以是的,它很烂
  • 让我调试你的项目并修改一些东西,然后我会发布一些工作代码。应该只需要 10 - 20 分钟。

标签: java swing logic


【解决方案1】:

这是您的代码,其中包含一些附加项和 cmets。我现在没有时间解释所有内容,但我稍后会编辑此答案并添加解释。看看看看,如果有什么令人困惑或错误的地方,请告诉我。

目前只支持玩一个游戏,然后你必须关闭并重新运行应用程序。哦,按钮只能按下一次,因为我在按下按钮后删除了按钮的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

【讨论】:

  • 好吧,事情是它没有因为没有我的照片而给我一个错误,它没有修复它,它仍然打印出多个东西并停止 5 次点击。如果我发布它会有帮助吗完整的代码现在我知道如何做到这一点,而中间没有所有的废话
  • 是的,这将非常有帮助,只需通过编辑将代码添加到您的问题中。
  • 我知道 else if 语句,但是每当我在 java 中使用它们时,我都会得到一个没有 if 错误的 else,现在我只是嵌套它们。即使新游戏结束,点击 4 次后它仍然停止工作
  • 好的,代码可以工作,但我想要一个获胜屏幕,因为玩游戏有点尴尬,而且必须查看控制台才能看到获胜者。这是我到目前为止所拥有的,但它似乎打破了一切。 I 10 错误 8 使用此符号时未找到符号。和 2 用于 JLabel。我将把代码放在主要问题中,因为我认为我不能把它放在这里
  • 我的屏幕有点工作,但我不知道在哪里放置 else 语句以便在游戏结束时触发它。
猜你喜欢
  • 2015-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多