simplification
Download
336 lines 13.4 KiBLuaModified 2026-11-09 raw
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
-- A very short game of Nomic, played with Nomsu (run with: lua examples/nomic.lua)
--
-- Almost everything about the game is defined by its rules, which are Nomsu code that
-- players can change: what players can do, whose turn it is, how proposals and votes
-- work, what passing a proposal does, scoring, winning, and the announcements. This Lua
-- file is only a small kernel. Any player can submit code at any time, and the kernel
-- runs it and gives the rules a few things that can't be done in a sandbox:
--   (send $request)        Send a request (plain data) to the game. After the player's
--                          code finishes, the game handles it with (handle $event).
--   (enact $code)          Run some code (as text) in this sandbox.
--   (try enacting $code)   Try running some code in a copy of the game, and return the
--                          problem with it (or nil if there isn't one).
--   propose: ...           Turn the code in the block into text, and pass it to
--                          (submit proposal $code). (This needs a compile rule, which
--                          sandboxed code can't define.)
--
-- The game has a persistent sandbox, which runs everything that happens in the game,
-- once. Code that a player submits runs in a sandbox of their own: a copy of the game,
-- made by running the game's history again in a new sandbox (since Lua functions can't be
-- copied). Players can do anything in their sandbox without changing anything for anyone
-- else (what they say there is only shown to them). The only way to affect the game is
-- to send requests.
local root_dir = (arg and arg[0] or ""):match("^(.*)/examples/[^/]*$") or "."
package.path = root_dir.."/?.lua;"..package.path
local nomsu = require "nomsu"
local Limits = require "nomsu_limits"
local unpack = unpack or table.unpack

-- Terminal colors (unless NO_COLOR is set)
local use_color = not os.getenv("NO_COLOR")
local function color(codes, text)
    if not use_color then return text end
    return "\027["..codes.."m"..text.."\027[0m"
end
local player_colors = {alice = "1;35", bob = "1;36", carol = "1;33"}
local function name(player) return color(player_colors[player] or "1", player) end
-- Color some text, with players' names in their colors
local function with_names(codes, text)
    if not use_color then return text end
    for player, player_color in pairs(player_colors) do
        text = text:gsub("%f[%w]"..player.."%f[%W]",
            "\027["..player_color.."m"..player.."\027[0;"..codes.."m")
    end
    return color(codes, text)
end

-- The kernel's one compile rule
local kernel = [[
#!/usr/bin/env nomsu -V8.0.0
public:
    (propose $code) compiles to:
        $statements = ($code if ($code.type == "Block") else {$code})
        $text = (("\($ as nomsu)" for $ in $statements) joined with "\n")
        return (Lua "submit_proposal(\($text, as lua))")
]]

-- The rules the game starts with. Rules run in order, so later rules (like ones that
-- proposals add) can redefine anything that earlier rules defined.
local initial_rules = {
    [[
### Rule 1: the players and the game's state
public $game = {
    .players = {"alice", "bob", "carol"}, .scores = {.alice = 0, .bob = 0, .carol = 0}
    .proposals = {}, ."next proposal" = 1, .turn = 1, ."proposed this turn" = (no)
}]],
    [[
### Rule 2: what players can do
public:
    (submit proposal $code) means (send {.type = "proposal", .code = $code})
    (vote yes on proposal $n) means (send {.type = "vote", .proposal = $n, .vote = "yes"})
    (vote no on proposal $n) means (send {.type = "vote", .proposal = $n, .vote = "no"})
    (tell everyone $message) means (send {.type = "message", .message = $message})
    (handle $event) means:
        $request = $event.request
        when:
            ($request.type == "proposal"):
                handle proposal $request.code from $event.player
            ($request.type == "vote"):
                handle vote $request.vote on proposal $request.proposal from $event.player
            ($request.type == "message"):
                say "\($event.player) says: \($request.message)"]],
    [[
### Rule 3: players take turns making proposals, in order. A turn ends when its proposal
### is decided.
public:
    (whose turn is it) means $game.players.($game.turn)
    (next turn) means:
        ### The game is over when someone has won
        if (winner): return
        $game.turn = (($game.turn mod #$game.players) + 1)
        $game."proposed this turn" = (no)
        say "It's \(whose turn is it)'s turn to propose."]],
    [[
### Rule 4: a proposal must be made on its author's turn. Proposals that would break the
### game are rejected, and the rest are announced.
public:
    (check the game) means:
        winner
        reward for passing a proposal
        proposal {.votes = {.alice = "yes"}} passes
    (handle proposal $code from $player) means:
        unless ($player == (whose turn is it)):
            say "\$player can't propose now, since it's \(whose turn is it)'s turn."
            return
        if $game."proposed this turn":
            say "\$player already made a proposal this turn."
            return
        $problem = (try enacting "\$code\ncheck the game")
        if $problem:
            say "\$player's proposal was rejected, since it would break the game: \$problem"
            return
        $n = $game."next proposal"
        $game."next proposal" += 1
        $game.proposals.$n = {.author = $player, .code = $code, .votes = {}}
        $game."proposed this turn" = (yes)
        say "Proposal \$n, by \$player:\n    \($code, with "\n" -> "\n    ")"]],
    [[
### Rule 5: when everyone has voted, the proposal is decided, and the turn ends
public:
    (handle vote $vote on proposal $n from $player) means:
        $proposal = $game.proposals.$n
        unless $proposal: return
        $proposal.votes.$player = $vote
        for $other in $game.players:
            unless $proposal.votes.$other: return
        $game.proposals.$n = (nil)
        if (proposal $proposal passes):
            say "Proposal \$n passes."
            enact $proposal.code
            proposal $proposal passed
        ..else:
            say "Proposal \$n fails."
        next turn]],
    [[
### Rule 6: proposals pass with a majority of votes
public:
    (proposal $p passes) means:
        $yes = 0
        $no = 0
        for ($player = $vote) in $p.votes:
            if ($vote == "yes"):
                $yes += 1
            ..else:
                $no += 1
        return ($yes > $no)]],
    [[
### Rule 7: passing a proposal earns points, and the first player with 10 points wins
public:
    (reward for passing a proposal) means 3
    (proposal $p passed) means:
        $reward = (reward for passing a proposal)
        $game.scores.($p.author) += $reward
        say "\($p.author) gets \$reward points."
        announce the scores
    (announce the scores) means:
        say "Scores: \(("\$player \($game.scores.$player)" for $player in $game.players) joined with ", ")"
        if (winner):
            say "\(winner) wins!"
    (winner) means:
        for ($player = $points) in $game.scores:
            if ($points >= 10):
                return $player]],
}

-- Everything that has happened in the game, in order: rules (code), and requests from
-- players. Running it all in a new sandbox gives a copy of the game.
local history = {}
for _, rule in ipairs(initial_rules) do table.insert(history, {code = rule}) end

-- Requests are plain data, so the game can't get anything else from a player's sandbox
local plain_copy = nomsu.plain_copy

-- Nomsu's error messages show the code where the error happened. Just keep the message.
local function short(err)
    err = tostring(err)
    return err:match("%^+%s*\n%s*([^\n]-)%s*\n") or err:match("[^\n]*")
end

local build_sandbox

-- Make a sandbox with the kernel's functions. While it's replaying history, its output is
-- hidden, and (try enacting) gives the same results it gave the first time.
local function new_sandbox(output, send)
    local sandbox = {replaying = false}
    sandbox.runtime = nomsu.Runtime{
        print = function(text) if not sandbox.replaying then output(text) end end,
        environment = {
            send = function(request) if send then send(plain_copy(request)) end end,
            enact = function(code)
                local ok, err = sandbox.runtime:run(code)
                if not ok then error(err, 0) end
            end,
            try_enacting = function(code)
                if sandbox.replaying then return table.remove(sandbox.recorded, 1) or nil end
                -- Building a copy of the game is the kernel's work, so it doesn't count
                -- against the instruction limit (but the time limit still applies)
                local problem = Limits.run_unlimited(function()
                    local copy = build_sandbox(function() end)
                    local ok, err = copy.runtime:run(code)
                    if not ok then return short(err) end
                end)
                if sandbox.recorded then table.insert(sandbox.recorded, problem or false) end
                return problem
            end,
        },
        modules = {kernel = kernel},
        limits = {instructions = 1e6, seconds = 5},
    }
    assert(sandbox.runtime:run("use \"kernel\""))
    sandbox.runtime:seal()
    return sandbox
end

-- Run something from the game's history in a sandbox
local function run_entry(sandbox, entry)
    sandbox.recorded = entry.recorded
    if sandbox.replaying and entry.recorded then sandbox.recorded = {unpack(entry.recorded)} end
    local ok, err
    if entry.code then
        ok, err = sandbox.runtime:run(entry.code)
    else
        local env = sandbox.runtime.environment.RUNTIME_ENV
        env.event = {player = entry.player, request = plain_copy(entry.request)}
        ok, err = sandbox.runtime:run("handle $event")
        env.event = nil
    end
    sandbox.recorded = nil
    return ok, err
end

-- A copy of the game, made by running its history again
function build_sandbox(output, send)
    local sandbox = new_sandbox(output, send)
    sandbox.replaying = true
    for _, entry in ipairs(history) do run_entry(sandbox, entry) end
    sandbox.replaying = false
    return sandbox
end

-- The game's persistent sandbox. What it says is announced to everyone.
local game = build_sandbox(function(text)
    local lines, newline = text:match("^(.-)(\n?)$")
    io.write(with_names("34", "  "..lines:gsub("\n", "\n  ")), newline)
end)

-- A player submits some code, which runs in their own sandbox. Then the game handles the
-- requests they sent. Players can submit code whenever they like; the rules decide what
-- they're allowed to do.
local function submit(player, code)
    print("\n"..name(player)..color("1", ":"))
    print(color("2", "    "..code:gsub("\n", "\n    ")))
    local requests = {}
    local sandbox = build_sandbox(function(text)
        local line, newline = text:match("^(.-)(\n?)$")
        io.write("    ", color("2", "["..player.."'s sandbox]"), " ", color("32", line), newline)
    end, function(request) table.insert(requests, request) end)
    local ok, err = sandbox.runtime:run(code)
    if not ok then print(color("31", "    Error: "..short(err))) end
    for _, request in ipairs(requests) do
        local entry = {player = player, request = request, recorded = {}}
        local ok, err = run_entry(game, entry)
        if not ok then print(color("31", "  The game had an error: "..short(err))) end
        table.insert(history, entry)
    end
end

print(color("1", "A game of Nomic between ")..name("alice")..", "..name("bob")..", and "..name("carol"))

submit("carol", [[tell everyone "Good luck, everyone!"]])

submit("bob", [[
### Looking things up only shows the results to bob
say "It's \(whose turn is it)'s turn, and the reward is \(reward for passing a proposal) points."]])

submit("bob", [[
propose:
    public:
        (reward for passing a proposal) means 5]])

submit("alice", [[
tell everyone "I'll propose what bob wanted."
propose:
    public:
        (reward for passing a proposal) means 5
vote yes on proposal 1]])

submit("bob", [[
vote yes on proposal 1
tell everyone "Thanks!"]])

submit("alice", [[
### Anything alice does in her sandbox only changes her copy of the game
$game.scores.alice = 100
say "In my sandbox, my score is \($game.scores.alice), and the winner is \(winner)"]])

submit("carol", "vote no on proposal 1")

submit("bob", [[
### This changes the game's state once, when it passes
propose:
    for ($player = $points) in $game.scores:
        $game.scores.$player = ($points + 2)
vote yes on proposal 2]])
submit("carol", "vote yes on proposal 2")
submit("alice", "vote yes on proposal 2")

submit("carol", [[
### Nobody can win if (winner) never finishes
propose:
    public:
        (winner) means:
            repeat:
                do nothing]])

submit("carol", [[
### Everyone who votes for a proposal that passes gets a point too
propose:
    public:
        (proposal $p passed) means:
            $game.scores.($p.author) += (reward for passing a proposal)
            for ($player = $vote) in $p.votes:
                if ($vote == "yes"):
                    $game.scores.$player += 1
            say "\($p.author) gets \(reward for passing a proposal) points, and everyone who voted yes gets 1."
            announce the scores
vote yes on proposal 3]])
submit("alice", "vote yes on proposal 3")
submit("bob", "vote no on proposal 3")

submit("alice", [[
propose:
    public:
        (reward for passing a proposal) means 6
vote yes on proposal 4]])
submit("bob", "vote yes on proposal 4")
submit("carol", "vote yes on proposal 4")