如何从事件中获取数据到主函数?

How to get data from events to the main function?

我目前正在制作国际象棋游戏。这也是我尝试创建图形用户界面的第一个项目,所以请告诉我是否有更简洁的方法来编写此代码。因此,我使用 java swing 创建了 64 个按钮,这些按钮在按下时将它们的坐标打印到控制台。

我还设法在我的主要方法中使用控制台输入创建了一个到 运行 我的国际象棋引擎的循环。我的问题是我不知道如何从我的 eventListeners 获取坐标到我的主循环,以便它移动一块。

我添加了主循环和执行动作的方法。希望这些代码足以解决我的问题。

感谢所有花时间帮助我的人!

    public static void main(String[] args) throws IOException{
    int[] coordinates = new int[4];
    
    Player player = new Player();
    Board board = new Board();
    Input input = new Input();
    board.showBoard();
    // here I give the gui object the references to my input and board objects 
    // so that it can call their methods and thereby give the information to them   
    Gui gui = new Gui(board, input); 

    
    while(!player.isCheckmate(board)) { 
    
        coordinates = input.getInput(board, player).clone();// get coordinates xpos, ypos, xposnew, yposnew
    
        Piece activePiece = board.getPiece(coordinates[0], coordinates[1]); // get the chosen piece
        
        if(!activePiece.isLegalMove(board, coordinates[2], coordinates[3]))// move the active piece to chosen destination
        {
            System.out.println("No legal move. Try again");
            continue;
        }
        
        activePiece.move(board, coordinates[2], coordinates[3]);
        
        player.switchPlayerTurn();
        
        player.isCheckmate(board);
        board.showBoard();
    }
     
}

这里是 actionPerformed 方法

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        // TODO Auto-generated method stub
        JButton button = (JButton) e.getSource();
        String[] numbers = button.getActionCommand().split("");
        
        if(coordinates[2] !=-1)
        {
            for(int i = 0; i < coordinates.length; i++)
                coordinates[i] = -1;
        } 
        if(coordinates[0] == -1) {
            coordinates[0] = Integer.parseInt(numbers[0]);
            coordinates[1] = Integer.parseInt(numbers[1]);
        } else if(coordinates[2] == -1) {
            coordinates[2] = Integer.parseInt(numbers[0]);
            coordinates[3] = Integer.parseInt(numbers[1]);
            }
        
        System.out.println("x coodinate = " + Integer.toString(coordinates[0]));
        System.out.println("y coodinate = " + Integer.toString(coordinates[1]));
        System.out.println("destination x coodinate = " + Integer.toString(coordinates[2]));
        System.out.println("destination y coodinate = " + Integer.toString(coordinates[3]));
        
    }

关于将数据从您的事件传递到主事件,您需要携带对管理 Piece 坐标的对象的引用(我假设这是您的 Board 对象)。您需要添加如下内容:

class Board {
  //Other class stuff
  
  public void setPiecePosition(Piece targetPiece, Point coordPoint) {
    //Code to update your tracking
  }
}

然后在您的活动中添加类似这样的内容:

board.setPiecePosition(targetPiece, new Point(xCoord, yCoord));