# Backgammon, a conformance game (issue #32): dice from the match's random source, a turn of several moves, the rules
# that a player must use as many dice as possible (and the larger die when only one can be used), entering from the bar,
# hitting and bearing off. Legal plays are checked against GNU Backgammon. Not modelled: the doubling cube, gammons and
# backgammons, and the opening roll-off (X simply rolls first).
#
# The board is state values, not components: points[i] holds point i + 1 as numbered from X's side, positive for X's
# checkers and negative for O's. X moves from 24 down to 1 and bears off below 1; O moves the other way. The functions
# work in each seat's own numbering ("relative" points), where 1 to 6 is home and 25 stands for the bar.
dsl: "0.4"

game:
  id: backgammon
  name: Backgammon
  players: { min: 2, max: 2 }
  seats:
    topology: ring
    names: [x, o]

state:
  global:
    points: "list<int> = [-2, 0, 0, 0, 0, 5, 0, 3, 0, 0, 0, -5, 5, 0, 0, 0, -3, 0, -5, 0, 0, 0, 0, 2]"
    bar: "list<int> = [0, 0]"
    borneOff: "list<int> = [0, 0]"
    dice: "list<int> = []"
  seat: {}

functions:
  # The board as one value, so plays can be worked out without changing the state.
  board:
    params: {}
    returns: "(points: list<int>, bar: list<int>, borneOff: list<int>)"
    expr: "(points: global.points, bar: global.bar, borneOff: global.borneOff)"
  # A seat's position in the bar and borneOff lists: 0 for X, 1 for O.
  slot:
    params: { s: seat }
    returns: int
    expr: "s == seat(x) ? 0 : 1"
  side:
    params: { s: seat }
    returns: int
    expr: "s == seat(x) ? 1 : -1"
  # The absolute point for a seat's relative point: X's numbering is the board's; O's runs the other way.
  point:
    params: { s: seat, r: int }
    returns: int
    expr: "s == seat(x) ? r : 25 - r"
  mine:
    params: { b: "(points: list<int>, bar: list<int>, borneOff: list<int>)", s: seat, r: int }
    returns: int
    expr: "max(0, side(s) * b.points[point(s, r) - 1])"
  theirs:
    params: { b: "(points: list<int>, bar: list<int>, borneOff: list<int>)", s: seat, r: int }
    returns: int
    expr: "max(0, -side(s) * b.points[point(s, r) - 1])"
  replaced:
    params: { l: "list<int>", k: int, v: int }
    returns: "list<int>"
    expr: "range(0, l.count()).select(i => i == k ? v : l[i])"
  allHome:
    params: { b: "(points: list<int>, bar: list<int>, borneOff: list<int>)", s: seat }
    returns: bool
    expr: "b.bar[slot(s)] == 0 && range(7, 25).all(r => mine(b, s, r) == 0)"
  # Whether a checker on relative point r (25 for the bar) may move d pips: onto a point not held by two or more of the
  # opponent's checkers, or off the board once every checker is home, exactly or from the highest occupied point.
  canMove:
    params: { b: "(points: list<int>, bar: list<int>, borneOff: list<int>)", s: seat, r: int, d: int }
    returns: bool
    expr: >
      r - d >= 1 ? theirs(b, s, r - d) < 2
        : allHome(b, s) && (r - d == 0 || range(r + 1, 7).all(q => mine(b, s, q) == 0))
  # The points a seat may move from: only the bar while it has checkers there.
  sources:
    params: { b: "(points: list<int>, bar: list<int>, borneOff: list<int>)", s: seat }
    returns: "list<int>"
    expr: "b.bar[slot(s)] > 0 ? [25] : range(1, 25).where(r => mine(b, s, r) > 0)"
  # The board after moving one checker d pips from relative point r, hitting a lone opposing checker.
  moved:
    params: { b: "(points: list<int>, bar: list<int>, borneOff: list<int>)", s: seat, r: int, d: int }
    returns: "(points: list<int>, bar: list<int>, borneOff: list<int>)"
    expr: >
      let lifted = r == 25 ? (points: b.points, bar: replaced(b.bar, slot(s), b.bar[slot(s)] - 1), borneOff: b.borneOff)
        : (points: replaced(b.points, point(s, r) - 1, b.points[point(s, r) - 1] - side(s)), bar: b.bar, borneOff: b.borneOff);
      let t = r - d;
      t < 1 ? (points: lifted.points, bar: lifted.bar, borneOff: replaced(lifted.borneOff, slot(s), lifted.borneOff[slot(s)] + 1))
        : theirs(lifted, s, t) == 1
          ? (points: replaced(lifted.points, point(s, t) - 1, side(s)), bar: replaced(lifted.bar, 1 - slot(s), lifted.bar[1 - slot(s)] + 1), borneOff: lifted.borneOff)
          : (points: replaced(lifted.points, point(s, t) - 1, lifted.points[point(s, t) - 1] + side(s)), bar: lifted.bar, borneOff: lifted.borneOff)
  # Every way to play the dice in the order given, as far as they can be played: each a list of steps and the board after.
  sequences:
    params: { b: "(points: list<int>, bar: list<int>, borneOff: list<int>)", s: seat, ds: "list<int>" }
    returns: "list<(steps: list<(from: int, die: int)>, board: (points: list<int>, bar: list<int>, borneOff: list<int>))>"
    expr: >
      let starts = ds.isEmpty() ? [] : sources(b, s).where(r => canMove(b, s, r, ds[0]));
      starts.isEmpty() ? [(steps: [], board: b)]
        : starts.selectMany(r => sequences(moved(b, s, r, ds[0]), s, range(1, ds.count()).select(i => ds[i]))
            .select(rest => (steps: [(from: r, die: ds[0])].concat(rest.steps), board: rest.board)))
  # The legal plays: as many dice as possible, the larger die when only one of two can be played, one play per
  # resulting position. With nothing playable, the only play is the empty one, a pass.
  legalPlays:
    params: { s: seat }
    returns: "list<list<(from: int, die: int)>>"
    expr: >
      let ds = global.dice;
      let all = ds.count() == 2 ? sequences(board(), s, ds).concat(sequences(board(), s, [ds[1], ds[0]])) : sequences(board(), s, ds);
      let most = all.max(p => p.steps.count());
      let used = all.where(p => p.steps.count() == most);
      let larger = most == 1 && ds.count() == 2 && used.any(p => p.steps[0].die == max(ds[0], ds[1])) ? used.where(p => p.steps[0].die == max(ds[0], ds[1])) : used;
      larger.distinctBy(p => p.board).select(p => p.steps)
  # The board after a whole play.
  played:
    params: { s: seat, steps: "list<(from: int, die: int)>" }
    returns: "(points: list<int>, bar: list<int>, borneOff: list<int>)"
    expr: "playedFrom(board(), s, steps, 0)"
  playedFrom:
    params: { b: "(points: list<int>, bar: list<int>, borneOff: list<int>)", s: seat, steps: "list<(from: int, die: int)>", i: int }
    returns: "(points: list<int>, bar: list<int>, borneOff: list<int>)"
    expr: "i == steps.count() ? b : playedFrom(moved(b, s, steps[i].from, steps[i].die), s, steps, i + 1)"

setup:
  - set: { target: global.dice, value: "[die(6), die(6)]" }
  - set: { target: global.dice, value: "global.dice[0] == global.dice[1] ? [global.dice[0], global.dice[0], global.dice[0], global.dice[0]] : global.dice" }

flow:
  - phase: play
    turns:
      order: { from: "seat(x)", direction: clockwise }
      budget: 1
      actions: [play]
      afterTurn:
        - set: { target: global.dice, value: "[die(6), die(6)]" }
        - set: { target: global.dice, value: "global.dice[0] == global.dice[1] ? [global.dice[0], global.dice[0], global.dice[0], global.dice[0]] : global.dice" }

actions:
  play:
    choose:
      - steps: { from: "legalPlays(self)" }
    effect:
      - let: { name: after, value: "played(self, steps)" }
      - set: { target: global.points, value: "after.points" }
      - set: { target: global.bar, value: "after.bar" }
      - set: { target: global.borneOff, value: "after.borneOff" }
      - if:
          cond: "global.borneOff[slot(self)] == 15"
          then: [ { endGame: { winner: self, reason: bore off } } ]

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