Java не имеет смысла с программой Tic Tac Toe

1

Это был мой побочный проект в APCS за последние несколько недель, и я почти это сделал. Я в основном делаю простой gui с качелями, который имеет сетку кнопок и отображает изображения, такие как tic tac toe. Однако я просто не могу заставить последовательность выигрышей работать. Я прибегал к использованию метода, который я нашел в Интернете, и он все еще не работает; на самом деле это даже не имеет смысла. У меня есть 1 оператор печати для проверки значений, и он печатает 4 раза. Я просто полностью потерялся. Что-то нужно отметить, что я делаю это на своем домашнем ПК, поэтому у меня нет изображений на этом ПК, но я не думаю, что это повлияет на программу...?

Heres код (я думаю, проблема в 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;
                                    }
                }

Idk что-то с дисплеем кода, но если вы скажете мне, как исправить это, я это сделаю.

редактировать полный код:

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
}

Теперь старый метод, который я использовал, все еще существует, и часть перезапуска еще не закончена, но это все. (Старый метод, который я просто не мог заставить работать с логикой. Я пытался заставить его определить, выиграла ли одна из шашек или закончилась игра, но я просто не мог правильно понять логику)

EDIT win screen

NVM Я получил работу сейчас, мне просто нужно знать, куда ее поместить, чтобы она активизировалась, когда закончилась.

  • 0
    Отсутствие файлов изображений на ПК вызовет FileNotFoundException .
  • 1
    Измените вкладки на 4 пробела каждая.
Показать ещё 6 комментариев
Теги:
logic
swing

1 ответ

0

Вот ваш код с некоторыми дополнениями и комментариями. У меня нет времени объяснять все прямо сейчас, но я отредактирую этот ответ позже и добавлю объяснения. Посмотрите, посмотрите и дайте мне знать, если что-то запутанно или неправильно.

В настоящее время он поддерживает только игру в одной игре, а затем вам нужно закрыть и повторно запустить приложение. Ох и кнопки можно нажимать только один раз, потому что я MouseListener кнопку 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 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 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 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
  • 0
    Хорошо, дело в том, что это не дает мне ошибку из-за отсутствия моих фотографий, и это не исправляет это, оно все еще печатает несколько вещей и останавливает 5 щелчков. Помогло бы, если бы я опубликовал полный код, как теперь я знаю, как сделай это без всякой хрени в середине
  • 0
    да, это было бы очень полезно, просто добавьте код к своему вопросу с помощью редактирования.
Показать ещё 3 комментария

Ещё вопросы

Сообщество Overcoder
Наверх
Меню