# Chess, following the US Chess Federation rules as applied to online play
# (Chapter 1 game rules, Chapter 10 online rules). DSL v0 proof file.
dsl: "1.0"

game:
  id: chess
  name: Chess
  players: { min: 2, max: 2 }
  seats:
    topology: ring
    names: [white, black]          # seat 0 = white, seat 1 = black

enums:
  kind: [pawn, knight, bishop, rook, queen, king]
  promo: [knight, bishop, rook, queen]

consts:
  orthogonal: "[(x: 1, y: 0), (x: -1, y: 0), (x: 0, y: 1), (x: 0, y: -1)]"
  diagonal:   "[(x: 1, y: 1), (x: 1, y: -1), (x: -1, y: 1), (x: -1, y: -1)]"
  royal:      "orthogonal.concat(diagonal)"
  knightJumps: "[(x: 1, y: 2), (x: 2, y: 1), (x: 2, y: -1), (x: 1, y: -2), (x: -1, y: -2), (x: -2, y: -1), (x: -2, y: 1), (x: -1, y: 2)]"

boards:
  board:
    kind: grid
    size: [8, 8]
    labels: { x: "abcdefgh", y: "12345678" }

components:
  piece:
    props:
      kind: kind
      owner: seat
      hasMoved: "bool = false"

data:
  startPosition:
    of: piece
    rows:
      - { kind: rook,   owner: white, at: a1 }
      - { kind: knight, owner: white, at: b1 }
      - { kind: bishop, owner: white, at: c1 }
      - { kind: queen,  owner: white, at: d1 }
      - { kind: king,   owner: white, at: e1 }
      - { kind: bishop, owner: white, at: f1 }
      - { kind: knight, owner: white, at: g1 }
      - { kind: rook,   owner: white, at: h1 }
      - { kind: pawn,   owner: white, at: [a2, b2, c2, d2, e2, f2, g2, h2] }
      - { kind: rook,   owner: black, at: a8 }
      - { kind: knight, owner: black, at: b8 }
      - { kind: bishop, owner: black, at: c8 }
      - { kind: queen,  owner: black, at: d8 }
      - { kind: king,   owner: black, at: e8 }
      - { kind: bishop, owner: black, at: f8 }
      - { kind: knight, owner: black, at: g8 }
      - { kind: rook,   owner: black, at: h8 }
      - { kind: pawn,   owner: black, at: [a7, b7, c7, d7, e7, f7, g7, h7] }

zones:
  square:   { kind: cell, board: board, of: piece, capacity: 1, visibility: public }
  captured: { kind: set, of: piece, perSeat: true, visibility: public }

state:
  global:
    enPassant: "square? = null"      # square a pawn may capture onto, this move only
    halfmoveClock: "int = 0"         # moves since the last pawn move or capture
  seat: {}

