简体   繁体   中英

How do you keep track of a board game positions live? (Java)

I am creating a board game in java using a 2d array. The board is shown in a JFrame.

How do you "move" pieces on the 2d array and display them live on the screen (the 2d array is shown with buttons).

Is there a better way to show my game with a 2d array and what would be a good algorithm to update my game?

use the mvc mini architecture :

import java.util.Observable;
import java.util.Observer;
public class So44075321 {
    enum Piece {
        vacant,knight,bishop;
    }
    static class Game extends Observable implements Observer { // model
        Game() {
            for(int i=0;i<n;i++)
                for(int j=0;j<n;j++)
                    board[i][j]=Piece.vacant;
            addObserver(this);
        }
        @Override public String toString() {
            StringBuffer stringBuffer=new StringBuffer();
            for(int i=0;i<n;i++) {
                for(int j=0;j<n;j++)
                    stringBuffer.append(board[i][j]+" ");
                stringBuffer.append('\n');
            }
            return stringBuffer.toString();
        }
        void move(int i,int j,int k,int l) {
            Piece piece=board[i][j];
            board[i][j]=Piece.vacant;
            board[k][l]=piece;
            setChanged();
            notifyObservers();
        }
        final int n=3;
        Piece[][] board=new Piece[n][n];
        @Override public void update(Observable o,Object hint) { // view
            
            System.out.println("update: "+toString());
        }
    }
    public static void main(String[] args) { // controller
        Game game=new Game();
        game.board[0][0]=Piece.knight;
        System.out.println(game);
        game.move(0,0,1,1);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM