public class Board extends Thread {
    
    /**This Array contains the Tiles on which the players draw.
     * The tiles are aranged two dimensionally in this form:
     * 0 1 2
     * 3 4 5
     * 6 7 8
     */
    Tile tiles[] = new Tile[9];

    /**This Array contains the Players.
     * 
     */
    Player players[] = new Player[2];

    /**This Integer defines which character gets to draw first.
     * 
     */
    int firstPlayer;

    /**This Integer defines which character can currently draw on a tile.
     * 
     */
    int currentPlayer;

    /**This Integer tracts the amount of marks that were already placed.
     * 
     */
    int marks;

    /**Constructor of the Board class.
     * Creates the Tiles and Players and sets the player who starts the game.
     */
    Board() {
        for(int i = 0; i < players.length; i++) players[i] = new Player(i+1);
        firstPlayer = 0;
        initBoard();
    }

    Board(Player[] players, int firstPlayer) {
        this.players = players;
        this.firstPlayer = firstPlayer == 1 ? 0 : 1;
        initBoard();
    }

    private void initBoard() {
        for(int i = 0; i < tiles.length; i++) tiles[i] = new Tile(0,0,0);
        currentPlayer = firstPlayer;
        marks = 0;
    }

    /**Ends the turn by increasing the mark counter and changing the player.
     * Additionally it ends the game when certain conditions are met.
     */
    public void turnEnd() {
        marks++;
        if(marks > 4 && victoryCheck()) {
            System.out.println("You win Player " + currentPlayer);
            players[currentPlayer].playerScoreInc();
        } else if(marks == 9) {
            System.out.println("A draw");
        } else {
            currentPlayer = currentPlayer == 1 ? 0 : 1;
        }
    }

    /**Checks whether the current player has won the game.
     * 
     * @return current player won
     */
    public boolean victoryCheck() {
        boolean victory = false;
        for(int i = 0; i < 3; i++) {
            if(currentPlayer == tiles[0+i*3].get_owner() && currentPlayer == tiles[1+i*3].get_owner() && currentPlayer == tiles[2+i*3].get_owner()) victory = true;
            if(currentPlayer == tiles[0+i].get_owner() && currentPlayer == tiles[3+i].get_owner() && currentPlayer == tiles[6+i].get_owner()) victory = true;
        }
        if(currentPlayer == tiles[0].get_owner() && currentPlayer == tiles[4].get_owner() && currentPlayer == tiles[8].get_owner()) victory = true;
        if(currentPlayer == tiles[2].get_owner() && currentPlayer == tiles[4].get_owner() && currentPlayer == tiles[6].get_owner()) victory = true;
        return victory;
    }
}