# GraNr1

his game of chance for two, played by the machine, after Winiarski's Gra nr 1 from Gry (1976).

Run it with `swift run --package-path Examples Example-Recreations-RyszardWiniarski-GraNr1`.

```swift
//  Recreation after Ryszard Winiarski - "Gra nr 1" (Game no. 1, a game of
//  chance for two), from "Gry" (Games, 1976). He made the set of seven game
//  boards in 1976 and showed it at Kunstcentrum Badhuis in Gorinchem. It is
//  now in the Anna and Jerzy Starak Collection. Game no. 1 is a board of 36
//  numbered fields, 24 red and 24 black counters, and two dice. A homage,
//  not a reproduction, and not affiliated with or endorsed by the artist or
//  his estate.
//  https://starakfoundation.org/en/spectra/news/ryszard_winiarski_games_spectra_art_space_masters
//  https://starakfoundation.org/files/21fb4cd3/winiarski_sasm_prev.pdf
//
//  An original Ollin interpretation written from the game's instruction and
//  from the photograph of the board. Both are in the Starak Family
//  Foundation's catalog, "Ryszard Winiarski. Gry / Games" (Spectra Art
//  Space, 2016). Nothing was ported: the work is a painted board with wooden
//  counters, and its players were the visitors.

import Ollin

/// "Gra nr 1" (Ryszard Winiarski, 1976), game number one of seven. In 1972
/// Winiarski turned a gallery room in Warsaw into a game parlor, and in 1976
/// he showed seven games of his own in Gorinchem. He said they came from a
/// struggle. People took his works in a way he had not intended, and he
/// wanted them to see the program behind the pictures. A game hands the
/// program to the visitors, and they fill the board.
///
/// The catalog of the set prints each game's instruction, and this sketch
/// plays the first to the letter. The board has 36 fields, numbered along
/// the rows. There are 24 red and 24 black counters and two dice. One die
/// has the digits 1 to 6, the other the numbers 0, 6, 12, 18, 24, and 30. A
/// coin decides who begins. A player casts both dice and adds them: the
/// instruction's example is 5 + 24 = 29. He puts a counter of his color on
/// that field. If the field is already taken, he loses his turn. The first
/// to fill a whole line, across, down, or corner to corner, wins. If nobody
/// does, the player with more fields on the board, more than 18, wins.
///
/// Three readings are this sketch's own. The instruction does not say when
/// a game without a line ends. Here it is played until the board is full,
/// which 24 counters a side allow. A full board with 18 fields each is
/// called a draw. And a player who has put down all 24 counters keeps
/// casting, and loses each turn.
///
/// One lap is one game. The dice under the board show each throw. Every
/// throw is also written under them in order, in its player's color. It is
/// the number of the field, struck through when the turn was lost. A lost
/// turn passes in half the time a counter takes to go down. The finished
/// board holds, with a line across the winning six if there is one. Then
/// the counters come off in the order they went on.
///
/// Try it: `gameSeed` is the game, and a click plays the next one. `seconds`
/// is the lap, however many throws the game takes.
///
/// `--export-svg` with a frame in the hold gives the board back as squares,
/// one for every counter. The file can then be checked against the throws.
@main
final class GraNr1: Sketch {
    /// Which game is played: the coin and every throw of the dice.
    @Param(1 ... 9999, icon: "dice") var gameSeed = 1
    /// Seconds for one lap: the game, a hold on the finished board, and the
    /// counters coming off.
    @Param(12 ... 30, icon: "clock") var seconds = 30.0

    override var loopDuration: Double? { seconds }

    private let wall = Color(hex: 0xE9E5DC)
    private let board = Color(hex: 0xF1EDDE)
    private let ruling = Color(hex: 0xCFC8B6)
    private let red = Color(hex: 0xC5222C)
    private let black = Color(hex: 0x131417)
    private let handwriting = Color(hex: 0x4A4640)

    // MARK: The game

    /// One throw: who cast, what the two dice showed, and whether a counter
    /// went down or the turn was lost.
    struct Cast {
        var red: Bool
        /// The die with the digits 1 to 6.
        var digit: Int
        /// The die with the numbers 0, 6, 12, 18, 24, and 30.
        var number: Int
        var placed: Bool
        /// True when the player had no counter left to put down.
        var spent = false

        /// The field the two dice name, 1 to 36.
        var field: Int { digit + number }
    }

    /// One game from the coin to its end.
    struct Game {
        var casts: [Cast] = []
        /// True when red won, false when black did, nil for a draw.
        var redWon: Bool?
        /// The six fields of the winning line, numbered from 0, or none.
        var line: [Int] = []

        /// When each throw is over, as a share of the whole game. A lost
        /// turn passes in half the time a counter takes to go down.
        var ends: [Double] {
            var total = 0.0
            let running = casts.map { cast -> Double in
                total += cast.placed ? 1 : 0.5
                return total
            }
            return running.map { $0 / total }
        }
    }

    /// Fields along one side of the board.
    static let across = 6
    /// Counters each player has.
    static let countersEach = 24

    /// Every full line a counter can complete: six rows, six columns, and
    /// the two diagonals, as fields numbered from 0.
    static let lines: [[Int]] = {
        var all: [[Int]] = []
        for k in 0 ..< across {
            all.append((0 ..< across).map { k * across + $0 })
            all.append((0 ..< across).map { $0 * across + k })
        }
        all.append((0 ..< across).map { $0 * (across + 1) })
        all.append((0 ..< across).map { ($0 + 1) * (across - 1) })
        return all
    }()

    /// Play one game. The coin comes first, then the two dice for every
    /// throw, the digit before the number.
    static func play(seed: UInt64) -> Game {
        var generator = SplitMix64(seed: seed)
        func roll() -> Double { Double(generator.next() >> 11) * 0x1p-53 }
        func face() -> Int { min(across - 1, Int(roll() * Double(across))) }

        var game = Game()
        var fields = [Bool?](repeating: nil, count: across * across)
        var down = (red: 0, black: 0)
        var redToCast = roll() < 0.5

        // The cap is far past any game: a board of 36 fields fills in about
        // 150 throws.
        while game.casts.count < 5000 {
            let digit = face() + 1
            let number = face() * across
            let field = digit + number - 1
            let left = countersEach - (redToCast ? down.red : down.black)
            let placed = fields[field] == nil && left > 0
            game.casts.append(Cast(red: redToCast, digit: digit, number: number, placed: placed,
                                   spent: left == 0))

            if placed {
                fields[field] = redToCast
                if redToCast { down.red += 1 } else { down.black += 1 }
                let made = lines.first { line in
                    line.contains(field) && line.allSatisfy { fields[$0] == redToCast }
                }
                if let line = made {
                    game.redWon = redToCast
                    game.line = line
                    return game
                }
                if down.red + down.black == fields.count { break }
            }
            redToCast.toggle()
        }
        // Nobody filled a line: more fields wins, and 18 each is a draw.
        if down.red != down.black { game.redWon = down.red > down.black }
        return game
    }

    // MARK: The lap

    /// The shares of the lap: the game ends at `played`, and the counters
    /// start coming off at `clearing`.
    static let played = 0.76, clearing = 0.93

    private var game = Game()
    private var ends: [Double] = []
    private var playedFor = -1
    /// Where in the lap the last click came, taken off the lap from then on
    /// so the next game starts with its first throw.
    private var restart = 0.0

    override func mousePressed() {
        gameSeed = gameSeed >= 9999 ? 1 : gameSeed + 1
        restart = -loopProgress(over: seconds)
    }

    override func draw() {
        background(wall)
        if playedFor != gameSeed {
            game = Self.play(seed: UInt64(gameSeed))
            ends = game.ends
            playedFor = gameSeed
        }
        let casts = game.casts
        let progress = loopProgress(over: seconds, phase: restart)

        // How far the game has got: the throw in hand, and how far through
        // it the lap is. Past the end every throw is made.
        let along = progress / Self.played
        let finished = along >= 1
        let current = finished ? casts.count - 1 : (ends.firstIndex { $0 > along } ?? casts.count - 1)
        let began = current == 0 ? 0 : ends[current - 1]
        let within = finished ? 1 : (along - began) / max(ends[current] - began, 1e-9)
        // The dice are read first, and the counter goes down a moment later.
        let counterDown = within >= 0.4

        // Counters on the board, in the order they went down.
        var placedOrder: [(field: Int, red: Bool)] = []
        for (index, cast) in casts.enumerated() where cast.placed {
            if index < current || (index == current && counterDown) {
                placedOrder.append((cast.field - 1, cast.red))
            }
        }
        // Clearing takes them off again, first on, first off.
        var removed = 0
        if progress >= Self.clearing {
            let t = (progress - Self.clearing) / (1 - Self.clearing)
            removed = min(placedOrder.count, Int(t * Double(placedOrder.count + 1)))
        }
        // Text and dice fade in as the lap opens and out as the board clears.
        let inked = progress >= Self.clearing
            ? 1 - (progress - Self.clearing) / (1 - Self.clearing)
            : min(1, progress / 0.015)

        let side = min(width, height)
        let boardSide = side * 0.6
        let field = boardSide / Double(Self.across)
        let origin = Vector2((width - boardSide) / 2, side * 0.055)

        // The board: 36 numbered fields.
        noStroke()
        fill(board)
        drawRect(origin.x, origin.y, boardSide, boardSide)
        noFill()
        stroke(ruling)
        strokeWeight(1)
        for k in 0 ... Self.across {
            let step = Double(k) * field
            drawLine(origin.x + step, origin.y, origin.x + step, origin.y + boardSide)
            drawLine(origin.x, origin.y + step, origin.x + boardSide, origin.y + step)
        }
        func center(of index: Int) -> Vector2 {
            origin + Vector2((Double(index % Self.across) + 0.5) * field,
                             (Double(index / Self.across) + 0.5) * field)
        }
        textFont(OutlineFont.systemBold)
        for index in 0 ..< Self.across * Self.across {
            drawText("\(index + 1)", at: center(of: index), size: field * 0.16, color: black,
                     align: .center, .middle)
        }

        // The counters. Each sits a little off square, the way a hand puts
        // it down, by an amount that depends only on its field.
        noStroke()
        for item in placedOrder.dropFirst(removed) {
            let lot = Self.lot(item.field)
            let half = field * 0.478
            let middle = center(of: item.field) + Vector2(lot.x, lot.y) * (field * 0.008)
            let turn = lot.turn * 0.014
            let corners = [Vector2(-half, -half), Vector2(half, -half),
                           Vector2(half, half), Vector2(-half, half)]
            fill(item.red ? red : black)
            drawPolygon(corners.map { middle + $0.rotated(by: turn) })
        }

        // The winning line, once the game is over and until it is cleared.
        if finished, removed == 0, let first = game.line.first, let last = game.line.last {
            stroke(board)
            strokeWeight(field * 0.035)
            strokeCap(.round)
            drawLine(center(of: first), center(of: last))
            noStroke()
        }

        // The throw in hand: the two dice, their sum, and what came of it.
        let cast = casts[current]
        let diceY = origin.y + boardSide + side * 0.058
        let die = side * 0.056
        let ink = (cast.red ? red : black).withAlpha(inked)
        let quiet = handwriting.withAlpha(inked)
        drawDie("\(cast.digit)", center: Vector2(origin.x + die * 0.5, diceY), size: die, alpha: inked)
        drawDie("\(cast.number)", center: Vector2(origin.x + die * 2.1, diceY), size: die, alpha: inked)
        textFont(OutlineFont.system)
        drawText("+", at: Vector2(origin.x + die * 1.3, diceY), size: die * 0.42, color: quiet,
                 align: .center, .middle)
        drawText("=", at: Vector2(origin.x + die * 2.95, diceY), size: die * 0.42, color: quiet,
                 align: .center, .middle)
        textFont(OutlineFont.systemBold)
        let sumAt = Vector2(origin.x + die * 3.75, diceY)
        drawText("\(cast.field)", at: sumAt, size: die * 0.62, color: ink, align: .center, .middle)
        if !cast.placed {
            stroke(ink)
            strokeWeight(die * 0.05)
            strokeCap(.butt)
            drawLine(sumAt.x - die * 0.42, sumAt.y, sumAt.x + die * 0.42, sumAt.y)
            noStroke()
        }

        var reds = 0, blacks = 0
        for item in placedOrder { if item.red { reds += 1 } else { blacks += 1 } }
        let who = cast.red ? "Red" : "Black"
        let first: String
        if finished {
            switch game.redWon {
            case .some(let redWon):
                let winner = redWon ? "Red" : "Black"
                first = game.line.isEmpty
                    ? "\(winner) wins with more fields."
                    : "\(winner) wins with a full line."
            case .none:
                first = "A draw: 18 fields each."
            }
        } else if cast.placed {
            first = "Throw \(current + 1). \(who) takes field \(cast.field)."
        } else if cast.spent {
            first = "Throw \(current + 1). \(who) has no counters left."
        } else {
            first = "Throw \(current + 1). \(cast.field) is taken, so \(who.lowercased()) loses the turn."
        }
        let second = finished
            ? "Red \(reds) fields, black \(blacks), in \(casts.count) throws."
            : "Red \(reds) fields, black \(blacks)."
        let right = origin.x + boardSide
        textFont(OutlineFont.system)
        drawText(first, right, diceY - side * 0.014, size: side * 0.0155, color: quiet,
                 align: .right, .middle)
        drawText(second, right, diceY + side * 0.014, size: side * 0.0155, color: quiet,
                 align: .right, .middle)

        // The record: every throw so far, in order, as the field it named.
        let shown = current + 1
        let rows = 7
        let columns = max(24, (casts.count + rows - 1) / rows)
        let pitch = boardSide / Double(columns)
        let size = side * 0.0165 * 24 / Double(columns)
        let top = diceY + side * 0.062
        textFont(OutlineFont.systemMono)
        for index in 0 ..< shown {
            let entry = casts[index]
            let at = Vector2(origin.x + (Double(index % columns) + 0.5) * pitch,
                             top + Double(index / columns) * size * 1.62)
            let color = (entry.red ? red : black).withAlpha(inked)
            drawText("\(entry.field)", at: at, size: size, color: color, align: .center, .middle)
            if !entry.placed {
                stroke(color)
                strokeWeight(max(1, size * 0.07))
                strokeCap(.butt)
                drawLine(at.x - pitch * 0.36, at.y, at.x + pitch * 0.36, at.y)
                noStroke()
            }
        }
    }

    /// One die: a rounded square with its numeral.
    private func drawDie(_ numeral: String, center: Vector2, size: Double, alpha: Double) {
        fill(Color(hex: 0xFBF8F0).withAlpha(alpha))
        stroke(ruling.withAlpha(alpha))
        strokeWeight(1)
        drawRect(center: center, width: size, height: size, cornerRadius: size * 0.16)
        noStroke()
        textFont(OutlineFont.systemBold)
        drawText(numeral, at: center, size: size * 0.44, color: black.withAlpha(alpha),
                 align: .center, .middle)
    }

    /// Three steady numbers between -1 and 1 for a field. They say how far
    /// off its middle a counter sits, across and down, and how far it is
    /// turned.
    private static func lot(_ field: Int) -> (x: Double, y: Double, turn: Double) {
        var generator = SplitMix64(seed: UInt64(field) &* 0x9E37_79B9 &+ 77)
        func roll() -> Double { Double(generator.next() >> 11) * 0x1p-53 * 2 - 1 }
        return (roll(), roll(), roll())
    }
}
```
