简体   繁体   中英

How to create a game board with arrays in Java?

I am currently working on an assignment to create a Connect 4 style game in Java. A large section of the code has been provided in several different classes and we are required to build the game based on the comments for the code that is provided. The columns for the board are created as an array in one class, then the game board is to be created as an array that is populated by column objects in another class. I'm quite new to Java and I am not sure what the best way to create the board is. We are also required to display the board in a grid with each column bordered by pipes with the columns reading 1-6 from bottom to top and rows reading 1-7 from left to right (first element of first column in the bottom left corner and last element of last column in the top right).

The board should look like this:

    1 2 3 4 5 6 7 
 * ---------------
 * | | | | | | | |
 * | | | | | | | |
 * | | | | | | | |
 * | | | | | | | |
 * | |X| | | |O| |
 * |O|O|X| |X|O| |   
 * ---------------
 *  1 2 3 4 5 6 7 

Creating the game board itself is the most pressing issue right now, but help with both would be greatly appreciated. The Board and Column classes are attached below:

public class Board {
    
    /** Number of rows on the board */
    private final static int NUM_ROWS = 6;
    
    /** Number of columns on the board */
    private final static int NUM_COLS = 7;
    
    /** Array of Column objects, which contain token values */
    private Column[] board = new Column[NUM_COLS];
    
    /**
     * Loop through the board array, to instantiate and initialize each element as a new Column.
     */
    public Board() {
        //TODO create game board
    }
    
    /**
     * Validate the column number, output an error message and return false if its invalid.
     * Try to put the token in the specified column of the board. Output an error message and return false if it does not work.
     * 
     * @param column The column in which to place the token, valid values are 1 - 7.
     * @param token Token character to place on the board, an X or an O.
     * @return True if putting the token on the column is successful, else false.
     */
    public boolean makeMove(int column, char token) {
        //TODO create method to make a move
    }
    
    /**
     * Checks for Computer's victory by looking for complete vertical and horizontal nibbles.
     * 
     * @return True if any nibbles of O's are found on the board, otherwise false.
     */
    public boolean checkVictory() {
        
        // TODO Loop through each column to check for victory.
        // hint: as soon as any column has a nibble, you can return true and stop checking further.
        
        
        // TODO: Loop through each row to look for horizontal nibbles
        for (int row = 1; row <= NUM_ROWS; row++) {
            // TODO: Loop through each column in the row to check the value of the column and row.
            // Use a counter to track the number of X's or O's found.
            // hint: you may need to reset the counter to 0 at some point.
            
            
            // TODO: if a nibble is found, return true
            
        }
        
        // return false
        return false;
    }
    
    /**
     * Checks each column to see if there is room enough for at least 4 more O values.
     * Checks final row to see if there is room enough for at least 4 O (non-X) values.
     * @return True if the computer has no more safe moves, else false.
     */
    public boolean isFull() {
        //TODO check if board contains any possible moves
    }
    
    /**
     * Displays each column number, divided by spaces.
     * Displays, in a grid, the contained in each column of each row.
     * Displays the column numbers again at the bottom.
     * Example:
     *
     *  1 2 3 4 5 6 7 
     * ---------------
     * | | | | | | | |
     * | | | | | | | |
     * | | | | | | | |
     * | | | | | | | |
     * | |X| | | |O| |
     * |O|O|X| |X|O| |   
     * ---------------
     *  1 2 3 4 5 6 7 
     *
     *
     */
    public void display() {
        final String numDisplay = " 1 2 3 4 5 6 7 ";
        final String hr = "---------------";
        
        System.out.println(numDisplay);
        System.out.println(hr);
        
        //TODO display game board here
        
        System.out.println(hr);
        System.out.println(numDisplay);
    }
    
}

===========================================================================================

public class Column {

    private static final int MAX_HEIGHT = 6;
    private int height = 0;
    private char[] column;
    
    /**
     * Default constructor - initialize the column array and each element of the column array to contain a blank space.
     */
    public Column() {
        column = new char[MAX_HEIGHT];
        Arrays.fill(column, ' ');
    }
    
    /**
     * Return the value in the specified row.
     * 
     * @param row The specified row. Valid values are 1 - 6. 
     * @return The character in the specified row, or blank if an invalid row was requested.
     */
    public char get(int row) {
        char foundChar;
        
        if (row >= 1 && row <= 6) {
            foundChar = column[row - 1];
        } else {
            foundChar = ' ';
        }
        return foundChar;
    }
    
    /** Put the specified token character at the top of the column, increments the height, and returns true.
     * 
     * @param token Token character to place on the board, an X or an O.
     * @return True if there is room in the column for the token, else false.
     */
    public boolean put(char token) {
        boolean placed;
        if (height >= 0 && height < 6) {
            column[height] = token;
            placed = true;
            height++;
        } else {
            placed = false;
        }
        return placed;
    }
    
    /**
     * Check if the column contains a Nibble.
     * 
     * @return True if the column contains 4 or more consecutive 'O' tokens, else false.
     */
    public boolean checkVictory() {
        //TODO finish implementing checkVictory 
        boolean win = false;
        return win;
    }
    
    /**
     * Returns the current height of the Column.
     * @return the height of the column
     */
    public int getHeight() {
        return this.height;
    }
}

Welcome to Stackoverflow, ChewyParsnips.

Since this a homework question, I will not give you any code but I'll help you dissect the question and re-phrase some parts to, hopefully, help with the understanding.

You have two questions: How to represent the board? and How to print the board?

How to represent the board?

The answer lies in your own text:

The columns for the board are created as an array in one class, then the game board is to be created as an array that is populated by column objects in another class.

But we need to translate this into Java.

In your Column class, you have private char[] column , which is the first array.

In your Board class, you have private Column[] board = new Column[NUM_COLS] , which is the second array ready to receive column objects. Now, you need to populate the array with Column objects. In the Board constructor, ie,

public Board() {
    //TODO create game board
}

You need to run through the size of the array and make new Column objects. When do this, beware of boundaries.

How to print the board?

Again, you need to run through the array in the Board , but now also the underlying array in the Column object. Here, you need to be careful with how you traverse the grid because you need to print a line but your board is based on columns, so you need to change this representation while iterating the arrays.

Further considerations

While Connect Four is focused on dropping pieces down a column, it might make sense to structure the grid with focus on columns. However, you also need to check rows and diagonals for nibbles, and you need to print the board, which works on a row basis. So, if you weren't locked by the structure of the homework, I'd recommend a one-dimensional array where you present multiple methods that give different views.

you can simply write

public Board() {
    for(int i=0; i<board.length;i++) {
        board[i] = new Column()
    }
}

This initializes all values in the array when you create an instance of Board .

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