Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

corkscrew.gno

2.19 Kb · 73 lines
 1// Package corkscrew is a community challenge for the Cellar, written by
 2// a player to show how any realm can join the hall by importing the flag
 3// package. It is about the order in which an avl.Tree iterates.
 4package corkscrew
 5
 6import (
 7	"strconv"
 8	"strings"
 9
10	"gno.land/p/g15c02s5hhdny9uvr9za3xsyn9sw8p0klptrh6kf/cellar/flag"
11	"gno.land/p/nt/avl/v0"
12	"gno.land/r/g15c02s5hhdny9uvr9za3xsyn9sw8p0klptrh6kf/cellar/hall"
13)
14
15var info = flag.Info{
16	Slug:       "corkscrew",
17	Title:      "The Corkscrew",
18	Difficulty: flag.Easy,
19	Category:   "avl trees",
20	Brief: "The cellar opens its oldest bottle first. The register is kept by year, and only bottles " +
21		"younger than 1900 may be added. Get your own bottle opened first.",
22}
23
24var (
25	captures = flag.NewLedger()
26	shelf    = avl.NewTree() // year as decimal string -> owner address
27)
28
29func init(cur realm) {
30	shelf.Set("1811", cur.Address()) // the house bottle belongs to the realm
31	hall.Enlist(cross(cur), challenge{})
32}
33
34type challenge struct{}
35
36func (challenge) Info() flag.Info              { return info }
37func (challenge) Captured(player address) bool { return captures.Captured(player) }
38
39// Shelve adds your bottle of the given year to the shelf.
40func Shelve(cur realm, year int) {
41	if year <= 1900 {
42		panic("corkscrew: only bottles after 1900 may be shelved")
43	}
44	key := strconv.Itoa(year)
45	if shelf.Has(key) {
46		panic("corkscrew: a bottle of that year is already shelved")
47	}
48	shelf.Set(key, cur.Previous().Address())
49}
50
51// Open opens the oldest bottle on the shelf: the first one the register
52// lists. If it is yours, the flag is yours.
53func Open(cur realm) {
54	player := flag.MustPlayer(cur.Previous())
55	_, owner := shelf.GetByIndex(0)
56	if owner.(address) != player {
57		panic("corkscrew: the oldest bottle is not yours")
58	}
59	captures.Record(player)
60}
61
62// Render shows the shelf in register order.
63func Render(_ string) string {
64	var b strings.Builder
65	b.WriteString(flag.Card(info, captures))
66	b.WriteString("\n## The shelf, oldest first\n\n")
67	shelf.Iterate("", "", func(year string, v any) bool {
68		b.WriteString("- " + year + ": `" + v.(address).String() + "`\n")
69		return false
70	})
71	b.WriteString("\n## Captured by\n\n" + flag.Captures(captures, 5))
72	return b.String()
73}