functions:
  forward:
    params: { s: seat }
    returns: int
    expr: "s == seat(white) ? 1 : -1"
  homeRank:
    params: { s: seat }
    returns: int
    expr: "s == seat(white) ? 1 : 8"
  pawnStartRank:
    params: { s: seat }
    returns: int
    expr: "homeRank(s) + forward(s)"
  lastRank:
    params: { s: seat }
    returns: int
    expr: "s == seat(white) ? 8 : 1"
  king:
    params: { s: seat }
    returns: piece
    expr: "pieces(s).first(p => p.kind == kind.king)"
  # Squares a piece attacks (ignores whose turn it is and pins).
  attacks:
    params: { p: piece }
    returns: "list<square>"
    expr: >
      p.kind switch {
        kind.pawn   => [offset(p.at, -1, forward(p.owner)), offset(p.at, 1, forward(p.owner))].whereNotNull(),
        kind.knight => knightJumps.select(d => offset(p.at, d.x, d.y)).whereNotNull(),
        kind.bishop => diagonal.selectMany(d => ray(p.at, d.x, d.y, stopAtOccupied: true)),
        kind.rook   => orthogonal.selectMany(d => ray(p.at, d.x, d.y, stopAtOccupied: true)),
        kind.queen  => royal.selectMany(d => ray(p.at, d.x, d.y, stopAtOccupied: true)),
        kind.king   => royal.select(d => offset(p.at, d.x, d.y)).whereNotNull()
      }
  attacked:
    params: { sq: square, by: seat }
    returns: bool
    expr: "pieces(by).any(p => attacks(p).contains(sq))"
  inCheck:
    params: { s: seat }
    returns: bool
    expr: "attacked(king(s).at, opponent(s))"
  # Destination squares before the "don't leave your king in check" test.
  targets:
    params: { p: piece }
    returns: "list<square>"
    expr: >
      p.kind == kind.pawn
        ? pawnTargets(p)
        : attacks(p).where(sq => pieceAt(sq) == null || pieceAt(sq).owner != p.owner)
          .concat(p.kind == kind.king ? castleTargets(p) : [])
  pawnTargets:
    params: { p: piece }
    returns: "list<square>"
    expr: >
      [ offset(p.at, 0, forward(p.owner)) ].whereNotNull().where(sq => pieceAt(sq) == null)
      .concat(
        p.at.rank == pawnStartRank(p.owner)
          && pieceAt(offset(p.at, 0, forward(p.owner))) == null
          && pieceAt(offset(p.at, 0, 2 * forward(p.owner))) == null
        ? [offset(p.at, 0, 2 * forward(p.owner))] : [])
      .concat(attacks(p).where(sq =>
        (pieceAt(sq) != null && pieceAt(sq).owner != p.owner) || sq == global.enPassant))
  castleTargets:
    params: { k: piece }
    returns: "list<square>"
    expr: >
      k.hasMoved || inCheck(k.owner) ? [] :
      [ (rookFile: 'h', path: ['f','g'], empty: ['f','g'], dest: 'g'),
        (rookFile: 'a', path: ['d','c'], empty: ['d','c','b'], dest: 'c') ]
      .where(c =>
        pieceAt(square(c.rookFile, homeRank(k.owner)))?.kind == kind.rook
        && !pieceAt(square(c.rookFile, homeRank(k.owner))).hasMoved
        && c.empty.all(f => pieceAt(square(f, homeRank(k.owner))) == null)
        && c.path.all(f => !attacked(square(f, homeRank(k.owner)), opponent(k.owner))))
      .select(c => square(c.dest, homeRank(k.owner)))
  insufficientMaterial:
    params: {}
    returns: bool
    # K v K, K+minor v K, K+B v K+B with bishops on the same colour.
    expr: >
      let rest = allPieces().where(p => p.kind != kind.king);
      rest.count() == 0
      || (rest.count() == 1 && (rest[0].kind == kind.bishop || rest[0].kind == kind.knight))
      || (rest.all(p => p.kind == kind.bishop) && rest.select(p => p.at.color).distinct().count() == 1)
  canStillMate:
    params: { s: seat }
    returns: bool
    # US Chess 14E: a lone king, or king plus one minor piece, cannot win on time.
    expr: >
      let mine = pieces(s).where(p => p.kind != kind.king);
      !(mine.count() == 0 || (mine.count() == 1 && (mine[0].kind == kind.bishop || mine[0].kind == kind.knight)))

setup:
  - createFrom: { table: startPosition, into: square, positionColumn: at }

history:
  # What counts as "the same position" for repetition (US Chess 14C).
  # Which piece is on which square, not hasMoved: castlingRights carries the part of hasMoved that matters.
  positionKey: [board, activeSeat, castlingRights, enPassantKey]
  derived:
    board: "allPieces().select(p => (p.at, p.kind, p.owner))"
    # The en passant square counts only when a pawn of the side to move attacks it (US Chess 14C).
    enPassantKey: "global.enPassant != null && pieces(activeSeat).any(p => p.kind == kind.pawn && attacks(p).contains(global.enPassant)) ? global.enPassant : null"
    castlingRights: "allPieces().where(p => (p.kind == kind.king || p.kind == kind.rook) && !p.hasMoved).select(p => p.at)"

