java - 如何为井字游戏逻辑引用 JButtons 对象(Java 中的井字游戏)

标签 java swing object reference jbutton

我正在开发井字游戏。我添加了 9 个带有 ActionListeners 的 JButton。每个按钮都会正确监听 Action 事件。最后,我正在研究游戏的逻辑组件,但我仍然不知道如何去做。

如果您看一下我的 TicTacToeButton 类,我决定为扩展 JButton 的 TicTacToeButton 对象提供两个实例变量:一个表示按钮编号的整数变量(这样我就知道按下了哪个按钮 #。数字零是第一个数字)和一个字符变量,它将为玩家 1 的名为 boardLogic 的字符数组分配一个“o”字符,为玩家 2 分配一个“x”。

问题是我不知道如何在我的 TicTacToeBoard 类中引用我的 TicTacToeButton 数组中的元素来执行游戏中实际按下的 JButton。 Java 对象中是否有一个方法可以告诉您是按下了编号为 0 的 JButton 还是按下了编号为 1 的 JButton,这与我在下面陈述的代码相对应。

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Point;
import javax.swing.JFrame;
import javax.swing.JPanel;

/*
 * The TicTacToeBoard is an object that has characterisitics of a JFrame 
 */
public class TicTacToeBoard extends JFrame {

    /* create an array of characters that holds 9 elements 
     *  to create a model for the tic-tac-toe board logic since the board has 9 boxes
     *  create the board from a separate class to minimize bugs and for easier debugging
     *  simulate the game's logic by creating an array of characters
     */
    public static char[] boardLogic = {};
    // number of buttons in the game
    static int numOfButtons = 9;
    // TicTacToeButton is an object that extends JButton
    static TicTacToeButton[] buttons;

    public TicTacToeBoard() {
        // setTitle to the frame
        setTitle("TicTacToe Game");
        /* call this method to the GameFrame object if you do not call this 
         * method the JFrame subclass will not actually close
         */
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        /* set size to an appropriate size create a dimension object 
         * notice my Dimension object does not have a variable this is 
         * a prefer way to create this object since no further 
         * operations will be perform on this object besides this operation 
         */
        setSize(new Dimension(1000, 1000));
        // upon creating the object set the location of the frame to the center of the screen
        setLocation(new Point(0, 0));
        // prevent the user from resizing the GameFrame object
        // uncomment bottom to prevent window maximumization 
        //setResizable(false);
    }

    public void printButtons(Container contentPane) {
        JPanel gamePanel = new JPanel();
        gamePanel.setLayout(new GridLayout(3, 3));
        // the idea of boardLogic is creating a 9 element character array to simulate the game's logic
        boardLogic = new char[numOfButtons];
        // creates the objects of the type JButtons
        buttons = new TicTacToeButton[numOfButtons];
        // create 9 buttons for the game using a for loop
        for (int i = 0; i < buttons.length; i++) {
            // create a new JButton object every loop   
            buttons[i] = new TicTacToeButton(i);
            // set a default value. I use '-' for simplicity.
            boardLogic[i] = buttons[i].getButtonChar();
            // and add it to the frame
            gamePanel.add(buttons[i]);
        }
        contentPane.add(gamePanel, BorderLayout.CENTER);
    }
}

.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;


/* the class design is that we will create a class that has characteristics
 * of what a JButton can do but can also hear for action events
 */
public class TicTacToeButton extends JButton implements ActionListener {

    /* referring my Buttons with names denoted as String type
     * set it empty for now. I will name the JButtons using a for loop
     * the program will use buttonNumber assigned to each button
     * to create the game's logic
     */
    private int buttonNumber = 0;
    // Each character assigned to each button is assigned a hyphen by default
    private char buttonChar = '-';

    public TicTacToeButton(int buttonNumber) {
        // call the JButton super class constructor to initialize the JButtons
        super();
        // set the name of the parameter to the data member of the JButton object 
        this.buttonNumber = buttonNumber;
        // upon creating of the JButton the button will add ActionListener to itself
        addActionListener(this);
    }

    // a get method that retrieves the button's object data member
    public int getButtonNumber() {
        return buttonNumber;
    }

    // everytime the user press a button set the number 10 as the button number
    public void setButtonChar(char buttonChar) {
        if (buttonChar == 'O' || buttonChar == 'X') {
            this.buttonChar = buttonChar;
        }
    }

    public static void printArray() {
        for (int i = 0; i < TicTacToeBoard.boardLogic.length; i++) {
            System.out.println(TicTacToeBoard.boardLogic[i]);
        }
    }

    public char getButtonChar() {
        return buttonChar;
    }

    public void actionPerformed(ActionEvent e) {
        /* both cases must be true before this code can happen
         *  After Player A turn, then is Player B turn
         */
        if (e.getSource() instanceof JButton && TicTacToeBoard.currentPlayerTurn.equals(TicTacToeMain.firstPlayerName)) {
            // Player A uses circle 
            /* the state of the image for the Buttons will change depending on the player's turn 
             *  Player A will use the cross sign , Player B will use Circle Sign
             */
            ImageIcon icon = new ImageIcon("buttonImages/circle-sign.png");
            TicTacToeBoard.currentPlayerTurn = TicTacToeMain.secondPlayerName;
            // set the appropriate picture as the JButton icon
            setIcon(icon);
            // prevent user from clicking the button more than once
            setEnabled(false);
            //increment buttonClick variable by one for each mouse click 
            TicTacToeBoard.buttonClicks += 1;
            //notify both players whose turn is it
            TicTacToeMain.contentPane.remove(TicTacToeBoard.currentPlayerTurnLabel);
            TicTacToeBoard.printCurrentPlayerTurnLabel(TicTacToeMain.contentPane);
            // Tests the Winning conditions of the player's 
            TicTacToeBoardLogic boardLogic = new TicTacToeBoardLogic();
            boardLogic.checksWinningConditions();
        } else {// After Player B turn, then is Player A turn
            // Player B uses cross 
            /* the state of the image for the Buttons will change depending on the player's turn 
             *  Player A will use the cross sign , Player B will use Circle Sign
             */
            ImageIcon icon = new ImageIcon("buttonImages/x-sign.jpg");
            TicTacToeBoard.currentPlayerTurn = TicTacToeMain.firstPlayerName;
            // set the appropriate picture as the JButton icon
            setIcon(icon);
            // prevent user from clicking the button more than once
            setEnabled(false);
            //increment buttonClick variable by one for each mouse click 
            TicTacToeBoard.buttonClicks += 1;
            //notify both players whose turn is it
            TicTacToeMain.contentPane.remove(TicTacToeBoard.currentPlayerTurnLabel);
            TicTacToeBoard.printCurrentPlayerTurnLabel(TicTacToeMain.contentPane);
        }
        // if all buttons been pressed, the game makes a decision
        // Tests the Winning conditions of the player's 
        TicTacToeBoardLogic boardLogic = new TicTacToeBoardLogic();
        boardLogic.checksWinningConditions();
    }
}

最佳答案

你的赢家是稍微扩展一下这个方法:

public TicTacToeButton(int buttonNumber) { 
    // call the JButton super class constructor to initialize the JButtons 
    super(); 
    // set the name of the parameter to the data member of the JButton object  
    this.buttonNumber = buttonNumber; 
    // upon creating of the JButton the button will add ActionListener to itself 
    addActionListener(this); 
    setActionCommand(Integer.toString(buttonNumber));*************
} 

(我的添加后缀有星号)

这将“命名”与按钮关联的 Action 事件。

然后在 Actionperformed (ActionEvent e) 中,您可以使用 e.getActionCommand() 获取该 ActionCommand。 对于九个,最简单的可能是一个 switch 语句。记得用 varName.equals(e.getActionCommand()) 来比较。

HTH

关于java - 如何为井字游戏逻辑引用 JButtons 对象(Java 中的井字游戏),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12465051/

相关文章:

java - 如何计算 LinkedList<String> 的实际大小(以字节为单位)?

java - 为什么小程序在调整到我指定的大小之前会以默认大小启动?

javascript - 元素中的 polymer 定义属性

java - 画图程序麻烦java

Java:AbsoluteLayout 中的额外空间

java - Swing 逐页转换(MultiPages Widget)

java - 哈希集对象

javascript - 如何在 JavaScript 中搜索其他不区分大小写的对象?与 _.where() 一样,仅不区分大小写

java - 如何获取 ComboFieldEditor 的值?

java - 当相应的 JTextfield 为空时,如何填充 JTable 中的所有项目