rack.gno
2.03 Kb · 68 lines
1// Package rack is a Cellar challenge about who may write an object, and
2// why a read-only view of a /p/ type is not read-only.
3package rack
4
5import (
6 "strings"
7
8 "gno.land/p/g15c02s5hhdny9uvr9za3xsyn9sw8p0klptrh6kf/cellar/flag"
9 "gno.land/p/nt/avl/v0"
10)
11
12// Prize is the bottle nobody has ever been promised.
13const Prize = "1811 Château d'Yquem"
14
15// Rack is the reserve rack: which bottle is set aside for which guest.
16type Rack struct {
17 Keeper address
18 Reserved *avl.Tree // guest address -> bottle
19}
20
21// Ledger is posted on the door for every realm to read. Other realms can
22// import it but cannot change it: Gno makes their view of it read-only.
23var Ledger = &Rack{
24 Keeper: address("g15c02s5hhdny9uvr9za3xsyn9sw8p0klptrh6kf"),
25 Reserved: avl.NewTree(),
26}
27
28// Reserve sets a bottle aside for guest. Only the keeper reserves, and the
29// keeper never reserves the Prize.
30func Reserve(cur realm, guest address, bottle string) {
31 if cur.Previous().Address() != Ledger.Keeper {
32 panic("rack: only the keeper reserves bottles")
33 }
34 if bottle == Prize {
35 panic("rack: the keeper would never")
36 }
37 Ledger.Reserved.Set(guest.String(), bottle)
38}
39
40// Collect hands over the bottle reserved in your name. If it is the Prize,
41// the flag is yours.
42func Collect(cur realm) {
43 player := flag.MustPlayer(cur.Previous())
44 v := Ledger.Reserved.Get(player.String())
45 if v == nil {
46 panic("rack: nothing is reserved in your name")
47 }
48 if v.(string) != Prize {
49 panic("rack: you collect a " + v.(string) + ". Pleasant, but not the flag")
50 }
51 captures.Record(player)
52}
53
54// Render shows the rack.
55func Render(_ string) string {
56 var b strings.Builder
57 b.WriteString(flag.Card(info, captures))
58 b.WriteString("\n**Keeper:** `" + Ledger.Keeper.String() + "`\n\n## Reserved\n\n")
59 if Ledger.Reserved.Size() == 0 {
60 b.WriteString("*Nothing set aside.*\n")
61 }
62 Ledger.Reserved.Iterate("", "", func(addr string, v any) bool {
63 b.WriteString("- `" + addr + "`: " + v.(string) + "\n")
64 return false
65 })
66 b.WriteString("\n## Captured by\n\n" + flag.Captures(captures, 5))
67 return b.String()
68}