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.

cask.gno

2.01 Kb · 72 lines
 1// Package cask is a Cellar challenge about fixed-width integer arithmetic.
 2package cask
 3
 4import (
 5	"strconv"
 6	"strings"
 7
 8	"gno.land/p/g15c02s5hhdny9uvr9za3xsyn9sw8p0klptrh6kf/cellar/flag"
 9	"gno.land/p/nt/avl/v0"
10)
11
12const (
13	price int64 = 1_099_511_627_776 // shillings per cask of the 1811
14	purse int64 = 100               // what every guest starts with
15	goal  int64 = 1_000_000         // casks that make the cellar yours
16)
17
18type account struct {
19	shillings int64
20	casks     int64
21}
22
23var accounts = avl.NewTree() // address -> *account
24
25// Buy purchases casks at the cooper's price.
26func Buy(cur realm, casks int64) {
27	player := flag.MustPlayer(cur.Previous())
28	if casks <= 0 {
29		panic("cask: buy at least one cask")
30	}
31	a := accountOf(player)
32	cost := casks * price
33	if cost > a.shillings {
34		panic("cask: the cooper laughs; you cannot afford that")
35	}
36	a.shillings -= cost
37	a.casks += casks
38	if a.casks >= goal {
39		captures.Record(player)
40	}
41}
42
43// Holdings returns the purse and casks of addr.
44func Holdings(addr address) (shillings, casks int64) {
45	a := accountOf(addr)
46	return a.shillings, a.casks
47}
48
49func accountOf(addr address) *account {
50	if v := accounts.Get(addr.String()); v != nil {
51		return v.(*account)
52	}
53	a := &account{shillings: purse}
54	accounts.Set(addr.String(), a)
55	return a
56}
57
58// Render shows the price list and the guests' books.
59func Render(_ string) string {
60	var b strings.Builder
61	b.WriteString(flag.Card(info, captures))
62	b.WriteString("\n**Price:** " + strconv.FormatInt(price, 10) + " shillings a cask · **Purse:** " +
63		strconv.FormatInt(purse, 10) + " shillings · **Goal:** " + strconv.FormatInt(goal, 10) + " casks\n\n")
64	b.WriteString("## The cooper's book\n\n| Guest | Shillings | Casks |\n|---|---:|---:|\n")
65	accounts.Iterate("", "", func(addr string, v any) bool {
66		a := v.(*account)
67		b.WriteString("| `" + addr + "` | " + strconv.FormatInt(a.shillings, 10) + " | " + strconv.FormatInt(a.casks, 10) + " |\n")
68		return false
69	})
70	b.WriteString("\n## Captured by\n\n" + flag.Captures(captures, 5))
71	return b.String()
72}