当前位置: 首页 > 知识库问答 >
问题:

如何为Tic-tac-Toe游戏逻辑引用JButtons对象(Java中的Tic-tac-Toe游戏)

常乐
2023-03-14

我正在做一个井字游戏。我添加了带有ActionListeners的9个JButton。每个按钮都会正确监听操作事件。最后,我正在研究游戏的逻辑部分,但我被困在了如何进行这项工作上。

如果您查看我的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();
    }
}

共有3个答案

袁法
2023-03-14

您可能需要考虑将模型(带有X和O的TictaToe板)与视图(JButtons)分开。这将允许您将游戏的当前状态传递给任何您想要的方法,而不需要Swing组件的开销。

狄令
2023-03-14

要知道TictaBoard类中按下了哪个按钮,我建议在TictaToe类中实现action listener,而不是TictaToeButton类。

这是Windows类的一个小演示代码,在您的情况下是TicTacToeBoard。

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class Window implements ActionListener{

static Buttons[] buttons = new Buttons[2];

public Window(){
    JFrame f = new JFrame();
    f.setSize(400,400);
    JPanel p = new JPanel();
    GridLayout gl = new GridLayout(1,2);
    p.setLayout(gl);
    for(int i = 0; i<2; i++){
        buttons[i] = new Buttons(i);
        buttons[i].addActionListener(this);
        p.add(buttons[i]);
    }
    f.add(p);
    f.setVisible(true);
}

public static void main(String... args){
    new Window();
}

@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    if(e.getSource() == buttons[0] ){
        System.out.println("0");
    }

}

}

下面是Buttons类的演示,以TictoeButton为例。

import javax.swing.JButton;


public class Buttons extends JButton{

int num = 0;

public Buttons(int num){
    this.num = num;
}



}
雍兴修
2023-03-14

您的赢家是将此方法稍加扩展:

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));*************
} 

(我添加的内容后缀为星星)

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

然后,在动作执行(ActionEvent e)中,您可以使用e.getActionCommand()获得该ActionCommand。使用9,您最简单的可能是一个开关语句。请记住使用varName.equals(e.getActionCommand())来比较它。

 类似资料:
  • 首先,我是java的初学者,我正在尝试模拟TicTacToe游戏。我想使用游戏树为所有状态创建一个可能的树。树中的每个节点都将代表状态并使用此树来决定下一步要做的事情。我计划按如下方式进行, > 接口类包括表示单个移动所需的信息。 抽象/接口类包括以下方法: a、 返回一个新的状态对象,该对象表示应用该移动后游戏的状态。 B.如果当前状态代表其中一名玩家的胜利,则此游戏的获胜者ID。 c、 返回当

  • 我正在做一个井字游戏项目,我正在使用9个按钮和图像(Circle.jpg,Cross.jpg)。首先,我想向你们澄清一件事,所以首先我用字母(“X”),(“O”)制作了这个游戏,现在我用这个游戏的图像,也是电脑对玩家的游戏运行后,当我点击按钮显示我在那个按钮上交叉,没错,电脑会自动在另一个按钮上画圆圈! 问题是,当我点击按钮时,它会显示一个十字,这是正确的。但电脑不会用圆圈挡住我的行。 }

  • 我该怎么做? 下面是我的代码:

  • 对角线从右到左 在这里,支票中奖者代码结束。

  • 我一直在更新我在网上找到的一个有点过时的tic-tac-toe代码(好像它现在真的可以工作了:P)。我的代码几乎完成了,但我一直有一个相同的问题。tic tac趾板内的3x3按钮工作完美,除了一件事,它们被点击后的颜色始终是背景,我尝试过纠正这一点,但它所做的只是使按钮完全不改变颜色。这两种颜色是红色和绿色,我希望这样,当每个玩家点击一个按钮,它会改变他们的颜色。 主要游戏代码: