Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class ChessyRootComponent private constructor(
- val rootElement: HTMLDivElement,
- val squares: Array<Array<SquareComponent>>
- ) {
- companion object {
- fun create(onSquareClick: (x: Int, y: Int) -> Unit): ChessyRootComponent {
- val rootEl = document.create.div("chessy-root")
- val boardEl = rootEl.append.div("chessy-board")
- val squares =
- Array(8) { x ->
- Array(8) { y ->
- SquareComponent.create((x + y) % 2 == 1) { onSquareClick(x, y) }
- }
- }
- for (l in arrayOf("", "a", "b", "c", "d", "e", "f", "g", "h", "")) {
- boardEl.append.div("chessy-square chessy-square-out") {
- text(l)
- }
- }
- for (y in 7 downTo 0) {
- boardEl.append.div("chessy-square chessy-square-out") {
- text(y + 1)
- }
- for (x in 0..7) {
- boardEl.append(squares[x][y].div)
- }
- boardEl.append.div("chessy-square chessy-square-out") {
- text(y + 1)
- }
- }
- for (l in arrayOf("", "a", "b", "c", "d", "e", "f", "g", "h", "")) {
- boardEl.append.div("chessy-square chessy-square-out") {
- text(l)
- }
- }
- return ChessyRootComponent(rootEl, squares)
- }
- }
- }
- class SquareComponent private constructor(
- val div: HTMLElement
- ) {
- fun update(square: Square) {
- div.removeClass("white-player")
- val piece = square.piece
- if (piece == null) {
- div.innerText = ""
- } else {
- div.innerText = charForPiece(piece.type).toString()
- if (piece.player == Player.WHITE) {
- div.addClass("white-player")
- }
- }
- }
- private fun charForPiece(type: PieceType): Char {
- return when (type) {
- PieceType.PAWN -> '♟'
- PieceType.KNIGHT -> '♞'
- PieceType.BISHOP -> '♝'
- PieceType.ROOK -> '♜'
- PieceType.QUEEN -> '♛'
- PieceType.KING -> '♚'
- }
- }
- companion object {
- fun create(isWhite: Boolean, onClick: () -> Unit): SquareComponent {
- val div = document.create.div("chessy-square") {
- if (isWhite) {
- classes += "white"
- }
- onClickFunction = { onClick() }
- }
- return SquareComponent(div)
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement