Как создать игровую доску с массивами в Java? - PullRequest
0 голосов
/ 06 августа 2020

В настоящее время я работаю над заданием по созданию игры в стиле Connect 4 в Java. Большой раздел кода предоставлен в нескольких различных классах, и мы должны построить игру на основе комментариев к предоставленному коду. Столбцы для доски создаются как массив в одном классе, затем игровое поле должно быть создано как массив, который заполняется объектами столбцов в другом классе. Я новичок в Java и не уверен, как лучше всего создать доску. Нам также необходимо отобразить доску в сетке, где каждый столбец будет ограничен трубами, причем столбцы будут читать 1-6 снизу вверх, а строки 1-7 слева направо (первый элемент первого столбца в нижнем левом углу и последний элемент последнего столбца в правом верхнем углу).

Доска должна выглядеть так:

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

Создание самого игрового поля сейчас является наиболее актуальной проблемой, но поможет с обоими был бы очень признателен. Классы Board и Column прикреплены ниже:

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

Ответы [ 2 ]

3 голосов
/ 06 августа 2020

Добро пожаловать в Stackoverflow, ChewyParsnips.

Поскольку это вопрос домашнего задания, я не дам вам никакого кода, но я помогу вам проанализировать вопрос и перефразировать некоторые части, чтобы, надеюсь, помочь с понимание.

У вас есть два вопроса: Как изобразить доску? и Как распечатать доску?

Как изобразить доску?

Ответ кроется в вашем собственном тексте:

столбцы для доски создаются как массив в одном классе, затем игровое поле должно быть создано как массив , который заполняется объектами столбца в другом классе.

Но нам нужно преобразовать это в Java.

В вашем классе Column у вас есть private char[] column, который является первым массивом.

В вашем классе Board у вас есть private Column[] board = new Column[NUM_COLS], который является вторым массив, готовый к приему объектов столбцов. Теперь вам нужно заполнить массив объектами Column. В конструкторе Board, т. Е.

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

, вам нужно просмотреть размер массива и создать новые Column объекты. Когда это нужно делать, остерегайтесь границ.

Как распечатать доску?

Опять же, вам нужно пройти через массив в Board, но теперь также и базовый массив в Column объект. Здесь вам нужно быть осторожным с тем, как вы перемещаетесь по сетке, потому что вам нужно напечатать строку, но ваша доска основана на столбцах, поэтому вам нужно изменить это представление во время итерации массивов.

Дополнительные соображения

В то время как Connect Four ориентирован на опускание частей вниз по столбцу, может иметь смысл структурировать сетку с фокусом на столбцах. Однако вам также необходимо проверить строки и диагонали на полубайты, и вам нужно распечатать доску, которая работает на основе строк. Итак, если бы вы не были привязаны к структуре домашнего задания, я бы порекомендовал одномерный массив, в котором вы представляете несколько методов, которые дают разные представления.

0 голосов
/ 07 августа 2020

вы можете просто написать

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

Это инициализирует все значения в массиве, когда вы создаете экземпляр Board.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...