Search code examples
javatic-tac-toe

Play method for TicTacToe java


So we got an excercise and need to write a tictactoe class, we need to work with a 2d int array as the board and 2 players, one has a "1" as the "X" and the other one a "2" as the "O", "0" is for empty field. Now we need to write a method for the players to actually set something on the field, but all I can think about is stuff to do with a string or char board and nothing really with an int board. How do you realize this setting of a problem with a number on an int board? Thanks for any help!

I already got a method which checks if there's any free spot available on the board anyways, which should be correct.

public class TicTacToe extends BasicBoard implements Game {

    int PlayerA = 1;
    int PlayerB = 2;
    int empty = 0;
    private int row, column;
    private int[][] board = new int[column][row];


    public boolean isboardfull(int row, int column) {
        for (int i = 0; i <= column; i++)
        {
            for (int j = 0; j <= row; j++)
            {
                if (board[i][j] == PlayerA || board[i][j] == PlayerB)
                    return true;
            }
        }
        return false;
     }
     public  void playerturn(){
        if (!isboardfull(row, column))

     }
}

Solution

  • Your TicTacToe class extends from the BasicBoard and Game classes but you have not provided them. I assume that these classes give you methods to render the board and control the game evolution but since we don't have them I have included something similar (and simple) in my example (to demonstrate how it works). You can skip the game, printBoard, resetBoard, and endGame methods if these are provided by the BasicBoard and Game classes.

    Here is a list of assumptions I have made:

    • The players are asked for the coordinates where to play
    • The game ends when the board is full. A more complex version should check every iteration of the game if one of the players has won.

    And here a general explanation of my approach:

    • The mapping between X and O to 1 and 2 is set to static constant since this will never change.
    • The number of rows and columns may vary between executions and its parametrized in the TicTacToe constructor.
    • The players fill the information through the standard input when prompted.
    • The game function asks for the players to move and renders the board (on the standard output) until the board is completely filled.
    • The isBoardFull function checks if there are empty slots on the board or not. Thus, if we find an empty slot we know it is not full, otherwise we need to keep searching for empty slots. If we search through all the board and there are no empty slots, then it is full. (in my opinion, this part is miss-written in the coded you provided)
    • The playerTurn function asks for the coordinates where the player wants to play and fills the board. To do so, we scan 2 lines of the standard input, convert them to int and check if the position is empty and within bounds. If so, we mark the position with the player number.

    The code:

    public class TicTacToe {
    
        private static final int PLAYER_A = 1;
        private static final int PLAYER_B = 2;
        private static final int EMPTY = 0;
    
        private final int numRows;
        private final int numColumns;
        private final int[][] board;
    
        private final Scanner inputScanner;
    
    
        public TicTacToe(int numRows, int numColumns) {
            // Retrieve board sizes
            this.numRows = numRows;
            this.numColumns = numColumns;
    
            // Instantiate board
            this.board = new int[numRows][numColumns];
    
            // Initialize board
            resetBoard();
    
            // Initialize the input scanner (for player choices)
            this.inputScanner = new Scanner(System.in);
        }
    
        public void game() {
            // Initialize the game
            int numMoves = 0;
            printBoard(numMoves);
    
            // Play until the game is over
            while (!isBoardFull() && !hasPlayerWon()) {
                // A or B player should move
                int currentPlayer = (numMoves % 2 == 0) ? PLAYER_A : PLAYER_B;
                playerTurn(currentPlayer);
    
                // We increase the number of moves
                numMoves += 1;
    
                // We render the board
                printBoard(numMoves);
            }
    
            // Check winner and close game
            endGame();
        }
    
        private void resetBoard() {
            for (int i = 0; i < this.numRows; ++i) {
                for (int j = 0; j < this.numColumns; ++j) {
                    this.board[i][j] = EMPTY;
                }
            }
        }
    
        private void printBoard(int currentMove) {
            System.out.println("Move: " + currentMove);
            for (int i = 0; i < this.numRows; ++i) {
                for (int j = 0; j < this.numColumns; ++j) {
                    System.out.print(this.board[i][j] + " ");
                }
                System.out.println();
            }
    
            // A new line to split moves
            System.out.println();
        }
    
        private boolean isBoardFull() {
            for (int i = 0; i < this.numRows; ++i) {
                for (int j = 0; j < this.numColumns; ++j) {
                    if (this.board[i][j] == EMPTY) {
                        // If there is an empty cell, the board is not full
                        return false;
                    }
                }
            }
            // If there are no empty cells, the board is full
            return true;
        }
    
        private boolean hasPlayerWon() {
            // TODO: Return whether a player has won the game or not
            return false;
        }
    
        private void playerTurn(int currentPlayer) {
            // Log player information
            System.out.println("Turn for player: " + currentPlayer);
    
            // Ask the player to pick a position
            boolean validPosition = false;
            while (!validPosition) {
                // Ask for X position
                int posX = askForPosition("row", this.numRows);
                // Ask for Y position
                int posY = askForPosition("column", this.numColumns);
    
                // Check position
                if (posX >= 0 && posX < this.numRows) {
                    if (posY >= 0 && posY < this.numColumns) {
                        if (this.board[posX][posY] == EMPTY) {
                            // Mark as valid
                            validPosition = true;
                            // Mark the position
                            this.board[posX][posY] = currentPlayer;
                        } else {
                            System.out.println("Position is not empty. Please choose another one.");
                        }
                    } else {
                        System.out.println("Column position is not within bounds. Please choose another one.");
                    }
                } else {
                    System.out.println("Row position is not within bounds. Please choose another one.");
                }
            }
    
        }
    
        private int askForPosition(String rc, int dimensionLimit) {
            System.out.println("Select a " + rc + " position between 0 and " + dimensionLimit);
    
            return Integer.valueOf(this.inputScanner.nextLine());
        }
    
        private void endGame() {
            // Close input scanner
            this.inputScanner.close();
    
            // Log game end
            System.out.println("GAME ENDED!");
    
            // TODO: Check the board status
            System.out.println("Draw");
        }
    
        public static void main(String[] args) {
            TicTacToe ttt = new TicTacToe(3, 4);
            ttt.game();
        }
    
    }
    

    Example Output:

    Move: 0
    0 0 0 0 
    0 0 0 0 
    0 0 0 0 
    
    Turn for player: 1
    Select a row position between 0 and 3
    4
    Select a column position between 0 and 4
    1
    Row position is not within bounds. Please choose another one.
    Select a row position between 0 and 3
    1
    Select a column position between 0 and 4
    1
    Move: 1
    0 0 0 0 
    0 1 0 0 
    0 0 0 0 
    
    Turn for player: 2
    .
    .
    .
    Move: 12
    2 2 1 2 
    1 1 2 1 
    1 2 1 2 
    
    GAME ENDED!
    Draw