flow:
  - phase: play
    turns:
      order: { from: "seat(white)", direction: clockwise }
      budget: 1
      actions: [move]
      onNoLegalAction:
        - if:
            cond: "inCheck(activeSeat)"
            then: [ { endGame: { winner: "opponent(activeSeat)", reason: checkmate } } ]
            else: [ { endGame: { draw: true, reason: stalemate } } ]

actions:
  move:
    choose:
      - piece: { from: "pieces(self)", where: "targets(piece).any()" }
      - to: { from: "targets(piece)" }
      - promoteTo:
          options: promo
          when: "piece.kind == kind.pawn && to.rank == lastRank(self)"
          default: queen               # platforms may auto-promote (US Chess 10/12E)
    postcondition: "!inCheck(self)"   # a move may not leave your own king in check
    effect:
      - let: { name: wasCapture, value: "pieceAt(to) != null || (piece.kind == kind.pawn && to == global.enPassant)" }
      - if:
          cond: "piece.kind == kind.pawn && to == global.enPassant"
          then: [ { move: { what: "pieceAt(offset(to, 0, -forward(self)))", to: "captured[self]" } } ]
      - if:
          cond: "pieceAt(to) != null"
          then: [ { move: { what: "pieceAt(to)", to: "captured[self]" } } ]
      - if:
          cond: "piece.kind == kind.king && abs(to.file - piece.at.file) == 2"
          then:
            - move:
                what: "pieceAt(square(to.file > piece.at.file ? 'h' : 'a', homeRank(self)))"
                to: "square(to.file > piece.at.file ? 'f' : 'd', homeRank(self))"
      - set: { target: global.enPassant, value: "piece.kind == kind.pawn && abs(to.rank - piece.at.rank) == 2 ? offset(piece.at, 0, forward(self)) : null" }
      - move: { what: piece, to: to }
      - set: { target: piece.hasMoved, value: true }
      - if:
          cond: "promoteTo != null"
          then: [ { set: { target: piece.kind, value: promoteTo } } ]
      - set: { target: global.halfmoveClock, value: "piece.kind == kind.pawn || wasCapture ? 0 : global.halfmoveClock + 1" }

  resign:
    anytime: true
    effect:
      - endGame: { winner: "opponent(self)", reason: resignation }

  offerDraw:
    anytime: true
    require: "!pendingOffer('drawOffer')"
    effect:
      - offer: { id: drawOffer, to: "opponent(self)", accept: [ { endGame: { draw: true, reason: agreement } } ] }

  claimDraw:
    anytime: true
    require: "history.count(position) >= 3 || global.halfmoveClock >= 100"
    effect:
      - endGame: { draw: true, reason: "history.count(position) >= 3 ? 'threefold repetition' : '50-move rule'" }

triggers:
  # Automatic draws the online rules allow a platform to apply (Chapter 10, 10A1 and 10C).
  - event: afterAction
    when: "history.count(position) >= 5"
    do: [ { endGame: { draw: true, reason: fivefold repetition } } ]
  - event: afterAction
    when: "global.halfmoveClock >= 150"
    do: [ { endGame: { draw: true, reason: 75-move rule } } ]
  - event: afterAction
    when: "insufficientMaterial()"
    do: [ { endGame: { draw: true, reason: insufficient material } } ]

clock:
  supported: [suddenDeath, increment, delay, bronsteinDelay]
  onTimeExpired:
    # US Chess 14E: no win on time for a side that cannot mate.
    - if:
        cond: "canStillMate(opponent(expiredSeat))"
        then: [ { endGame: { winner: "opponent(expiredSeat)", reason: time forfeit } } ]
        else: [ { endGame: { draw: true, reason: insufficient material to win on time } } ]

end:
  scoring: { win: 1, draw: 0.5, loss: 0 }
  rating: elo

hooks:
  pgnExport:
    kind: notation
    signature: "(log: MatchLog) -> string"
