loloof64
08/31/2020, 7:44 AMpackage com.developpez.tictactoe
import javafx.geometry.Insets
import javafx.scene.layout.GridPane
import tornadofx.*
import java.lang.IllegalStateException
class TicTacToeApp : App(Board::class)
open class CellValue
class Empty: CellValue()
class Cross: CellValue()
class Circle: CellValue()
data class CellClickedEvent(val row: Int, val col: Int) : FXEvent()
class Board : View("Tic Tac Toe") {
    var cellsValues: Array<Array<CellValue>> = Array(3) {Array(3) {Empty()}}
    var currentPlayer: CellValue = Cross()
    init {
        subscribe<CellClickedEvent> {
            if (cellsValues[it.row][it.col] == Empty()) {
                cellsValues[it.row][it.col] = currentPlayer
                refreshContent()
                currentPlayer = when (currentPlayer) {
                    is Cross -> Circle()
                    is Circle -> Cross()
                    else -> throw IllegalStateException("Current player is not defined.")
                }
            }
        }
    }
    private fun refreshContent() {
        root.children.removeAll()
        buildContent()
    }
    private fun buildContent()  {
        with (root) {
            repeat(3) { row ->
                row {
                    apply {
                        repeat(3) { col ->
                            button {
                                gridpaneConstraints {
                                    margin = Insets(2.0)
                                    setPrefSize(100.0, 100.0)
                                }
                                action {
                                    fire(CellClickedEvent(row, col))
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    override val root = GridPane()
}