Playground
codec.gno
package golf
import (
"strconv"
"strings"
)
// How golf's rows are kept in store: strings, never golf's own types (a value
// of a realm's type kept in another realm would carry this realm's methods into
// it, and would not outlive these rules). Each is its format's version, then
// its fields, each as its length, ":" and itself (store's own rows are so): a
// row reads back by its lengths, not by a scan of every byte (a scan, as
// strings.Split, costs several times more gas), whatever its fields hold. A
// later version of the rules reads every format ever written, row by row.
const format = "1"
func join(fs ...string) string {
var sb strings.Builder
sb.WriteString("1:" + format)
for _, f := range fs {
sb.WriteString(strconv.Itoa(len(f)) + ":" + f)
}
return sb.String()
}
// fields is a row's fields, its format checked: n of them, or it panics.
func fields(s, what string, n int) []string {
f := make([]string, 0, n+1)
for rest := s; len(rest) > 0; {
i, l := 0, 0
for i < len(rest) && i < 6 && rest[i] >= '0' && rest[i] <= '9' {
l = l*10 + int(rest[i]-'0')
i++
}
if i == 0 || i == len(rest) || rest[i] != ':' || len(rest)-i-1 < l || len(f) > n {
panic("golf: a " + what + " not as golf keeps it: " + strconv.Quote(s))
}
f = append(f, rest[i+1:i+1+l])
rest = rest[i+1+l:]
}
if len(f) != n+1 || f[0] != format {
panic("golf: a " + what + " not as golf keeps it: " + strconv.Quote(s))
}
return f[1:]
}
func itoa(n int) string { return strconv.Itoa(n) }
func i64(n int64) string { return strconv.FormatInt(n, 10) }
func ftoa(x float64) string { return strconv.FormatFloat(x, 'g', -1, 64) } // (exact: it reads back to the same float)
func btoa(b bool) string {
if b {
return "1"
}
return "0"
}
func atoi(s string) int {
n, err := strconv.Atoi(s)
if err != nil {
panic("golf: a number not as golf keeps it: " + strconv.Quote(s))
}
return n
}
func atoi64(s string) int64 {
n, err := strconv.ParseInt(s, 10, 64)
if err != nil {
panic("golf: a number not as golf keeps it: " + strconv.Quote(s))
}
return n
}
func atof(s string) float64 {
x, err := strconv.ParseFloat(s, 64)
if err != nil {
panic("golf: a number not as golf keeps it: " + strconv.Quote(s))
}
return x
}
// --- a version of a hole -------------------------------------------------------
func encodeEntry(e *entry) string {
out := []string{"", "", "", "", ""} // never archived: no drain
if e.out != nil {
out = []string{"1", e.out.from[assisted], e.out.from[pro], btoa(e.out.done[assisted]), btoa(e.out.done[pro])}
}
return join(append([]string{e.id, e.name, itoa(e.par), e.world, ftoa(e.order), btoa(e.official),
e.slot, itoa(e.version), e.by.String(), i64(e.height), e.sha, e.note,
itoa(e.plays), itoa(e.best), itoa(e.proBest), e.bestBy.String(), e.proBestBy.String(), e.next}, out...)...)
}
func decodeEntry(s string) *entry {
f := fields(s, "hole", 23)
e := &entry{id: f[0], name: f[1], par: atoi(f[2]), world: f[3], order: atof(f[4]), official: f[5] == "1",
slot: f[6], version: atoi(f[7]), by: address(f[8]), height: atoi64(f[9]), sha: f[10], note: f[11],
plays: atoi(f[12]), best: atoi(f[13]), proBest: atoi(f[14]), bestBy: address(f[15]), proBestBy: address(f[16]), next: f[17]}
if f[18] == "1" {
e.out = &draining{from: [modes]string{f[19], f[20]}, done: [modes]bool{f[21] == "1", f[22] == "1"}}
}
return e
}
// --- a round under way ---------------------------------------------------------
func encodeRound(r *round) string {
return join(ftoa(r.bx), ftoa(r.by), ftoa(r.fx), ftoa(r.fy), itoa(r.strokes), i64(r.period), r.shots, itoa(r.mode))
}
func decodeRound(s string) *round {
f := fields(s, "round", 8)
return &round{bx: atof(f[0]), by: atof(f[1]), fx: atof(f[2]), fy: atof(f[3]), strokes: atoi(f[4]), period: atoi64(f[5]), shots: f[6], mode: atoi(f[7])}
}
// --- a course standing ---------------------------------------------------------
func encodeRow(r *row) string {
return join(r.player, itoa(r.holes), itoa(r.strokes), itoa(r.par), i64(r.height))
}
func decodeRow(s string) *row {
f := fields(s, "standing", 5)
return &row{player: f[0], holes: atoi(f[1]), strokes: atoi(f[2]), par: atoi(f[3]), height: atoi64(f[4])}
}
data.gno
package golf
import (
"chain"
"chain/runtime"
"crypto/sha256"
"encoding/hex"
"math"
"strconv"
"strings"
"unicode"
"unicode/utf8"
"gno.land/p/nym-alexiscolin000/gnogolf/course"
)
// Holes as data: a version is a GG1 string, checked once at publish and kept
// as bytes; each call decodes it afresh and stores nothing of it. A version
// is never edited or removed: a new one takes its alias, and the old one is
// archived, still playable, its records kept.
// wearGrid is the entry's wear: a count of balls at rest per cell of the
// WearW by WearH grid, row-major.
func (e *entry) wearGrid() []int {
out := make([]int, wearCells)
e.wear().Iterate("", "", func(k, v string) bool {
if i := atoi(k); i >= 0 && i < wearCells {
out[i] = atoi(v)
}
return false
})
return out
}
const wearCells = course.WearW * course.WearH
// wear is a version's wear counters: pad(cell, 3) -> balls at rest there, a
// row a cell played (one small write a stroke).
func (e *entry) wear() view { return view{"wear", e.id + " "} }
// mark counts a ball come to rest in wear cell i.
func (e *entry) mark(i int) {
if i < 0 || i >= wearCells {
return // course.WearIndexOn never gives one
}
k := pad(i, 3)
n := 0
if v, ok := e.wear().Get(k); ok {
n = atoi(v)
}
e.wear().Set(k, itoa(n+1))
}
// maxData bounds a version's data: a hole at every limit of the format is
// about 21 KB.
const maxData = 32 << 10
// Publish puts a course hole's data into its slot as its next version and
// returns the new id ("garden/7/v2"). Only the owner can. hexData is the hole
// as course.Encode wrote it, in hex. slot must be the data's own world and
// order ("garden/7", order 1 to 999), so a mis-edited file cannot replace the
// wrong hole; the course holds at most 9999 slots (maxCourse). Data identical
// to the current version's is refused. The version it replaces is archived:
// its records stay, its bests leave the course standings. note (at most 140
// characters, cleaned) says why.
func Publish(cur realm, slot, hexData, note string) string {
begin()
r := publishNow(cur, slot, hexData, note)
flush(cur) // (only once it went through: a refusal writes nothing)
return r
}
func publishNow(cur realm, slot, hexData, note string) string {
by := cur.Previous().Address()
if !isOwner(by) {
panic("golf: only the owner can publish a course hole")
}
h, data, sum := decodeData(hexData)
if h.Order < 1 || h.Order != math.Trunc(h.Order) {
panic("golf: a course hole's order is a whole number from 1 to 999")
}
own := h.World + "/" + strconv.Itoa(int(h.Order))
if slot != own {
panic("golf: this data is " + own + ", not " + slot)
}
key, ok := slotKeyOf(slot)
if !ok {
panic("golf: " + slot + " is not a course slot") // its data's own world/order: cannot happen
}
var old *entry
n := 1
if v, ok := slots.Get(key); ok {
old = find(v)
if old.sha == sum {
panic(nothingNew(old))
}
n = old.version + 1
} else if slots.Size() >= maxCourse {
panic("golf: the course is full: 9999 slots")
}
e := dataEntry(slot, n, h, by, sum, note)
e.official = true
saveEntry(e)
holeData.Set(e.id, data)
slots.Set(key, e.id)
chain.Emit(EventHolePublished, "hole", e.id, "slot", slot, "sha", sum, "by", by.String(), "official", "true")
if old != nil {
retire(old, e.id)
}
return e.id
}
// PublishMine publishes a community hole of the caller's own and returns its
// id: "<caller>/<slug>/v1", then v2 and on. Anyone can while publishing is
// open (SetPublishing); only the same address adds versions. slug is 1 to 32
// of a-z, 0-9 and "-". The data is checked as Publish checks it, its world
// and order aside; its name and note carry no web address. It is playable and
// recorded, in no cup and not in the course ranking; a new version of a
// hidden hole stays hidden. The publisher pays the storage deposit (about
// half a GNOT a version), and nothing published can be deleted.
func PublishMine(cur realm, slug, hexData, note string) string {
begin()
r := publishMineNow(cur, slug, hexData, note)
flush(cur) // (only once it went through: a refusal writes nothing)
return r
}
func publishMineNow(cur realm, slug, hexData, note string) string {
if !publishing {
panic("golf: publishing community holes is not open yet")
}
by := cur.Previous().Address()
if !validSlug(slug) {
panic("golf: a slug is 1 to 32 of a-z, 0-9 and -")
}
alias := by.String() + "/" + slug
h, data, sum := decodeData(hexData)
var old *entry
n := 1
if v, ok := aliases.Get(alias); ok {
old = find(v)
if old.sha == sum {
panic(nothingNew(old))
}
n = old.version + 1
}
e := dataEntry(alias, n, h, by, sum, note)
if linkish(e.name) || linkish(e.note) {
panic("golf: a community hole's name and note carry no web address")
}
saveEntry(e)
holeData.Set(e.id, data)
aliases.Set(alias, e.id)
if old != nil {
old.next = e.id // archived; it never counted anywhere
saveEntry(old)
}
if !hidden.Has(alias) { // a hidden hole has no row (Hide)
a := by.String()
// the newest row: the author's own moves to its height
moveAuthor(a, newestRow(a), pad(int(e.height), 12))
if old != nil {
byAuthor.Remove(a + " " + recentKey(old.height, slug))
}
byAuthor.Set(a+" "+recentKey(e.height, slug), e.id)
}
chain.Emit(EventHolePublished, "hole", e.id, "slot", alias, "sha", sum, "by", by.String(), "official", "false")
return e.id
}
// newestRow is the height of an author's newest row in byAuthor
// ("<address> <height> <slug>"), "" if they have none.
func newestRow(a string) string {
latest := ""
byAuthor.ReverseIterate(a+" ", a+"!", func(k, _ string) bool {
latest = k[len(a)+1 : len(a)+13]
return true
})
return latest
}
// newestRowBut is newestRow with the row but left out ("" if it was their only one).
func newestRowBut(a, but string) string {
latest := ""
byAuthor.ReverseIterate(a+" ", a+"!", func(k, _ string) bool {
if k == but {
return false
}
latest = k[len(a)+1 : len(a)+13]
return true
})
return latest
}
// moveAuthor moves an author's own row in byAuthor (recentKey(height,
// address)) from the height was to now, "" for none: it stays at their
// newest row's, and goes with their last.
func moveAuthor(a, was, now string) {
if was == now {
return
}
if was != "" {
byAuthor.Remove(was + " " + a)
}
if now != "" {
byAuthor.Set(now+" "+a, "")
}
}
// linkish spots a web address in a community hole's name or note: "www.", a
// dot between a letter or digit and two letters ("claim.xyz", "t.me"; not
// "e.g."), or an IP address, look-alike dots (.。․﹒) read as dots, letters in
// any case. Basic (the owner can Hide what gets past) and strict on purpose
// ("St.Andrews" is refused). It reads s a byte at a time: every mark is
// ASCII, so a non-ASCII character is decoded only to tell İ and the Kelvin
// sign (which lower-case to ASCII), the look-alike dots and spaces apart.
func linkish(s string) bool {
var c1, c2, c3 byte // the three characters before c, lower-cased
// the word so far (as strings.Fields splits): an IP is digits, three dots
word, ip, dots := false, true, 0
for i := 0; i < len(s); {
c, size, space := s[i], 1, false
switch {
case c >= 'A' && c <= 'Z':
c += 'a' - 'A'
case c >= utf8.RuneSelf:
var r rune
r, size = utf8.DecodeRuneInString(s[i:])
switch r {
case 'İ':
c = 'i'
case '\u212a': // the Kelvin sign
c = 'k'
case '.', '。', '․', '﹒':
c = '.'
default:
c, space = utf8.RuneSelf, unicode.IsSpace(r) // none of the marks
}
case c == ' ' || c >= '\t' && c <= '\r':
space = true
}
i += size
switch {
case c == '.' && c1 == 'w' && c2 == 'w' && c3 == 'w':
return true
case isLower(c) && isLower(c1) && c2 == '.' && (isLower(c3) || isDigit(c3)):
return true
}
c1, c2, c3 = c, c1, c2
if space {
if word && ip && dots == 3 {
return true
}
word, ip, dots = false, true, 0
continue
}
word = true
if c == '.' {
dots++
} else if !isDigit(c) {
ip = false
}
}
return word && ip && dots == 3
}
func isLower(c byte) bool { return c >= 'a' && c <= 'z' }
func isDigit(c byte) bool { return c >= '0' && c <= '9' }
// decodeData checks a version's data as it arrives: hex, GG1 within the
// format's limits, stored lengths bit-exact (DecodeChecked: every later
// Decode trusts them), and in the one form Encode gives.
func decodeData(hexData string) (*course.Simple, string, string) {
if len(hexData) > 2*maxData {
panic("golf: the data is too long")
}
b, err := hex.DecodeString(hexData)
if err != nil {
panic("golf: the data is not hex")
}
data := string(b)
h, err := course.DecodeChecked(data)
if err != nil {
panic("golf: " + err.Error())
}
// one hole, one string: data that decodes to a hole Encode would write
// otherwise (a skin never used, a style run split, a stored length a
// zero-length wall never reads) is refused, so the same hole cannot come
// back under another sha
if course.Encode(h) != data {
panic("golf: the data is not as course.Encode writes it")
}
// refused if a transaction could not replay its heaviest shot, or if in
// its dearest weather a commit's first shot would be capped below
// minShotWork: every commit decodes the hole and draws its forecast first
if newWork(h, nil).bound > maxShotGas {
panic(errShotTooHeavy)
}
if worstGas(h, len(data)) > workBudget {
panic(errTooStormy)
}
sum := sha256.Sum256(b)
return h, data, hex.EncodeToString(sum[:])
}
// nothingNew refuses data identical to the alias's current version: it would
// reset the hole's ranking for nothing.
func nothingNew(old *entry) string {
return "golf: this data is already " + old.id + ": nothing to publish"
}
func dataEntry(alias string, n int, h *course.Simple, by address, sum, note string) *entry {
e := newEntry(alias+"/v"+strconv.Itoa(n), cleanName(h.Title), h.Par(), h.World, h.Order)
e.slot, e.version, e.by, e.height, e.sha, e.note = alias, n, by, runtime.ChainHeight(), sum, cleanText(note, maxNote)
return e
}
// worlds is the course's worlds in play order, with their names on the page.
var worlds = []struct{ id, name string }{
{"garden", "Garden Cup"},
{"island", "Island Cup"},
{"town", "Mushroom Town"},
{"mountain", "Mountain Cup"},
{"mines", "Crystal Mines"},
}
// worldRank is a world's place among worlds; any other comes after.
func worldRank(w string) int {
for i, x := range worlds {
if x.id == w {
return i
}
}
return len(worlds)
}
// slotKey is a slot's key: its world's rank, the world, and the order in
// three digits, so the slots tree is in course order.
func slotKey(world string, order int) string {
return string(rune('0'+worldRank(world))) + world + "/" + pad(order, 3)
}
// slotKeyOf reads a slot, "world/order" (as "garden/7"), into its key.
func slotKeyOf(slot string) (string, bool) {
i := strings.Index(slot, "/")
if i < 0 || !course.IsWorld(slot[:i]) {
return "", false
}
n, err := strconv.Atoi(slot[i+1:])
if err != nil || n < 1 || n > course.MaxOrder || strconv.Itoa(n) != slot[i+1:] {
return "", false
}
return slotKey(slot[:i], n), true
}
func validSlug(s string) bool {
if len(s) < 1 || len(s) > 32 {
return false
}
for i := 0; i < len(s); i++ {
if c := s[i]; !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-') {
return false
}
}
return true
}
// HoleData is a version's GG1, in hex, as it was published (an alias gives
// its current version's): what a later version of the rules or an auditor
// reads back.
func HoleData(hole string) string {
e := readHole(hole)
data, _ := holeData.Get(e.id)
return hex.EncodeToString([]byte(data))
}
// Current is the id of the version an alias ("garden/7", "<address>/<slug>")
// plays now, "" if the alias has none.
func Current(alias string) string { return current(alias) }
// Versions is every version of an alias, oldest first (the newest pageMax if
// there are more): its id, number, the height it was published at, by whom,
// its data's sha256, its note, and the version that took its place. slot is
// the alias, "" (and no versions) for one that has none.
func Versions(alias string) string {
now := find(current(alias))
slot := ""
if now != nil {
slot = now.slot // never the caller's own bytes
}
var sb strings.Builder
sb.WriteString("{" + versionJSON + `,"slot":` + jstr(slot) + `,"versions":[`)
if now != nil {
i := 0
for n := firstVersion(now); n <= now.version; n++ {
e := find(now.slot + "/v" + strconv.Itoa(n))
if e == nil {
continue // (one before this course's first here: imported from v1, with v1's number)
}
sb.WriteString(sep(i) + `{"id":` + jstr(e.id) + `,"v":` + strconv.Itoa(e.version) +
`,"height":` + strconv.FormatInt(e.height, 10) + `,"by":` + jstr(e.by.String()) +
`,"sha":` + jstr(e.sha) + `,"note":` + jstr(e.note) + `,"next":` + jstr(e.next) + "}")
i++
}
}
sb.WriteString("]}")
return sb.String()
}
// firstVersion is the oldest of now's versions a list shows: the newest
// pageMax are (now is its alias's current version).
func firstVersion(now *entry) int {
if now.version > pageMax {
return now.version - pageMax + 1
}
return 1
}
// BestOf is a player's best finished round on a hole in a mode, 0 if none.
func BestOf(hole, mode string, player address) int {
e, m := readHole(hole), modeOf(mode)
return bestStrokes(bestOfPlayer(e, m, player.String()))
}
featured.gno
package golf
import (
"strconv"
"time"
)
// The records the hub puts forward (as the site's boards, web/lib/featured.ts,
// whose draw and rules these are): not the course ranking's top three, a few
// players worth racing today, each for a reason said beside them. One a
// player, drawn again each day (the same day, the same picks as the site's,
// but for the players the site's bot check hides: the chain knows none).
// featuredRead is how much of the course ranking the picks look at: its first
// page; podium, its first places, which get no card of their own.
const (
featuredRead = 50
podium = 3
)
// pick is a player put forward, and why.
type pick struct {
r *row
name string
at int // their place on the ranking
tag string
}
// today is the day, a number: the picks hold for it and change with it (block time).
func today() int64 { return time.Now().Unix() / 86400 }
// draw is a player's draw for a day: FNV-1a over their address, seeded with
// the day (featured.ts draw: the same numbers, so the same picks).
func draw(player string, day int64) uint32 {
h := uint32(2166136261) ^ uint32(day)
for i := 0; i < len(player); i++ {
h = (h ^ uint32(player[i])) * 16777619
}
return h
}
// featured is up to n picks from the course ranking in mode m: a fast start (a
// third of the course or less, at par or better), the best average against par
// (a third of the course played, nine holes at least), and today's picks for
// the rest; never the first three places.
func featured(m, n int) []pick {
// every named row read, the first three too (the best average is the
// course's, as featured.ts takes it, whoever holds it), numbered as the
// boards number them: a row whose name was deleted keeps no place
var rows []pick
walked, at := 0, 0
ranks[m].Iterate("", "", func(_, p string) bool {
walked++
if name := nameOf(p); name != "" {
at++
rows = append(rows, pick{r: rowOf(m, p), name: name, at: at})
}
return walked >= featuredRead
})
course := slots.Size()
third := course / 3
perHole := func(r *row) float64 { return float64(r.strokes-r.par) / float64(r.holes) }
var rising, many []pick
for _, x := range rows {
if x.r.holes > 0 && x.r.holes <= max1(third) && x.r.strokes <= x.r.par {
rising = append(rising, x)
}
if x.r.holes >= nine(third) {
many = append(many, x)
}
}
var sharp []pick
for _, x := range many {
switch {
case len(sharp) == 0 || perHole(x.r) < perHole(sharp[0].r):
sharp = []pick{x}
case perHole(x.r) == perHole(sharp[0].r):
sharp = append(sharp, x)
}
}
day := today()
var out []pick
used := map[string]bool{}
take := func(from []pick, tag string, again bool) {
for len(out) < n {
best := -1
for i, x := range from {
if !used[x.r.player] && x.at > podium && (best < 0 || draw(x.r.player, day) < draw(from[best].r.player, day)) {
best = i
}
}
if best < 0 {
return
}
x := from[best]
used[x.r.player] = true
x.tag = tag
if tag == "Today's pick" && countTag(out, tag) > 0 {
x.tag = "Also today"
}
out = append(out, x)
if !again {
return
}
}
}
take(rising, "Fast start", false)
take(sharp, "Best average", false)
take(rows, "Today's pick", true)
return out
}
func countTag(ps []pick, tag string) int {
n := 0
for _, p := range ps {
if p.tag == tag {
n++
}
}
return n
}
func max1(n int) int {
if n < 1 {
return 1
}
return n
}
func nine(n int) int {
if n < 9 {
return 9
}
return n
}
// featuredRows is the hub's records to beat in mode m, as markdown lines.
func featuredRows(m int) string {
s := ""
for _, x := range featured(m, 3) {
s += "- **" + x.tag + ":** " + md("@"+x.name, "/u/"+x.name) + ", " + count(x.r.holes, "hole") + " at " + vsPar(x.r.strokes-x.r.par) +
" (#" + strconv.Itoa(x.at) + ") · " + md("race their ghosts", playURL+"?by="+x.r.player) + "\n"
}
return s
}
gnomod.toml
module = "gno.land/r/nym-alexiscolin000/gnogolf/golf/v2" gno = "0.9" [addpkg] creator = "g1mpkp5lm8lwpm0pym4388836d009zfe4maxlqsq" height = 125560 max_deposit = "60000000ugnot"
golf.gno
// Package golf is the game realm: it keeps the holes, the players' rounds,
// the records and the rankings. Every hole is data (a GG1 string, p/…/course),
// never code: golf decodes it and plays it with p/…/physics. The owner
// publishes the course's holes into slots of a cup ("garden/7"), each publish
// a new version ("garden/7/v2"); once the owner opens publishing, anyone can
// publish a community hole ("<address>/<slug>/v1", PublishMine), playable and
// recorded but outside the course and its ranking.
//
// Reads take a version's id or its alias ("garden/7", "<address>/<slug>"),
// its current version. Writes take the exact id only, as HoleState or Holes gave
// it: a round cannot be replayed on a version it was not played on.
//
// Who can change what (in full on the hub page): the owner holds one power,
// the course itself: its holes (Publish), what the lists show (Hide), and
// whether anyone can publish (SetPublishing).
package golf
import (
"chain"
"chain/runtime"
"math"
"strconv"
"strings"
"unicode"
"gno.land/p/nym-alexiscolin000/gnogolf/course"
"gno.land/p/nym-alexiscolin000/gnogolf/physics"
"gno.land/p/nt/ufmt/v0"
"gno.land/r/sys/users"
)
const (
maxPower = 10.0
// maxShots bounds a commit; its work (workBudget) may bound it lower.
maxShots = 12
)
// The refusals said in more than one place.
const (
errShot = "golf: a shot is an angle and a power between 0 and 10"
errFine = "golf: a shot's angle and power go in steps of 0.01, as the game sends them"
errStrokeLimit = "golf: this round is over its stroke limit, Reset to play again"
errShotTooHeavy = "golf: one shot on this hole could cost more than a transaction can replay"
errTooStormy = "golf: in its dearest weather, a commit on this hole would leave too little room for a shot"
errUnknownHole = "golf: unknown hole: "
)
type entry struct {
id string // "<alias>/v<n>"
name string // the hole's name, cleaned; frozen when it was published
par int // frozen like the name
world string // "garden", "island", "town": frozen too
order float64
// official: a version the owner published into a slot; only these rank
official bool
// its provenance, set at publish (the hole itself is never stored: hole())
slot string // the alias it answers to: "garden/7", "<address>/<slug>"
version int // its number under that alias, from 1
by address // who published it
height int64
sha string // sha256 of its data, hex
note string
// Its rounds, bests, board and wear are rows of store's shared collections
// (views), not trees of its own, whose first leaf (a few KB) its first
// player would pay.
plays int
// the records per mode (rec), flat: a nested object costs a few hundred
// bytes more
best, proBest int
bestBy, proBestBy address
next string // the version that took this one's place, "" while it is current
// its drain once archived (drain); nil if never archived
out *draining
}
// The versions: the course's, current and archived, and everyone else's: id -> encodeEntry.
var (
courseHoles = view{"holes", ""}
community = view{"community", ""}
)
// saveEntry keeps a version as it is now: every call that changes one ends with it.
func saveEntry(e *entry) {
if seen != nil {
seen[e.id] = e
}
if e.official {
courseHoles.Set(e.id, encodeEntry(e))
} else {
community.Set(e.id, encodeEntry(e))
}
}
// record is the hole's record in one mode: who holds it, in how many
// strokes, 0 if never completed.
type record struct {
by address
best int
}
// rec is the entry's record in mode m.
func (e *entry) rec(m int) record {
if m == pro {
return record{e.proBestBy, e.proBest}
}
return record{e.bestBy, e.best}
}
// roundTree is the version's rounds under way: player address -> *round. A
// round is stored from its first commit that does not finish it, and removed
// as it is holed (stroke) or Reset: a finish is kept as a best, not a round.
func (e *entry) roundTree() view { return view{"rounds", e.id + " "} }
// bests is the version's results in mode m: player address -> their best
// finished round there, kept across replays, as bestOf writes it.
func (e *entry) bests(m int) view { return bestsOf(e.id, m) }
func bestsOf(id string, m int) view { return view{"bests", id + " " + modeNames[m] + " "} }
// bestOf is how a best is kept: "<strokes> <height> <period> <shots>". The
// height ranks it before a later tie (boardKey); the period and shots let
// Ghost replay it in its own weather. The mode is in the key.
func bestOf(r *round) string {
return strconv.Itoa(r.strokes) + " " + strconv.FormatInt(runtime.ChainHeight(), 10) + " " +
strconv.FormatInt(r.period, 10) + " " + r.shots
}
// errBest is a best not as bestOf writes it: never written, refused if read.
const errBest = "golf: a best not as bestOf writes it: "
// bestStrokes is a kept best's strokes, 0 for none ("").
func bestStrokes(s string) int {
if s == "" {
return 0
}
i := strings.Index(s, " ")
if i < 0 {
panic(errBest + s)
}
n, err := strconv.Atoi(s[:i])
if err != nil {
panic(errBest + s)
}
return n
}
// bestFields is a kept best's height, period and shots.
func bestFields(s string) (int64, int64, string) {
f := strings.SplitN(s, " ", 4)
if len(f) < 4 {
panic(errBest + s)
}
at, err := strconv.ParseInt(f[1], 10, 64)
period, err2 := strconv.ParseInt(f[2], 10, 64)
if err != nil || err2 != nil {
panic(errBest + s)
}
return at, period, f[3]
}
// board is the version's board in mode m: boardKey(best, player) ->
// player, the named players' bests, fewest strokes first.
func (e *entry) board(m int) view { return view{"boards", e.id + " " + modeNames[m] + " "} }
func newEntry(id, name string, par int, world string, order float64) *entry {
return &entry{id: id, name: name, par: par, world: world, order: order}
}
// hole is the entry's hole, decoded from its data for this call only: a
// public call decodes it once and passes it down, and it is never stored.
func (e *entry) hole() *course.Simple {
data, _ := holeData.Get(e.id)
s, err := course.Decode(data)
if err != nil {
panic("golf: the data of " + e.id + " does not decode: " + err.Error()) // checked at publish: cannot happen
}
return s
}
// draining is an archived hole's drain, per mode: the next player to take
// out, and whether all are out. The players whose first finish came after it
// was archived (never counted, so never taken out) are its fresh rows.
type draining struct {
from [modes]string
done [modes]bool
}
// copies is a version's bests sent again from another's (copyOf): player -> "1",
// kept, never ranked (no board row, no standing, no drain to take them out).
func (e *entry) copies(m int) view { return copiesOf(e.id, m) }
func copiesOf(id string, m int) view { return view{"copies", id + " " + modeNames[m] + " "} }
// How near a round must be to a record already on the board, shot for shot,
// to be that record sent again: a player's pull never lands this close to
// another's, three shots running.
const (
copyAngle = 0.05 // degrees, round the circle
copyPower = 0.02
copyMin = 3 // shots: two people keying a short round send alike
copyDepth = 10 // the board's first page: the records worth copying
)
// copyOf reports whether shots are a record of a board's first page (either
// mode's: the modes differ by the client's aim line alone, so a round replays
// the same in both; another player's) sent again: as many shots, each within
// copyAngle and copyPower, three shots or more, one of them pulled (not keyed:
// a whole degree, or a power on 0.5, the keyboard's and a typed form's). The
// tick is not compared: on most holes it changes nothing, and on a timed one
// another tick of the same beat plays the same.
func copyOf(e *entry, p, shots string) bool {
mine := strings.Split(shots, ";")
if len(mine) < copyMin {
return false
}
pulled := false
for _, s := range mine {
if a, pw, _ := parseShot(s); !keyed(a, pw) {
pulled = true
}
}
if !pulled {
return false
}
for m := 0; m < modes; m++ {
n, found := 0, false
e.board(m).Iterate("", "", func(_, q string) bool {
if q == p {
return false
}
_, _, theirs := bestFields(bestOfPlayer(e, m, q))
found = alike(mine, strings.Split(theirs, ";"))
n++
return found || n == copyDepth
})
if found {
return true
}
}
return false
}
// keyed is a shot a keyboard or a form sends: a whole degree, or a power on 0.5.
func keyed(a, p float64) bool {
return math.Abs(a-math.Round(a)) < 1e-6 || math.Abs(p*2-math.Round(p*2)) < 1e-6
}
func alike(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := range a {
x, px, _ := parseShot(a[i])
y, py, _ := parseShot(b[i])
d := math.Mod(math.Abs(x-y), 360) // round the circle: angles are kept in (-360, 360)
if d > 180 {
d = 360 - d
}
if d > copyAngle+1e-9 || math.Abs(px-py) > copyPower+1e-9 {
return false
}
}
return true
}
// fresh is an archived version's first finishes the drain has yet to reach: player -> "1".
func (e *entry) fresh(m int) view { return view{"fresh", e.id + " " + modeNames[m] + " "} }
type round struct {
bx, by float64 // the ball, exactly: flat, not a nested Vec2 object
fx, fy float64 // where the last stroke started: its path is replayed from there
strokes int
period int64 // the weather it is played in: set by its first stroke
shots string // the decisions so far, "angle,power,tick;…": the round, replayable
mode int // assisted or pro: set by its first stroke, like the weather
}
func (r *round) ball() physics.Vec2 { return physics.Vec2{X: r.bx, Y: r.by} }
// A round is played in one of two modes, each with its own records and
// rankings: assisted (the full aim preview) or pro (the preview cut short).
// The chain cannot see a screen: the mode is the player's word.
const (
assisted = iota
pro
modes
)
// modeOf reads a mode's name: "assisted" (or "") or "pro"; anything else
// panics rather than answer for another mode.
func modeOf(name string) int {
switch name {
case "", "assisted":
return assisted
case "pro":
return pro
}
panic(`golf: a mode is "assisted" or "pro", got: ` + name)
}
var modeNames = [modes]string{"assisted", "pro"}
// modeTitles is how the pages head a mode's board.
var modeTitles = [modes]string{"Assisted", "Pro"}
// The indexes: collections of store (kv.gno), shared by every version and
// mode, made at its deploy: a first player pays for their own rows only.
var (
// id -> a version's GG1 string, apart from its entry so that listing
// holes never loads it
holeData = view{"data", ""}
// slotKey(world, order) -> id of the current version there, in course order
slots = view{"slots", ""}
// "<address>/<slug>" -> id of the current version of a community hole
aliases = view{"aliases", ""}
// the listed community holes, two kinds of row in one collection:
// - "<address> " + recentKey(publish height, slug) -> id: an author's
// holes not hidden, newest last;
// - recentKey(their newest row's height, address) -> "": one per
// author (moveAuthor), the latest to publish last.
// A height is digits and an address "g1…": the two never mix.
byAuthor = view{"authors", ""}
// "<address>/<slug>" -> "1": community holes hidden (Hide), every
// version, out of byAuthor; still playable
hidden = view{"hidden", ""}
// recentKey(archive height, id) -> id of an archived course version
archived = view{"archived", ""}
// per mode: player -> encodeRow, their standing over the official holes
totals = [modes]view{{"totals", "assisted "}, {"totals", "pro "}}
// per mode: rankKey(row) -> player, the named players with a hole, best
// first
ranks = [modes]view{{"ranks", "assisted "}, {"ranks", "pro "}}
// per mode: rankKey(row) -> player, standings with no hole left (setRow)
idle = [modes]view{{"ranks", "idle assisted "}, {"ranks", "idle pro "}}
// golf's own settings and the archived holes still draining: meta
meta = view{"meta", ""}
)
// archiving is the archived holes still in the standings, oldest first (drain).
func archiving() []string {
v, _ := meta.Get("archiving")
if v == "" {
return nil
}
return strings.Split(v, " ")
}
func setArchiving(ids []string) { meta.Set("archiving", strings.Join(ids, " ")) }
// row is one player's standing across the course: their best on each hole
// counted, summed, and those holes' pars, summed. Its score against par,
// strokes - par, is what ranks it after its holes.
type row struct {
player string
holes, strokes, par int
height int64 // of the finish that last improved it: the first there ranks first
}
const topSize = 10
// named reports whether a player has a gno.land name (r/sys/users). Only
// named players rank: a name takes a registration, so a script cannot fill
// the boards with free addresses. Every finish is still kept.
func named(player string) bool {
return !users.ResolveAddress(address(player)).IsDeleted()
}
// nameOf is a named player's name, "" for anyone else.
func nameOf(player string) string {
if u := users.ResolveAddress(address(player)); !u.IsDeleted() && nameish(u.Name()) {
return u.Name()
}
return ""
}
// nameish is a name as r/sys/users registers it (a-z, then a-z, 0-9, "_" and
// "-", at most 64), checked again because the pages print names in links.
func nameish(n string) bool {
if n == "" || len(n) > 64 || n[0] < 'a' || n[0] > 'z' {
return false
}
for i := 0; i < len(n); i++ {
if c := n[i]; !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '_' || c == '-') {
return false
}
}
return true
}
// find is the hole with this exact id, nil if none.
// Within a call that writes (begin), a version is one object, however often
// it is found: a finish on an archived hole and the drain it runs change the
// same one, and the call keeps it once as it ends (flush forgets them all).
// A read caches nothing: called within another realm's transaction, it would
// keep its cache in this realm's state, stale once the rules change.
func find(id string) *entry {
if e := seen[id]; e != nil {
return e
}
v, ok := courseHoles.Get(id)
if !ok {
if v, ok = community.Get(id); !ok {
return nil
}
}
e := decodeEntry(v)
if seen != nil {
seen[id] = e
}
return e
}
// current is the id an alias points at now: a course slot's or a community
// hole's current version; "" if it is neither.
func current(alias string) string {
if k, ok := slotKeyOf(alias); ok {
v, _ := slots.Get(k)
return v
}
v, _ := aliases.Get(alias)
return v
}
// mustHole is the hole a write names: its exact id. An alias is refused: a
// new version may have taken its place since the round's shots were chosen.
func mustHole(id string) *entry {
if e := find(id); e != nil {
return e
}
if now := current(id); now != "" {
panic("golf: " + id + " is an alias: play its version by id, " + now)
}
panic(errUnknownHole + id)
}
// readHole is the hole a read names: an exact id, or an alias for its
// current version.
func readHole(id string) *entry {
if e := find(id); e != nil {
return e
}
if now := current(id); now != "" {
return find(now)
}
panic(errUnknownHole + id)
}
// recentKey orders by height, then by what is at that height.
func recentKey(height int64, what string) string { return pad(int(height), 12) + " " + what }
// pad writes n in width digits, zeros first: keys that sort as numbers.
func pad(n, width int) string {
s := strconv.Itoa(n)
for len(s) < width {
s = "0" + s
}
return s
}
// rankKey orders the course ranking: most holes first, then the best score
// against par (a hole at par counts the same whatever its par), then the
// first there, then the address. The score is signed: vsParBias puts it in
// seven digits. The holes take five: a standing can count more than the
// course's slots while a republished hole drains (its old best still counts,
// its new one adds a hole), so they get room well past maxCourse.
func rankKey(r *row) string {
return pad(99999-r.holes, 5) + "/" + pad(vsParBias+r.strokes-r.par, 7) + "/" + pad(int(r.height), 12) + "/" + r.player
}
// maxCourse bounds the course's slots (Publish); a standing's holes are at
// most those plus the archived versions drain has not taken it out of yet.
// vsParBias is more than a standing can be under or over par: a hole is -18
// to +59 (1 to 60 strokes, par 1 to 19), so a full course at most 9999 * 59 =
// 589,941 over, 179,982 under, and the seven digits hold 55,555 holes.
const (
maxCourse = 9999
vsParBias = 1000000
)
// boardKey orders a hole's board by each player's best v: fewest strokes,
// then the first to make them (a best's shots are public: whoever replays
// them ties it and ranks after), then the address.
func boardKey(v string, player string) string {
at, _, _ := bestFields(v)
return pad(bestStrokes(v), 3) + "/" + pad(int(at), 12) + "/" + player
}
// boardStrokes is the strokes of a board's key: always its three digits.
func boardStrokes(k string) int {
n, err := strconv.Atoi(k[:3])
if err != nil {
panic("golf: bad board key: " + k) // pad writes three digits: cannot happen
}
return n
}
// setRow moves a player's standing, as of height at, and keeps the ranking
// in step (and the standing itself). A standing with no hole left is not
// freed, nor its key, which moves to idle: its deposit is the player's, and
// freeing it would refund whoever drained it. It moves back at the player's
// next hole.
func setRow(m int, r *row, n, strokes, par int, at int64) {
k := rankKey(r)
had := ranks[m].Remove(k)
if idle[m].Remove(k) {
had = true
}
r.holes, r.strokes, r.par, r.height = n, strokes, par, at
totals[m].Set(r.player, encodeRow(r))
switch {
case r.holes > 0 && named(r.player):
ranks[m].Set(rankKey(r), r.player)
case had:
idle[m].Set(rankKey(r), r.player)
}
}
// improve moves a player's standing by a new best on an official hole of par
// par (was: their old best there, 0 if none): only those count, or anyone's
// own hole would be a way to the top. The standing is kept, not recomputed,
// so a finish costs the same however many play.
func improve(m int, player string, par, was, best int) {
r := &row{player: player}
if v, ok := totals[m].Get(player); ok {
r = decodeRow(v)
}
if was == 0 {
setRow(m, r, r.holes+1, r.strokes+best, r.par+par, runtime.ChainHeight())
} else {
setRow(m, r, r.holes, r.strokes+best-was, r.par, runtime.ChainHeight())
}
}
// retire archives an official hole replaced by next. Its bests stay there as
// its records but leave the course standings, in batches (drain): the Publish
// takes retireBatch, each course finish finishBatch, a Drain up to drainMax.
func retire(old *entry, next string) {
old.next, old.out = next, &draining{}
saveEntry(old)
archived.Set(recentKey(runtime.ChainHeight(), old.id), old.id)
setArchiving(append(archiving(), old.id))
chain.Emit(EventHoleRetired, "hole", old.id, "next", next)
drain(retireBatch)
}
// How many archived players a Publish, a course finish and a Drain take out
// of the standings: sized so none costs more however many played.
const (
retireBatch = 150
finishBatch = 4
drainMax = 400
)
// drain takes up to n archived players out of the standings, oldest
// archived hole first.
func drain(n int) {
list := archiving()
if len(list) == 0 {
return
}
for n > 0 && len(list) > 0 {
e := find(list[0])
d := e.out
for m := 0; m < modes && n > 0; m++ {
if d.done[m] {
continue
}
stopped := e.bests(m).Iterate(d.from[m], "", func(p string, v string) bool {
if n == 0 {
d.from[m] = p
return true
}
if !e.fresh(m).Has(p) && !e.copies(m).Has(p) { // (neither ever counted)
if t, ok := totals[m].Get(p); ok {
r := decodeRow(t)
setRow(m, r, r.holes-1, r.strokes-bestStrokes(v), r.par-e.par, r.height)
}
}
n--
return false
})
if !stopped {
d.done[m] = true
}
}
saveEntry(e)
if d.done[assisted] && d.done[pro] {
list = list[1:]
}
}
setArchiving(list)
}
// Drain takes up to n players (1 to 400) of archived holes out of the course
// standings, sooner than the finishes would, and returns how many archived
// holes still have players in them. Anyone can call it. A standing it
// empties is kept at 0 holes (setRow): nothing is refunded to the caller.
func Drain(cur realm, n int) int {
begin()
if n < 1 {
n = 1
}
if n > drainMax {
n = drainMax
}
drain(n)
flush(cur)
return len(archiving())
}
// counts reports whether a best on e by player (was: their previous best, 0
// if none) moves their standing: e is a current official hole, or an archived
// one whose drain has not reached them yet and where they already counted. A
// first finish on an archived hole never counts.
func counts(e *entry, m int, player string, was int) bool {
if !e.official {
return false
}
if e.next == "" {
return true
}
if was == 0 || e.out.done[m] || player < e.out.from[m] {
return false
}
return !e.fresh(m).Has(player)
}
// Launch plays one shot of the caller's round on hole (an exact id): angle in
// degrees (0 = right, 90 = down), power in (0, 10]. It is how gnoweb plays,
// with no aim preview, so its rounds are pro rounds. It answers with where
// the ball stopped, or the score if holed; PlayRoundAt commits many shots.
func Launch(cur realm, hole string, angle, power float64) string {
begin()
r := launchNow(cur, hole, angle, power)
flush(cur) // (only once it went through: a refusal writes nothing)
return r
}
func launchNow(cur realm, hole string, angle, power float64) string {
e := mustHole(hole)
h := e.hole()
player := cur.Previous().Address()
r := roundOf(e, h, player)
fresh := r.strokes == 0
if fresh {
r.period = Period() // a round starts in the weather of the moment, and keeps it
r.mode = pro
} else if r.mode != pro {
panic(otherMode(r))
}
fc := weatherOf(e, h, r.period)
w := newWork(h, fc.Zones)
w.fixed = fixedGas(e, fc)
w.next(h)
shot, holed := stroke(e, h, r, player, angle, power, 0, fc.Zones)
w.add(shot)
saveEntry(e)
if holed {
return ufmt.Sprintf("Holed in %d on %s! Your best there: %s:%s/%s", r.strokes, e.id, hub, e.id, player.String())
}
e.roundTree().Set(player.String(), encodeRound(r)) // (under way: kept as it stands now)
// what a gnoweb player needs for the next shot
a, d := aim(r.ball(), h.Cup())
return ufmt.Sprintf("Stroke %d on %s: the ball stopped %.1f from the cup, which is at %.0f° from it. Your round: %s:%s/%s",
r.strokes, e.id, d, a, hub, e.id, player.String())
}
// aim is the angle, in the shot's degrees, and the straight-line distance
// from a ball to the cup: walls and slopes are the player's to allow for.
func aim(from, cup physics.Vec2) (float64, float64) {
d := cup.Sub(from)
a := math.Atan2(d.Y, d.X) * 180 / math.Pi
if a < 0 {
a += 360
}
return a, d.Len()
}
// PlayRound is PlayRoundAt in the current period, for a caller with none to
// give (a form, a script); a round under way keeps its own. Prefer
// PlayRoundAt: a commit included after the weather turned is then played in
// the weather its shots were chosen in.
func PlayRound(cur realm, hole string, shots string) string {
begin()
r := playRoundNow(cur, hole, shots)
flush(cur) // (only once it went through: a refusal writes nothing)
return r
}
func playRoundNow(cur realm, hole string, shots string) string {
e, p := mustHole(hole), cur.Previous().Address()
period := Period()
if v, ok := e.roundTree().Get(p.String()); ok { // (a round is kept from its first stroke on)
period = decodeRound(v).period // stroke() still refuses a stale one
}
return playRound(e, p, shots, period, assisted)
}
// PlayRoundAt replays shots into the caller's assisted round on hole (an
// exact id), continuing it, in the weather of period: the current one or the
// one before, and a round under way keeps its own. The client sends
// decisions, never outcomes: the chain replays them.
//
// shots is "angle,power[,tick];…" (MsgCall carries no slice), at most 12,
// fewer on a heavy hole: a commit past the work budget is refused with the
// number of shots that fit, and the rest goes in the next commit.
func PlayRoundAt(cur realm, hole string, shots string, period int64) string {
begin()
r := playRoundAtNow(cur, hole, shots, period)
flush(cur) // (only once it went through: a refusal writes nothing)
return r
}
func playRoundAtNow(cur realm, hole string, shots string, period int64) string {
return playRound(mustHole(hole), cur.Previous().Address(), shots, period, assisted)
}
// PlayRoundPro is PlayRoundAt for a round played in pro mode: the aim
// preview cut short. It counts on the pro records and rankings only.
func PlayRoundPro(cur realm, hole string, shots string, period int64) string {
begin()
r := playRoundProNow(cur, hole, shots, period)
flush(cur) // (only once it went through: a refusal writes nothing)
return r
}
func playRoundProNow(cur realm, hole string, shots string, period int64) string {
return playRound(mustHole(hole), cur.Previous().Address(), shots, period, pro)
}
func playRound(e *entry, player address, shots string, period int64, mode int) string {
h := e.hole()
r := roundOf(e, h, player)
if r.strokes == 0 {
playablePeriod(period)
r.period, r.mode = period, mode
} else if r.period != period {
panic(ufmt.Sprintf("golf: this round is being played in the weather of period %d", r.period))
} else if r.mode != mode {
panic(otherMode(r))
}
list := shotList(shots)
fc := weatherOf(e, h, r.period) // once for the whole commit
weather := fc.Zones
w := newWork(h, weather)
w.fixed = fixedGas(e, fc)
for _, s := range list {
w.next(h)
angle, power, tick := parseShot(s)
shot, holed := stroke(e, h, r, player, angle, power, tick, weather)
w.add(shot)
if holed {
saveEntry(e)
return ufmt.Sprintf("holed in %d strokes", r.strokes)
}
}
saveEntry(e)
e.roundTree().Set(player.String(), encodeRound(r)) // under way: kept as it stands now
return ufmt.Sprintf("%d shots replayed, ball at %.1f,%.1f after %d strokes",
w.played, r.bx, r.by, r.strokes)
}
// otherMode refuses to go on with a round in a mode it was not started in.
func otherMode(r *round) string {
return "golf: this round is being played in " + modeNames[r.mode] + " mode"
}
// shotList is a commit's shots: the non-empty entries of "a,p;a,p;…", at
// least one and at most maxShots.
func shotList(shots string) []string {
var list []string
for _, s := range strings.Split(shots, ";") {
if s = strings.TrimSpace(s); s == "" {
continue
}
if len(list) == maxShots {
panic("golf: too many shots in one commit")
}
list = append(list, s)
}
if len(list) == 0 {
panic("golf: no shots")
}
return list
}
// work is a commit's estimated gas so far. A shot counts the larger of its
// path's estimate and its Shot.Work's, plus its pulses' set-up, on top of
// what the commit spent before its shots (fixed: decoding, forecast). A shot
// that could pass workBudget is refused before anything is kept, and each is
// played under a work cap (physics.Field.Cap), so no commit can pass it; the
// client mirrors the model. An estimate, not a gas meter: see docs/golf.md,
// "The work budget".
type work struct {
walls, pieces int64 // on the board this commit: walls, and every piece and polygon edge
setup int64 // what each shot spends outside its Shot.Work: a pulse's pieces, set up afresh
bound int64 // shotBound, and the set-up
fixed int64 // spent before the shots: decoding, forecast
spent, most int64
played int
cap int // the work cap of the shot being played
}
// The budget: of the 2e9 gas a wallet lets a transaction simulate, 1.4e9 for
// a commit, decoding and forecast included; the rest for package loads and
// bookkeeping.
const (
workBudget = 1400000000
workPerShot = 10000000
workPerWall = 150000
workPerPoint = 1200000
workPerPiece = 15000
workPerUnit = 1000
// a pulse's walls and posts, set up afresh for each shot outside its
// Shot.Work
workPerPulseWall = 700000
workPerPulsePost = 200000
)
// Decoding a hole's data costs at most decodeBase and decodePerByte a byte.
const (
decodeBase = 6000000
decodePerByte = 4000
)
// fixedGas is what a commit on e spends before its shots, in the forecast
// fc: decoding the hole, and drawing the forecast.
func fixedGas(e *entry, fc course.Forecast) int64 {
data, _ := holeData.Get(e.id)
return decodeGas(len(data)) + int64(fc.Work)*workPerUnit + storeGas
}
// storeGas is what a commit spends keeping its rows in store, on top of v1's
// work: reading the hole, its version and the round across the realm,
// decoding them, and its writes in one batch. Measured at 20.6M on the
// heaviest commit that does not finish (z_worst_play_filetest, against v1's):
// 25M, counted before the shots and at publish (worstGas). A finish spends
// some 30M to 40M more there (its best, the board, the standing, the drain's
// share), outside the work budget, as v1's finish was: the room between the
// budget and what a transaction may ask covers it.
const storeGas = 25000000
// decodeGas bounds decoding size bytes of a hole's data.
func decodeGas(size int) int64 { return decodeBase + decodePerByte*int64(size) }
// maxShotGas bounds a hole's heaviest shot (shotBound and its pulses'
// set-up): a hole past it is refused at publish.
const maxShotGas = 1300000000
// minShotWork is the work, in the physics' units, a commit's first shot may
// always do whatever the weather: four fifths of MaxWork. A shot is capped at
// what is left of the budget (work.next), so a hole whose dearest weather
// would leave less is refused at publish (worstGas): on a published hole,
// every shot of less than minShotWork plays out in any weather (as a commit's
// first, if need be), and an author whose board is too heavy is told at
// publish, not by a hole that misbehaves in the rain. A shot past it may be
// cut short; none is known: the course's heaviest real shot does 441,737
// over the full grid of tee shots (mountain/16, full power, in a storm), and
// the heaviest found in an adversarial search 0.74 of MaxWork (docs/golf.md);
// the course's tightest room in its dearest weather is 839,278 (mountain/7),
// 39,278 over the floor.
const minShotWork = 4 * physics.MaxWork / 5
// worstGas is what a commit on h (size bytes of data) spends up to a first
// shot of minShotWork in its dearest weather: decoding, the forecast at its
// most (course.WorstForecastWork), and the shot, its walls and its pulses'
// set-up, as work.next caps it.
func worstGas(h *course.Simple, size int) int64 {
w := newWork(h, nil)
return decodeGas(size) + storeGas + int64(course.WorstForecastWork(h))*workPerUnit +
workPerShot + w.walls*workPerWall + w.setup + (physics.MaxWorkStep+minShotWork)*workPerUnit
}
// newWork is a commit's work on a hole, before any shot: its walls and
// pieces, a pulse's as if always there, and the weather's.
func newWork(h *course.Simple, weather []physics.Zone) *work {
w := &work{}
if f := h.Field(); f != nil {
w.walls = int64(len(f.Walls))
w.pieces = pieces(f.Walls, f.Posts, f.Zones)
}
for _, p := range h.Pulses {
w.walls += int64(len(p.Walls))
w.pieces += pieces(p.Walls, p.Posts, p.Zones)
w.setup += int64(len(p.Walls))*workPerPulseWall + int64(len(p.Posts))*workPerPulsePost
}
w.pieces += pieces(nil, nil, weather)
w.bound = shotBound(w.walls) + w.setup
return w
}
// shotBound is the most one shot on a board of walls walls can cost: the
// physics ends a stroke at MaxWork, passing it by MaxWorkStep at most.
func shotBound(walls int64) int64 {
return workPerShot + walls*workPerWall + (physics.MaxWork+physics.MaxWorkStep)*workPerUnit
}
// pieces counts what a ball is tested against: each wall, post and zone, and
// each edge of a zone's polygon.
func pieces(ws []physics.Wall, ps []physics.Post, zs []physics.Zone) int64 {
n := len(ws) + len(ps) + len(zs)
for i := range zs {
n += len(zs[i].Poly)
}
return int64(n)
}
// next refuses the next shot if it could overrun the budget, and caps its
// work at what is left of it.
func (w *work) next(h *course.Simple) {
if w.played == 0 && w.bound > workBudget {
w.refuse()
}
if w.played > 0 && w.spent+w.most > workBudget {
w.refuse()
}
c := (workBudget-w.fixed-w.spent-workPerShot-w.walls*workPerWall)/workPerUnit - physics.MaxWorkStep
c -= w.setup / workPerUnit
if c < 1 {
w.refuse()
}
if c > physics.MaxWork {
c = physics.MaxWork
}
w.cap = int(c)
if f := h.Field(); f != nil {
f.Cap = w.cap // the decoded hole of this call only: never stored
}
}
// refuse refuses the shot being played: it does not fit the budget.
func (w *work) refuse() {
if w.played == 0 {
panic(errShotTooHeavy)
}
panic(ufmt.Sprintf("golf: more shots than one transaction can replay on this hole: commit the first %d, then the rest", w.played))
}
func (w *work) add(s physics.Shot) {
if w.cap < physics.MaxWork && s.Work > w.cap {
w.refuse() // it reached its cap: it would have gone further
}
c := workPerShot + w.walls*workPerWall + int64(len(s.Path))*(workPerPoint+w.pieces*workPerPiece)
if u := workPerShot + w.walls*workPerWall + int64(s.Work)*workPerUnit; u > c {
c = u // a shot that did more than its path shows
}
c += w.setup
w.spent += c
if c > w.most {
w.most = c
}
w.played++
}
// Reset abandons the caller's round under way on hole (an exact id), freeing
// its storage: the next stroke starts a new one from the tee. A finished round
// is not kept (its best is), so a new one needs no Reset. With no round under
// way it does nothing, and says nothing.
func Reset(cur realm, hole string) {
begin()
resetNow(cur, hole)
flush(cur) // (only once it went through: a refusal writes nothing)
}
func resetNow(cur realm, hole string) {
e := mustHole(hole)
player := cur.Previous().Address().String()
if e.roundTree().Remove(player) {
chain.Emit(EventRoundReset, "hole", e.id, "player", player)
}
}
// validShot refuses what would poison a round, and what the game cannot
// send (a step finer than 0.01), and returns the shot as recorded. NaN and infinities pass every comparison, so they are refused by
// name. The power is quantized before it is checked (0.00001 would round to
// 0). The angle is brought into (-360, 360), so a huge one cannot overflow to
// NaN in the physics, and again after rounding (-359.99996 is -0, not -360).
func validShot(angle, power float64) (float64, float64) {
power = q4(power)
if math.IsNaN(angle) || math.IsInf(angle, 0) || !(power > 0 && power <= maxPower) {
panic(errShot)
}
angle = q4(math.Mod(angle, 360))
if angle <= -360 || angle >= 360 {
angle = math.Mod(angle, 360)
}
// finer than the game's own steps: a solver's precision (a knife-edge
// shot), never a player's pull, nor its gnokey command's
if !cents(angle) || !cents(power) {
panic(errFine)
}
return angle, power
}
// cents reports whether x is a whole number of hundredths (as q4 left it).
func cents(x float64) bool { return math.Abs(x*100-math.Round(x*100)) < 1e-6 }
// resolve checks what the physics returned for a stroke: a path a read may
// print, and a ball that is a number. A hole is anyone's data.
func resolve(shot physics.Shot, holed bool) (physics.Shot, bool) {
if len(shot.Path) > maxPath {
panic("golf: the hole returned an oversized path")
}
rest := shot.Rest()
if math.IsNaN(rest.X) || math.IsNaN(rest.Y) || math.IsInf(rest.X, 0) || math.IsInf(rest.Y, 0) {
panic("golf: the hole returned a ball off the board")
}
return shot, holed
}
// back brings a ball that came to rest off the board (a leak in a hole's
// walls) back to from, where the shot started; the stroke counts, with no
// penalty. Every stroke golf plays or replays goes through it.
func back(h *course.Simple, from physics.Vec2, shot physics.Shot, holed bool) physics.Shot {
rest := shot.Rest()
w, hh := h.W, h.H
if holed || len(shot.Path) == 0 || (rest.X >= 0 && rest.X <= float64(w) && rest.Y >= 0 && rest.Y <= float64(hh)) {
return shot
}
// copies: the hole's own slices are the hole's
shot.Path = append(append(make([]physics.Vec2, 0, len(shot.Path)+1), shot.Path...), from)
shot.Air = append(append(make([]bool, 0, len(shot.Air)+1), shot.Air...), false)
shot.Cause = append(append(make([]byte, 0, len(shot.Cause)+1), shot.Cause...), '-')
return shot
}
// stroke resolves one shot into the round and reports whether it was holed.
func stroke(e *entry, h *course.Simple, r *round, player address, angle, power float64, tick int, weather []physics.Zone) (physics.Shot, bool) {
if r.strokes >= maxRoundStrokes {
panic(errStrokeLimit)
}
notOver(r.period) // every stroke, not only the first
// played exactly as it is recorded, so the record replays
angle, power = validShot(angle, power)
from := r.ball()
shot, holed := resolve(h.PreviewWith(from, angle*math.Pi/180, power, r.strokes, tick, weather))
shot = back(h, from, shot, holed)
w, hh := h.W, h.H
e.mark(course.WearIndexOn(shot.Rest(), w, hh)) // where the round's ball is: back's, for a leak
// the decisions, as played: what anyone needs to replay the round
if r.shots != "" {
r.shots += ";"
}
played := ufmt.Sprintf("%.4f,%.4f,%d", angle, power, tick)
r.shots += played
rest := shot.Rest()
r.fx, r.fy, r.bx, r.by = from.X, from.Y, rest.X, rest.Y
r.strokes++
e.plays++
if !holed {
chain.Emit(EventShot, "hole", e.id, "player", player.String(),
"strokes", strconv.Itoa(r.strokes), "mode", modeNames[r.mode], "shot", played)
return shot, false
}
m, p := r.mode, player.String()
// a player's best stays theirs: replaying the hole never erases it, and a
// tie keeps the older round, shots and all
best, _ := e.bests(m).Get(p)
// another's round sent again (nearly: copyOf): kept as this player's
// round and ghost, never ranked; it never replaces a best of their own,
// and a round of their own replaces it, better or not
copied, wasCopy := copyOf(e, p, r.shots), e.copies(m).Has(p)
if was := bestStrokes(best); (was == 0 || r.strokes < was || wasCopy && !copied) && !(copied && was > 0 && !wasCopy) {
if was > 0 && !wasCopy {
e.board(m).Remove(boardKey(best, p))
}
best = bestOf(r)
e.bests(m).Set(p, best)
counted := was // (what their standing holds of this hole: a copy, nothing)
if wasCopy {
counted = 0
}
switch {
case copied:
e.copies(m).Set(p, "1")
chain.Emit(EventCopyNotRanked, "hole", e.id, "player", p, "mode", modeNames[m])
case counts(e, m, p, counted):
e.copies(m).Remove(p)
improve(m, p, e.par, counted, r.strokes)
default:
e.copies(m).Remove(p)
if counted == 0 && e.official && e.next != "" && !e.out.done[m] && p >= e.out.from[m] {
// the drain has yet to reach this first finish: it was never
// counted, so it must not be taken out
e.fresh(m).Set(p, "1")
}
}
}
if named(p) && !e.copies(m).Has(p) {
seat(e, m, p, best)
}
if e.official {
drain(finishBatch) // only the course's finishes pay for the course's drain
}
chain.Emit(EventHoled, "hole", e.id, "player", p,
"strokes", strconv.Itoa(r.strokes), "mode", modeNames[m], "shots", r.shots)
// the round is its best now, or no better than it: not kept (a round of
// this commit's alone was never stored)
e.roundTree().Remove(p)
return shot, true
}
// seat puts a named player where their best puts them: on the hole's board,
// in its record if it tops it, and in the course ranking if they stand in it.
// Every finish does it, improved or not, so a player named since ranks.
func seat(e *entry, m int, p string, best string) {
k := boardKey(best, p)
if !e.board(m).Has(k) {
e.board(m).Set(k, p)
}
// the record is a named player's (a throwaway address could hold it for
// good) and the board's top, so a tie goes to the first to make it
if n, rec := bestStrokes(best), e.rec(m); rec.best == 0 || n < rec.best ||
n == rec.best && address(p) != rec.by && k < boardKey(bestOfPlayer(e, m, rec.by.String()), rec.by.String()) {
if m == pro {
e.proBest, e.proBestBy = n, address(p)
} else {
e.best, e.bestBy = n, address(p)
}
}
if v, ok := totals[m].Get(p); ok && decodeRow(v).holes > 0 {
if rk := rankKey(decodeRow(v)); !ranks[m].Has(rk) {
idle[m].Remove(rk) // a standing parked while unnamed leaves idle as it ranks
ranks[m].Set(rk, p)
}
}
}
// bestOfPlayer is a player's kept best on e in mode m, "" for none.
func bestOfPlayer(e *entry, m int, p string) string {
v, _ := e.bests(m).Get(p)
return v
}
// Claim ranks the caller's bests kept while they had no name: on the boards
// of the course's current holes, in both modes, and in the course ranking.
// It returns how many bests it seated, and refuses a caller with no gno.land
// name. It reads the course's holes only, so it costs the same for everyone.
func Claim(cur realm) int {
begin()
r := claimNow(cur)
flush(cur) // (only once it went through: a refusal writes nothing)
return r
}
func claimNow(cur realm) int {
p := cur.Previous().Address().String()
if !named(p) {
panic("golf: take a gno.land name first: only named players are ranked")
}
n := 0
slots.Iterate("", "", func(_ string, id string) bool {
var e *entry // (decoded only where the player has a best: most holes they have none)
for m := 0; m < modes; m++ {
if best, ok := bestsOf(id, m).Get(p); ok && !copiesOf(id, m).Has(p) {
if e == nil {
e = find(id)
}
seat(e, m, p, best)
n++
}
}
if e != nil {
saveEntry(e) // (its record may be theirs now)
}
return false
})
return n
}
// maxRoundStrokes bounds a round's history (Round shows it); maxPath the path
// a hole may return for a stroke (an honest one: a few hundred points).
const (
maxRoundStrokes = 60
maxPath = 512
)
// q4 rounds to the precision a shot is recorded at.
func q4(x float64) float64 { return math.Round(x*1e4) / 1e4 }
// maxTick bounds the third field of a shot: any timed piece turns in fewer.
const maxTick = 1023
// parseShot reads "angle,power" or "angle,power,tick". The tick is where the
// timed pieces were when the player let go (0 if absent), clamped to
// 0..maxTick.
func parseShot(s string) (float64, float64, int) {
parts := strings.Split(s, ",")
if len(parts) != 2 && len(parts) != 3 {
panic(`golf: a shot is "angle,power" or "angle,power,tick", got: ` + s)
}
angle, err := strconv.ParseFloat(strings.TrimSpace(parts[0]), 64)
if err != nil {
panic("golf: bad angle: " + s)
}
power, err := strconv.ParseFloat(strings.TrimSpace(parts[1]), 64)
if err != nil {
panic("golf: bad power: " + s)
}
tick := 0
if len(parts) == 3 {
tick = clampTick(strings.TrimSpace(parts[2]), s)
}
return angle, power, tick
}
// clampTick reads a tick: an optional sign and digits, clamped to
// 0..maxTick, even past what an int holds.
func clampTick(t, shot string) int {
digits := strings.TrimPrefix(strings.TrimPrefix(t, "-"), "+")
if digits == "" {
panic("golf: bad tick: " + shot)
}
for i := 0; i < len(digits); i++ {
if digits[i] < '0' || digits[i] > '9' {
panic("golf: bad tick: " + shot)
}
}
if strings.HasPrefix(t, "-") {
return 0
}
if digits = strings.TrimLeft(digits, "0"); len(digits) > 4 {
return maxTick
}
n, err := strconv.Atoi("0" + digits)
if err != nil {
panic("golf: bad tick: " + shot) // digits only, at most 4: cannot happen
}
if n > maxTick {
return maxTick
}
return n
}
// roundOf is the player's round under way on e, or a new one from the tee,
// not stored: its commit stores it if it does not finish it.
func roundOf(e *entry, h *course.Simple, player address) *round {
if v, ok := e.roundTree().Get(player.String()); ok {
return decodeRound(v)
}
s := h.Start()
return &round{bx: s.X, by: s.Y}
}
// maxName and maxNote bound a hole's name and a version's note.
const (
maxName = 40
maxNote = 140
)
// cleanName keeps a hole's name to one short line of plain text
// (cleanText), with at least a letter or a digit in it.
func cleanName(n string) string {
s := cleanText(n, maxName)
for _, c := range s {
if unicode.IsLetter(c) || unicode.IsDigit(c) {
return s
}
}
return "Untitled hole"
}
// cleanText keeps an author's text to one line of plain text, at most max
// characters: no control, format (Cf: bidi, zero-width, tags) or nonspacing
// (Mn: stacked accents, variation selectors) characters, no blank-looking
// ones, nothing that ends a markdown table cell or opens a link, a tag, an
// HTML entity, a strikethrough, a mention or an email link.
func cleanText(n string, max int) string {
b := make([]rune, 0, max)
for _, c := range n {
if len(b) >= max {
break
}
switch {
case c < 0x20 || c >= 0x7f && c < 0xa0:
continue
case c == 0xad, c == 0x34f, c == 0x61c, c == 0x115f, c == 0x1160, c == 0x17b4, c == 0x17b5, c == 0x180e,
c >= 0x200b && c <= 0x200f, c >= 0x2028 && c <= 0x202e, c >= 0x2060 && c <= 0x206f,
c == 0x2800, c == 0x3164, c >= 0xfe00 && c <= 0xfe0f, c == 0xfeff, c == 0xffa0,
c >= 0xe0000 && c <= 0xe0fff:
continue
case unicode.In(c, unicode.Mn, unicode.Cf):
// é typed as one (NFC) stays; combining marks (Devanagari, Thai) go
continue
case !unicode.IsPrint(c) && c != ' ':
// what Go would print escaped (\U…), which JSON readers refuse
continue
case strings.ContainsRune("|[]<>`*_#\\&~@", c):
continue
}
b = append(b, c)
}
// no bare link a page might make clickable (": /" keeps the length)
return strings.TrimSpace(strings.ReplaceAll(string(b), "://", ": /"))
}
// maxSkin bounds a skin's length.
const maxSkin = 24
// cleanSkin keeps a skin to what it is meant to be: a short lower-case id.
func cleanSkin(s string) string {
b := make([]byte, 0, maxSkin)
for i := 0; i < len(s) && len(b) < maxSkin; i++ {
c := s[i]
if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == ' ' || c == '-' || c == '_' {
b = append(b, c)
}
}
return string(b)
}
import_v1.gno
package golf
import (
"chain"
"strconv"
"strings"
v1 "gno.land/r/nym-alexiscolin000/gnogolf/golf"
)
// The migration (onyx only: stage.sh leaves this file out of the mainnet
// deploy): v1's course holes and records, read from v1 on chain in the same
// call that writes them, so no one types a value in. Not replayed: v1 already
// replayed each with this same physics. A hole keeps v1's id, so its weather
// and its records fit it.
// EventImported is a v1 record copied in; EventNotImported one left on v1, a
// shot of it finer than v2 takes (validShot): its ghost would not replay here.
const (
EventImported = "Imported"
EventNotImported = "NotImported"
)
// ImportHole copies v1's current version of a course slot, by its id
// ("garden/7/v3"): its data, provenance (by, height, note), plays and wear.
// Only the owner can, into a slot v2 has nothing in yet.
func ImportHole(cur realm, id string) string {
begin()
r := importHoleNow(cur, id)
flush(cur) // (only once it went through: a refusal writes nothing)
return r
}
func importHoleNow(cur realm, id string) string {
if !isOwner(cur.Previous().Address()) {
panic("golf: only the owner can import a course hole")
}
cut := strings.LastIndex(id, "/v")
if cut < 0 || v1.Current(id[:cut]) != id {
panic("golf: " + id + " is not a course slot's current version on v1")
}
slot := id[:cut]
key, ok := slotKeyOf(slot)
if !ok {
panic("golf: " + slot + " is not a course slot")
}
return importHole(id, key, v1.HoleData(id), jobject(v1.Versions(slot), id), jobject(v1.Holes(), id), v1.HoleState(id))
}
// importHole keeps the version id of slot key as v1 lists it: its data (hex),
// its row of Versions (ver), of Holes (row) and its HoleState (state).
func importHole(id, key, hexData, ver, row, state string) string {
cut := strings.LastIndex(id, "/v")
slot := id[:cut]
if slots.Has(key) {
panic("golf: " + slot + " already has a version here")
}
h, data, sum := decodeData(hexData)
if own := h.World + "/" + strconv.Itoa(int(h.Order)); own != slot {
panic("golf: v1's data of " + id + " is " + own) // v1 checked it at publish: cannot happen
}
e := dataEntry(slot, atoi(id[cut+2:]), h, address(jget(ver, "by")), sum, jget(ver, "note"))
e.height = atoi64(jget(ver, "height"))
e.plays = atoi(jget(row, "plays"))
e.official = true
saveEntry(e)
holeData.Set(e.id, data)
slots.Set(key, e.id)
for i, c := range strings.Split(jget(state, "cells"), ",") {
if c != "0" && c != "" && i < wearCells {
e.wear().Set(pad(i, 3), itoa(atoi(c)))
}
}
chain.Emit(EventHolePublished, "hole", e.id, "slot", slot, "sha", sum, "by", e.by.String(), "official", "true")
return e.id
}
// ImportRecord copies a player's v1 best on an imported hole in a mode
// (v1's Ghost: strokes, height, period, shots) and seats it as a finish
// would, onto the hole imported from v1 (the same data: its sha is v1's). Only
// the owner can, as the migration's script runs it: v1 plays on, with no
// near-copy rule, so a round played there later is not one to rank here.
// Idempotent: a record already as good stays; a better v1 one takes its
// place. A record with a shot finer than 0.01 (never one the game sends)
// stays on v1. It answers whether it copied anything.
func ImportRecord(cur realm, hole, mode string, player address) bool {
begin()
r := importRecordNow(cur, hole, mode, player)
flush(cur) // (only once it went through: a refusal writes nothing)
return r
}
func importRecordNow(cur realm, hole, mode string, player address) bool {
if !isOwner(cur.Previous().Address()) {
panic("golf: only the owner can import a record")
}
e, m := mustHole(hole), modeOf(mode)
if !e.official || e.next != "" {
panic("golf: " + hole + " is not a current course hole here")
}
// (Versions lists a slot's newest 100: a version past them would be refused,
// never wrongly let in; v1's slots have a few each)
if jget(jobject(v1.Versions(e.slot), e.id), "sha") != e.sha {
panic("golf: " + hole + " here is not v1's " + hole)
}
// v1's standing of the player, for its tie-break: the page of Players
// that starts just before their key
p, at := player.String(), int64(0)
if row := v1.Players(mode, p[:len(p)-1], 1); jget(row, "player") == p {
at = atoi64(jget(row, "height"))
}
return importRecord(e, m, p, v1.Ghost(hole, mode, player), at)
}
// importRecord copies p's best on e in mode m as v1's Ghost (g) has it; at is
// v1's standing's height (the course ranking's tie-break: the finish that last
// improved it, perhaps on a version since archived), 0 for none.
func importRecord(e *entry, m int, p, g string, at int64) bool {
if g == "null" {
return false
}
strokes, shots := atoi(jget(g, "strokes")), jget(g, "shots")
if strokes < 1 || jget(g, "hole") != e.id {
panic("golf: v1's record of " + e.id + " does not read") // v1 writes them: cannot happen
}
for _, s := range strings.Split(shots, ";") {
if a, pw, _ := parseShot(s); !cents(a) || !cents(pw) {
chain.Emit(EventNotImported, "hole", e.id, "player", p, "mode", modeNames[m], "shot", s)
return false
}
}
best, _ := e.bests(m).Get(p)
was, wasCopy := bestStrokes(best), e.copies(m).Has(p)
if was > 0 && was <= strokes && !wasCopy { // (their own, from v1, replaces a copy played here)
return false
}
if wasCopy { // a copy played here: never counted, never on the board
e.copies(m).Remove(p)
was = 0
} else if was > 0 {
e.board(m).Remove(boardKey(best, p))
}
best = itoa(strokes) + " " + i64(atoi64(jget(g, "height"))) + " " + i64(atoi64(jget(g, "period"))) + " " + shots
e.bests(m).Set(p, best)
r := &row{player: p}
if v, ok := totals[m].Get(p); ok {
r = decodeRow(v)
}
if at == 0 { // (no standing on v1: its finishes, not this call)
at = atoi64(jget(g, "height"))
}
if at < r.height { // (a finish here since: the later one)
at = r.height
}
if was == 0 {
setRow(m, r, r.holes+1, r.strokes+strokes, r.par+e.par, at)
} else {
setRow(m, r, r.holes, r.strokes+strokes-was, r.par, at)
}
if named(p) {
seat(e, m, p, best)
}
saveEntry(e)
chain.Emit(EventImported, "hole", e.id, "player", p, "mode", modeNames[m], "strokes", itoa(strokes))
return true
}
// jobject is a v1 list from the object whose "id" is id on ("" if none):
// jget then reads that object's fields, which every object of the list has.
func jobject(j, id string) string {
i := strings.Index(j, `{"id":`+jstr(id)+`,`)
if i < 0 {
return ""
}
return j[i:]
}
// jget is a field of v1's JSON, as v1 writes it (jstr): a string's value,
// unescaped, or a number's or an array's inside, "" if absent.
func jget(j, k string) string {
i := strings.Index(j, `"`+k+`":`)
if i < 0 {
return ""
}
v := j[i+len(k)+3:]
switch {
case v == "":
return ""
case v[0] == '"':
end := 1
for end < len(v) && v[end] != '"' {
if v[end] == '\\' {
end++
}
end++
}
s, err := strconv.Unquote(v[:end+1])
if err != nil {
panic("golf: v1's " + k + " does not read")
}
return s
case v[0] == '[':
return v[1:strings.Index(v, "]")]
}
return v[:strings.IndexAny(v, ",}]")]
}
kv.gno
package golf
import (
"strconv"
"strings"
"gno.land/r/nym-alexiscolin000/gnogolf/store"
)
// The data lives in store (the realm apart from these rules: a new version of
// the rules takes it on). A view is the rows of one of its collections under a
// prefix, read straight from store and written through this transaction's
// writes: queued as the call goes, read back by Get and Has, and sent to store
// in one batch as the entrypoint returns (flush). Iterate and ReverseIterate
// merge this call's writes into store's rows as they come; Size, index and
// IterateByOffset, a page by place, read store as it stands, so one over rows
// this call has written to panics instead (only the reads take them, which
// write nothing).
type view struct {
c string // the collection
p string // the prefix: "" for the whole collection, else ending with a space, which no id holds
}
var (
queued []string // set/del ops, four strings each, in order
over map[string]string // collection + "\x00" + key -> its value now; "\x00" for removed
dirty map[string]bool // the collections written to
seen map[string]*entry // the versions found in this call that writes: one object each (find)
)
// begin opens a call that writes: every crossing entrypoint that writes
// starts with it and ends with flush.
func begin() { seen = map[string]*entry{} }
const gone = "\x00"
func (v view) end() string {
if v.p == "" {
return ""
}
return v.p[:len(v.p)-1] + "!"
}
func (v view) Get(k string) (string, bool) {
if x, ok := over[v.c+"\x00"+v.p+k]; ok {
return x, x != gone
}
return store.Get(v.c, v.p+k)
}
func (v view) Has(k string) bool {
_, ok := v.Get(k)
return ok
}
func (v view) Set(k, x string) {
queue("set", v.c, v.p+k, x)
}
// Remove drops a row, reporting whether it was there.
func (v view) Remove(k string) bool {
if !v.Has(k) {
return false
}
queue("del", v.c, v.p+k, gone)
return true
}
func queue(op, c, k, x string) {
if over == nil {
over, dirty = map[string]string{}, map[string]bool{}
}
if op == "del" {
queued = append(queued, op, c, k, "")
} else {
queued = append(queued, op, c, k, x)
}
over[c+"\x00"+k] = x
dirty[c] = true
}
// flush sends this call's writes to store, in batches of what store takes in
// one call: every crossing entrypoint that writes ends with it, once it went
// through (begin opens it).
func flush(cur realm) {
for i := 0; i < len(queued); i += 4 * 64 {
j := i + 4*64
if j > len(queued) {
j = len(queued)
}
store.Batch(cross(cur), queued[i:j])
}
queued, over, dirty, seen = nil, nil, nil, nil
}
// clean refuses a walk over rows this call has written to (store has not got them yet)
func (v view) clean() {
if !dirty[v.c] {
return
}
for k := range over {
if strings.HasPrefix(k, v.c+"\x00"+v.p) {
panic("golf: a walk over " + v.c + " " + v.p + "after writing to it in the same call")
}
}
}
// Size is how many rows the view holds.
func (v view) Size() int {
v.clean()
if v.p == "" {
return store.Size(v.c)
}
return store.Index(v.c, v.end()) - store.Index(v.c, v.p)
}
// index is how many of its rows sort before k: k's place, from 0.
func (v view) index(k string) int {
v.clean()
return store.Index(v.c, v.p+k) - store.Index(v.c, v.p)
}
// Iterate is the rows in [start, end) ascending, end "" for no bound; cb
// returning true stops it, and Iterate then reports true.
func (v view) Iterate(start, end string, cb func(key, x string) bool) bool {
return v.walk(start, end, cb, false)
}
// ReverseIterate is the rows in [start, end] descending (store's, as v1's
// bptree: its end is kept), end "" for no bound.
func (v view) ReverseIterate(start, end string, cb func(key, x string) bool) bool {
return v.walk(start, end, cb, true)
}
func (v view) walk(start, end string, cb func(key, x string) bool, back bool) bool {
lo, hi := v.p+start, v.end()
if end != "" {
hi = v.p + end
}
// this call's own writes in the range, in walk order: merged into store's
// rows as they come (a finish on an archived hole, then its drain over it)
in := func(k string) bool { return k >= lo && (hi == "" || k < hi || back && k == hi) }
var mine []string
for ck := range over {
if c, k, _ := strings.Cut(ck, "\x00"); c == v.c && in(k) {
mine = append(mine, k)
}
}
sortKeys(mine, back)
emit := func(k, x string) bool { return cb(k[len(v.p):], x) }
// ours before k (or all of them, k ""), as they stand; true if the walk stopped
flushMine := func(k string) bool {
for len(mine) > 0 && (k == "" || (!back && mine[0] < k) || (back && mine[0] > k)) {
m := mine[0]
mine = mine[1:]
if x := over[v.c+"\x00"+m]; x != gone && emit(m, x) {
return true
}
}
return false
}
// (store's back walk keeps its end, its forward one does not: a back page
// after the first starts with the last one's key again, skipped). Pages
// start small and double: most walks stop after a row or a few.
again, size := "", firstRead
for {
var page string
if back {
page = store.PageBack(v.c, lo, hi, size)
} else {
page = store.Page(v.c, lo, hi, size)
}
n, last := 0, ""
for page != "" {
var k, x string
k, x, page = nextRow(page)
n, last = n+1, k
if k == again {
continue
}
if flushMine(k) {
return true
}
if len(mine) > 0 && mine[0] == k { // ours: as it stands now
mine = mine[1:]
if x = over[v.c+"\x00"+k]; x == gone {
continue
}
}
if emit(k, x) {
return true
}
}
if n < size {
return flushMine("")
}
if back {
hi, again = last, last
} else {
lo = last + "\x00" // (the next key up)
}
if size *= 2; size > maxRead {
size = maxRead
}
}
}
// sortKeys sorts keys ascending, or descending for back (a handful: insertion sort).
func sortKeys(ks []string, back bool) {
for i := 1; i < len(ks); i++ {
for j := i; j > 0 && (!back && ks[j] < ks[j-1] || back && ks[j] > ks[j-1]); j-- {
ks[j], ks[j-1] = ks[j-1], ks[j]
}
}
}
// IterateByOffset is count rows from the offset-th, fewer at the end.
func (v view) IterateByOffset(offset, count int, cb func(key, x string) bool) bool {
v.clean()
from, end := store.Index(v.c, v.p)+offset, v.end()
for count > 0 {
n := count
if n > maxRead {
n = maxRead
}
page, got := store.PageAt(v.c, from, n), 0
for page != "" {
var k, x string
k, x, page = nextRow(page)
if end != "" && k >= end || cb(k[len(v.p):], x) {
return true
}
got++
}
if got < n {
return false
}
from, count = from+got, count-got
}
return false
}
// A page of store: the first a walk asks for, and the largest.
const (
firstRead = 8
maxRead = 300
)
// nextRow is a page's first row (store.Page: each length, ":", itself) and the rest.
func nextRow(page string) (string, string, string) {
k, rest := field(page)
x, rest := field(rest)
return k, x, rest
}
func field(s string) (string, string) {
i := strings.IndexByte(s, ':')
if i < 0 {
panic("golf: store's page unread")
}
n, err := strconv.Atoi(s[:i])
if err != nil || n < 0 || i+1+n > len(s) {
panic("golf: store's page unread")
}
return s[i+1 : i+1+n], s[i+1+n:]
}
owner.gno
package golf
import (
"chain"
"chain/runtime"
"chain/runtime/unsafe"
"strconv"
"strings"
)
// The course's owner, the deployer, set at init: golf's only role. Every
// check is on the immediate caller (cur.Previous().Address()), never the
// signer, so a realm the owner calls cannot act in their name. The role
// passes by Transfer then Accept; Renounce freezes the course for good.
var (
owner address // "" once renounced
pending address // the address a Transfer offered the role to, "" if none
)
// self is golf's own pkgpath, hub its gnoweb path: every link follows from
// them, so the same code serves under any namespace.
var (
self = unsafe.CurrentRealm().PkgPath()
hub = strings.TrimPrefix(self, "gno.land")
officialPrefix = self[:strings.LastIndex(self, "/golf/")+1] // the namespace's realms, as "…/" (these rules are …/golf/v2)
dataRealm = officialPrefix + "store" // where the records are kept (kv.gno)
)
// playURL is the 3D client every page links to (SetPlayURL moves it).
var playURL = "https://gnogolf.xyz/"
// successor is the realm that took this course over, "" until the owner
// names it, once (SetSuccessor).
var successor string
func init() { setUp(unsafe.OriginCaller(), runtime.ChainID()) }
// setUp is init: the deployer owns the course, and community publishing
// starts closed. Only `gno test` (chain "dev") runs it with no signer: the
// owner stays "", which holds no power, and publishing starts open, since
// nobody there could open it.
func setUp(deployer address, chainID string) {
if deployer == "" && chainID != "dev" {
panic("golf: no owner: golf must be deployed by an account")
}
owner, publishing = deployer, deployer == ""
}
// Owner is the course's owner, "" once renounced.
func Owner() address { return owner }
// Pending is the address a Transfer offered the role to, "" if none.
func Pending() address { return pending }
// Successor is the realm that took this course over, "" if none.
func Successor() string { return successor }
// isOwner is the one owner check: a live role, held by the caller.
func isOwner(caller address) bool { return owner != "" && caller == owner }
// Transfer offers the role to another address, which takes it with Accept.
// Offering it to the owner themselves cancels an offer.
func Transfer(cur realm, to address) {
if !isOwner(cur.Previous().Address()) {
panic("golf: only the owner can transfer the course")
}
if !to.IsValid() {
panic("golf: not an address: " + to.String())
}
if to == owner {
pending = ""
chain.Emit(EventOwnershipOfferCancelled, "owner", owner.String())
return
}
pending = to
chain.Emit(EventOwnershipOffered, "owner", owner.String(), "to", to.String())
}
// Accept takes the role a Transfer offered the caller.
func Accept(cur realm) {
caller := cur.Previous().Address()
if owner == "" || pending == "" || caller != pending {
panic("golf: no transfer of the course is offered to you")
}
from := owner
owner, pending = caller, ""
chain.Emit(EventOwnershipTransfer, "from", from.String(), "to", owner.String())
}
// Renounce gives the role up for good: no owner, no offer, and none possible.
func Renounce(cur realm) {
if !isOwner(cur.Previous().Address()) {
panic("golf: only the owner can renounce the course")
}
from := owner
owner, pending = "", ""
chain.Emit(EventOwnershipRenounced, "from", from.String())
}
// maxURL bounds the play link, maxPkgPath a successor's pkgpath.
const (
maxURL = 100
maxPkgPath = 100
)
// SetPlayURL moves the link every page gives to the 3D client. Only the
// owner can. url is https://, at most 100 of letters, digits and "-._~/:%",
// with no query or fragment: a hole's link adds "?cup=…&hole=…" to it.
func SetPlayURL(cur realm, url string) {
if !isOwner(cur.Previous().Address()) {
panic("golf: only the owner can move the play link")
}
if !validURL(url) {
panic("golf: a play link is https:// and up to 100 of a-z, A-Z, 0-9 and -._~/:%")
}
playURL = url
chain.Emit(EventPlayURLSet, "url", url)
}
func validURL(u string) bool {
if len(u) > maxURL || !strings.HasPrefix(u, "https://") || len(u) == len("https://") {
return false
}
for i := 0; i < len(u); i++ {
c := u[i]
if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || strings.IndexByte("-._~/:%", c) >= 0) {
return false
}
}
return true
}
// SetSuccessor names the realm that takes this course over, once and for
// good: a pkgpath under gno.land/r/, not golf itself, with no "", "." or ".."
// segment. Only the owner can. It moves and blocks nothing: the pages and
// Holes say where the course went, and play goes on here. golf does not check
// the realm exists: check the path before sending.
func SetSuccessor(cur realm, pkgpath string) {
if !isOwner(cur.Previous().Address()) {
panic("golf: only the owner can name a successor")
}
if successor != "" {
panic("golf: the successor is already " + successor)
}
if !validPkgPath(pkgpath) || pkgpath == self {
panic("golf: a successor is a realm's pkgpath, gno.land/r/ and up to 100 of a-z, 0-9 and _-/.")
}
successor = pkgpath
chain.Emit(EventSuccessorSet, "successor", pkgpath)
}
// Hide takes a community hole ("<address>/<slug>", every version) off the
// lists (the hub, Holes, the 3D game), for a scam or abuse in its name or
// note; hide=false puts it back. Only the owner can. Its data, rounds and
// page stay, Community still has it, and a new version stays hidden. A hole
// already as asked is left alone, with no event.
func Hide(cur realm, slot string, hide bool) {
begin()
hideNow(cur, slot, hide)
flush(cur) // (only once it went through: a refusal writes nothing)
}
func hideNow(cur realm, slot string, hide bool) {
if !isOwner(cur.Previous().Address()) {
panic("golf: only the owner can hide a hole")
}
v, ok := aliases.Get(slot)
if !ok {
if e := find(slot); e != nil && !e.official {
panic("golf: " + slot + " is a version: hide its hole, " + e.slot)
}
panic("golf: " + slot + " is not a community hole")
}
if hidden.Has(slot) == hide {
return
}
// out of byAuthor, all the lists walk: they never read a hidden hole
e := find(v)
a := e.by.String()
row := a + " " + recentKey(e.height, slot[len(a)+1:])
// (their newest row once this one is in or out, read before this call
// writes to their rows)
was, now := newestRow(a), row[len(a)+1:len(a)+13]
if hide {
now = newestRowBut(a, row)
hidden.Set(slot, "1")
byAuthor.Remove(row)
} else {
if was > now {
now = was
}
hidden.Remove(slot)
byAuthor.Set(row, e.id)
}
moveAuthor(a, was, now)
chain.Emit(EventHoleHidden, "slot", slot, "hidden", strconv.FormatBool(hide))
}
// publishing is whether anyone can publish a community hole (PublishMine):
// closed at deploy (setUp), opened later without a redeploy.
var publishing bool
// Publishing is whether PublishMine is open.
func Publishing() bool { return publishing }
// SetPublishing opens community publishing (PublishMine) or closes it again.
// Only the owner can. Closing stops new holes and versions only: every hole
// published stays playable and listed. Setting it as it is does nothing.
func SetPublishing(cur realm, open bool) {
if !isOwner(cur.Previous().Address()) {
panic("golf: only the owner can open or close publishing")
}
if publishing == open {
return
}
publishing = open
chain.Emit(EventPublishingSet, "open", strconv.FormatBool(open))
}
func validPkgPath(p string) bool {
if len(p) > maxPkgPath || !strings.HasPrefix(p, "gno.land/r/") {
return false
}
for _, seg := range strings.Split(p[len("gno.land/r/"):], "/") {
if seg == "" || seg == "." || seg == ".." {
return false
}
}
for i := 0; i < len(p); i++ {
c := p[i]
if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || strings.IndexByte("_-/.", c) >= 0) {
return false
}
}
return true
}
// The events golf emits, and their attributes. A hole is always "hole", a
// player "player".
const (
EventHolePublished = "HolePublished" // hole, slot, sha, by, official ("true"/"false")
EventHoleRetired = "HoleRetired" // hole, next
EventShot = "Shot" // hole, player, strokes, mode, shot ("angle,power,tick" as recorded)
EventHoled = "Holed" // hole, player, strokes, mode, shots (the round's)
EventCopyNotRanked = "CopyNotRanked" // hole, player, mode: a record sent again, kept, not ranked
EventRoundReset = "RoundReset" // hole, player
EventOwnershipOffered = "OwnershipOffered" // owner, to
EventOwnershipOfferCancelled = "OwnershipOfferCancelled" // owner
EventOwnershipTransfer = "OwnershipTransfer" // from, to
EventOwnershipRenounced = "OwnershipRenounced" // from
EventPlayURLSet = "PlayURLSet" // url
EventSuccessorSet = "SuccessorSet" // successor
EventHoleHidden = "HoleHidden" // slot, hidden ("true"/"false")
EventPublishingSet = "PublishingSet" // open ("true"/"false")
)
render.gno
package golf
import (
"encoding/hex"
"math"
"strconv"
"strings"
"time"
"gno.land/p/nym-alexiscolin000/gnogolf/course"
"gno.land/p/nym-alexiscolin000/gnogolf/physics"
"gno.land/p/nt/ufmt/v0"
"gno.land/r/nym-alexiscolin000/gnogolf/store"
)
// wearRunes draw a cell's wear: none, then up to wearLight, wearWorn and
// wearGroove balls come to rest there, and past.
const (
wearRunes = " :;x%" // pristine grass blank: a shot's dots stand out on it
wearLight = 2
wearWorn = 6
wearGroove = 14
)
// maxTunnels is how many tunnels the board numbers, 1 to 9.
const maxTunnels = 9
const (
markWall = '#'
markPost = '0'
markCup = 'U' // not O: in gnoweb's font O and the post's 0 look alike
markTee = '*'
)
// Render is the game as text: gnoweb draws the board and submits the shot.
//
// Paths: "" the hub; "<world>" a cup's holes; "<address>" the holes an
// address published; "<hole>" a hole's page, "<hole>/<address>" the same
// with that player's ball, "<hole>/data" a version's provenance and data.
// <hole> is a version's id or an alias. A query string ("?…") is ignored.
func Render(path string) string {
if i := strings.IndexByte(path, '?'); i >= 0 {
path = path[:i]
}
if path == "" {
return renderHub()
}
if e := lookup(path); e != nil {
return renderHole(e, e.hole(), "")
}
// the segments of a hole's path, which gnoweb links one by one
if course.IsWorld(path) {
return renderCup(path)
}
if address(path).IsValid() {
return renderAuthor(address(path))
}
// the id has slashes of its own, so what trails it is looked at last
if i := strings.LastIndex(path, "/"); i >= 0 {
head, tail := path[:i], path[i+1:]
if e := lookup(head); e != nil {
if address(tail).IsValid() {
return renderHole(e, e.hole(), address(tail))
}
if tail == "data" {
return renderData(e)
}
}
}
return noSuch(path)
}
// noSuch is the page for a path that is no hole, cup or address.
func noSuch(path string) string {
what := "That page"
if c := cleanText(path, maxName); c != "" {
what = "`" + c + "`"
}
return "# No such hole\n\n> [!WARNING]\n> " + what + " is not a hole here. " + md("See every hole", hub) + ".\n"
}
// lookup is readHole that answers nil for no hole.
func lookup(id string) *entry {
if e := find(id); e != nil {
return e
}
return find(current(id))
}
// playLink is the 3D client's link to this hole: a current course hole by cup
// and order, any other by its id, which no newer version can take.
func playLink(e *entry) string {
if !e.official || e.next != "" {
return playURL + "?hole=" + e.id
}
return playURL + "?cup=" + e.world + "&hole=" + strconv.Itoa(int(e.order))
}
// cupName is how a world is called on the page.
func cupName(w string) string {
if r := worldRank(w); r < len(worlds) {
return worlds[r].name
}
if w == "" {
return "Holes"
}
return strings.ToUpper(w[:1]) + w[1:]
}
// who is a player as a link to their gno.land profile.
func who(addr string) string { return md(short(addr), "/u/"+addr) }
func renderHub() string {
var sb strings.Builder
sb.WriteString("# Gnogolf — mini-golf on-chain\n\n" + moved() +
"The course is data its owner published, anyone can add holes of their own, and the chain computes every shot: nobody can fake a score.\n\n" +
"> [!TIP] How to play\n" +
"> **In 3D:** " + md("open the game", playURL) + ". Aim with a free preview, then record your round in a transaction (a long one in a few).\n>\n" +
"> **Here, one shot at a time:** open a hole, fill its Launch form (an angle and a power) and sign it with your gno.land wallet (" + md("Adena", "https://adena.app") + "), then add `/<your address>` to the hole's URL to see your ball.\n>\n" +
"> Only players with a gno.land name are ranked.\n\n")
// what to race first: a few records worth beating, not the podium
beat := ""
for m := 0; m < modes; m++ {
if rows := featuredRows(m); rows != "" {
beat += "**" + modeTitles[m] + "**\n\n" + rows + "\n"
}
}
if beat != "" {
sb.WriteString("## Records to beat today\n\nA few players worth racing today, each for a reason (never the ranking's top three; drawn again each day). Race their ghosts in the game: their best rounds, replayed stroke for stroke.\n\n" + beat)
}
var archived, others []*entry
type cup struct {
world string
holes, par int
top *entry
}
var cups []*cup
for _, e := range listed() {
switch {
case e.official && e.next == "":
// one column per cup: nothing here calls a hole
if len(cups) == 0 || cups[len(cups)-1].world != e.world {
cups = append(cups, &cup{world: e.world})
}
c := cups[len(cups)-1]
c.holes++
c.par += e.par
if e.plays > 0 && (c.top == nil || e.plays > c.top.plays) {
c.top = e
}
case e.official:
archived = append(archived, e)
default:
others = append(others, e)
}
}
if len(cups) == 0 {
sb.WriteString("_No course hole yet._\n\n")
} else {
// a column a cup, so they all fit one row (gnoweb's columns wrap past four)
head, rule, sizes, tops := "| ", "|---", "| holes · par", "| most played"
for _, c := range cups {
top := "—"
if c.top != nil {
top = c.top.name
}
head += " | " + md(cupName(c.world), hub+":"+c.world)
rule += "|---"
sizes += " | " + strconv.Itoa(c.holes) + " · " + strconv.Itoa(c.par)
tops += " | " + top
}
sb.WriteString(head + " |\n" + rule + "|\n" + sizes + " |\n" + tops + " |\n\n")
}
sb.WriteString("## Community holes\n\nAnyone can publish a hole of their own with PublishMine while the owner keeps publishing open. These are not part of the course: they have no cup and do not count in its ranking.\n\n")
switch {
case len(others) > 0:
case publishing:
sb.WriteString("_None yet. Publish yours with " + md("PublishMine", hub+"$help&func=PublishMine") + "._\n")
default:
sb.WriteString("_None yet: publishing opens with the game's hole builder._\n")
}
names := map[string]string{} // the record holders' names, read once each (bestCell)
if len(others) > 0 {
sb.WriteString("| hole | by | par | best | shots played |\n|---|---|---|---|---|\n")
for _, e := range others {
sb.WriteString("| " + md(e.name, hub+":"+e.slot) + " | " + md(short(e.by.String()), hub+":"+e.by.String()) + " | " + strconv.Itoa(e.par) + " | " + bestCell(e, names) + " | " +
strconv.Itoa(e.plays) + " |\n")
}
}
if len(archived) > 0 {
sb.WriteString("\n## Archived course holes\n\nA newer version took each one's place in its cup. They can still be played, and keep their records, but no longer count in the course-wide ranking. Every version of a slot is on its data page.\n\n" +
"| hole | version | par | best | shots played | now |\n|---|---|---|---|---|---|\n")
for _, e := range archived {
sb.WriteString("| " + md(e.name, hub+":"+e.id) + " | " + e.id + " | " + strconv.Itoa(e.par) + " | " + bestCell(e, names) + " | " +
strconv.Itoa(e.plays) + " | " + md(e.next, hub+":"+e.next) + " |\n")
}
}
sb.WriteString("\n")
sb.WriteString("## The boards\n\nEach named player's best finish on each current hole of the course, added up: most holes first, then the best score against par (each hole's strokes less its par, added up: a hole at par counts the same whatever its par). " +
"Assisted rounds (played with the 3D game's aim line) and pro rounds (without it, on the player's word; every round played on this page is pro) are ranked apart.\n\n")
for m := 0; m < modes; m++ {
sb.WriteString("### " + modeTitles[m] + "\n\n")
rows, i := "", 0
eachRanked(m, func(r *row, name string) {
i++
rows += "| " + strconv.Itoa(i) + " | " + md("@"+name, "/u/"+name) + " | " + strconv.Itoa(r.holes) + " | " + vsPar(r.strokes-r.par) + " |\n"
})
if rows == "" {
sb.WriteString("_Nobody has finished a hole of the course yet._\n\n")
continue
}
sb.WriteString("| rank | player | holes | vs par |\n|---|---|---|---|\n" + rows + "\n")
}
sb.WriteString(fairPlay())
sb.WriteString(noAdmin())
return sb.String()
}
// fairPlay says what keeps a score honest, and where the rules stand.
func fairPlay() string {
return "## Fair play\n\n" +
"- **The chain plays every shot.** A round is its shots (an angle, a power, the moment of the release), replayed here: nobody can send a score.\n" +
"- **Shots go in the game's steps of 0.01**, angle and power: a finer one (a program's precision) is refused.\n" +
"- **A record sent again is not ranked.** A round that sends one of the hole's top records again, shot for shot within a hair, is kept (the player's round and ghost) but ranks nowhere.\n" +
"- **The site's boards hide suspected bots**, and say why; the chain and this page keep every record.\n" +
"- **The rules and the data are apart:** the records are kept in " + md("Gnogolf's data", strings.TrimPrefix(dataRealm, "gno.land")) + ", which takes writes from these rules alone. New rules take over three days after their code is on chain, so anyone can read them first; nothing is reset.\n\n"
}
// moved is the banner every page shows once these rules no longer save (the
// data's writer is another, or saves are paused) or the course has moved.
func moved() string {
switch w := store.Writer(); {
case w == "":
return "> [!WARNING] Saves are paused\n> " + md("Gnogolf's data", strings.TrimPrefix(dataRealm, "gno.land")) + " takes no save until these rules are resumed or new ones named: rounds here are refused, every record can still be read.\n\n"
case w != self:
return "> [!NOTE] New rules play this course\n> " + md(w, strings.TrimPrefix(w, "gno.land")) + " keeps its records now: play there; a round sent here is refused.\n\n"
case successor != "":
return "> [!NOTE] This course has moved\n> Its successor is " + md(successor, strings.TrimPrefix(successor, "gno.land")) +
". Everything here still plays and keeps its records.\n\n"
}
return ""
}
// renderCup is a cup's page: its current holes, in order.
func renderCup(world string) string {
var sb strings.Builder
sb.WriteString("# " + cupName(world) + "\n\n" + moved())
k := slotKey(world, 0)
k = k[:len(k)-3] // the world's slots are the keys "<rank><world>/…"
n, names := 0, map[string]string{}
slots.Iterate(k, k[:len(k)-1]+"0", func(_, v string) bool {
e := find(v)
if n == 0 {
sb.WriteString("| # | hole | par | best | shots played |\n|---|---|---|---|---|\n")
}
n++
sb.WriteString("| " + strconv.Itoa(int(e.order)) + " | " + md(e.name, hub+":"+e.slot) + " | " + strconv.Itoa(e.par) + " | " +
bestCell(e, names) + " | " + strconv.Itoa(e.plays) + " |\n")
return n >= maxListed
})
if n == 0 {
return noSuch(world)
}
return sb.String() + "\n" + md("Every cup", hub) + "\n"
}
// renderAuthor is the holes an address published, as their current versions.
func renderAuthor(a address) string {
var sb strings.Builder
sb.WriteString("# Community holes by " + who(a.String()) + "\n\n" + moved())
n, names := 0, map[string]string{}
aliases.Iterate(a.String()+"/", a.String()+"0", func(k, v string) bool {
if hidden.Has(k) {
return false // off the lists, as Hide says: this page is one
}
e := find(v)
if n == 0 {
sb.WriteString("| hole | versions | par | best | shots played | data |\n|---|---|---|---|---|---|\n")
}
n++
sb.WriteString("| " + md(e.name, hub+":"+e.slot) + " | " + strconv.Itoa(e.version) + " | " + strconv.Itoa(e.par) + " | " +
bestCell(e, names) + " | " + strconv.Itoa(e.plays) + " | " + source(e) + " |\n")
return n >= pageMax
})
if n == 0 {
sb.WriteString("_This address has published no community hole._\n")
}
return sb.String() + "\n" + md("Every hole", hub) + "\n"
}
// bestCell is a hole's records, assisted then pro, for a table cell. names
// caches holders: r/sys/users is read once a player, not once a record.
func bestCell(e *entry, names map[string]string) string {
best := ""
for m := 0; m < modes; m++ {
if r := e.rec(m); r.best > 0 {
if best != "" {
best += " · "
}
by := r.by.String()
name, ok := names[by]
if !ok {
name = byName(by)
names[by] = name
}
best += ufmt.Sprintf("%s %d, %s", modeNames[m], r.best, name)
}
}
if best == "" {
return "—"
}
return best
}
// weatherNote is the hole's weather now (f, the forecast of this period) and
// how long it lasts, on a hole's own page.
func weatherNote(f course.Forecast) string {
left := PeriodSeconds - time.Now().Unix()%PeriodSeconds
what := "Clear"
switch f.Kind {
case course.Wind:
a, _ := aim(physics.Vec2{}, f.Wind)
what = ufmt.Sprintf("Wind toward **%.0f°**: it pushes every roll that way", a)
case course.Rain:
what = "Rain: the green runs fast, and puddles slow the ball"
case course.Fog:
what = "Fog: it hides nothing here, and does not touch the ball"
case course.Storm:
what = "Storm: rain, puddles and wind"
case course.Snow:
what = "Snow: the green runs slow"
}
// ufmt has no width: the seconds padded by hand
return ufmt.Sprintf("> [!NOTE] Weather now\n> %s — for %d min %s s more. A round keeps the weather it started in, and can be played on until the next weather is over: after that it must be Reset.\n\n",
what, left/60, pad(int(left%60), 2))
}
// noAdmin states who can change what, the owner's own powers included.
func noAdmin() string {
holder := who(owner.String())
if owner == "" {
holder = "nobody: the role was given up, and the course is frozen for good"
}
return "\n> [!INFO]- Who can change what\n" +
"> Anyone can play (Launch, PlayRound, PlayRoundAt, PlayRoundPro), Reset their own round, " +
"publish holes of their own (PublishMine) while publishing is open, and settle the ranking sooner (Drain). These rules never edit or delete a round, a record, a best, a standing or a published version, " +
"and nobody can change this realm's code. Its rules can be replaced, its records kept: the owner of " + md("Gnogolf's data", strings.TrimPrefix(dataRealm, "gno.land")) + " may propose new rules, which take over three days after their code is on chain (anyone can read it first: what they do to the records is in it), and may stop every save at once for a bug (the reads go on) and start these same rules again; that page says which rules are in force. Every hole is data, played by golf's own physics: no hole runs code of its own. Check it yourself: " + md("the source", hub+"$source") + ".\n>\n" +
"> One party holds a real power: the course's owner, now " + holder + ". The owner publishes the course holes and their new versions (Publish). " +
"A new version takes its slot: the old one is archived, still playable, its records kept, but its bests leave the course-wide ranking, which the new version starts afresh. " +
"So the owner shapes the course, and through it the ranking, and a stolen owner key could archive every slot, for good. " +
"A version identical to the current one is refused, but a replacement can still be unplayable: a hole can be replaced, never taken down. " +
"When a version is published picks its id, and its id seeds its weather. " +
"The owner also sets where the pages link the 3D game (SetPlayURL), and can name, once and for good, a successor this course has moved to (SetSuccessor): a banner, which blocks nothing. " +
"Whoever holds `" + strings.TrimPrefix(officialPrefix, "gno.land/") + "` can deploy lookalike realms under it. " +
"The owner can take a community hole off the lists (Hide: a scam or abuse in its name or note), and put it back; it stays playable, its page and data kept. " +
"The owner opens community publishing and can close it again (SetPublishing): closed, nobody adds a hole or a version, and every hole published plays on. " +
"The owner cannot edit or remove a version, change a community hole, the weather, the physics or this code, " +
"and can only hand the role on (Transfer, then Accept) or give it up for good (Renounce).\n"
}
// source links a hole's data page: read it before trusting it with a round.
func source(e *entry) string { return md("data", hub+":"+e.id+"/data") }
func md(label, href string) string { return "[" + label + "](" + href + ")" }
// vsPar is a score against par: "even", "+3", "-2" (ufmt has no %+d).
func vsPar(d int) string {
switch {
case d > 0:
return "+" + strconv.Itoa(d)
case d < 0:
return strconv.Itoa(d)
}
return "even"
}
// flatRolls is how far a shot rolls on flat grass (a tee shot's Kick, the
// usual friction).
const flatRolls = "On flat grass a power of 10 rolls about 40, a 5 about 15."
func renderHole(e *entry, h *course.Simple, focus address) string {
f := h.Field()
var mine *round // the focused player's round, looked up once
if v, ok := e.roundTree().Get(focus.String()); ok {
mine = decodeRound(v)
}
stroke := 0
if mine != nil {
stroke = mine.strokes
}
// a timed hole is drawn as it stands for the focused player's next stroke
ws, ps := h.Extras(stroke)
f = course.WithZones(course.WithExtras(f, ws, ps), h.ExtraZones(stroke))
// a community hole's world is its author's word: only the course has cups
where := md(cupName(e.world), hub+":"+e.world)
if !e.official {
where = "Community hole by " + md(short(e.by.String()), hub+":"+e.by.String())
}
s := ufmt.Sprintf("# %s\n\n**Par %d** · %s · %s\n\n", e.name, e.par, where, md("Play in 3D", playLink(e))) + moved()
if e.next != "" {
next := e.next
if n := find(e.next); n != nil {
next = n.name
}
s += "> [!NOTE]\n> Archived: " + md(next, hub+":"+e.next) + " (" + e.next + ") took its place. It can still be played, and your best here still shows on this page"
if e.official {
s += ", but it no longer counts in the course-wide ranking"
}
s += ".\n\n"
}
if focus != "" {
s += roundSummary(e, focus, mine)
}
// the page's forecast, drawn once: its note, and the last shot of a round
// played in it
now := weatherOf(e, h, Period())
s += weatherNote(now)
if h.Varies() {
if focus == "" {
s += "_This hole changes with every stroke. It is drawn for a first shot; add `/<your address>` to the URL to see it for your next one._\n\n"
} else {
s += ufmt.Sprintf("_This hole changes with every stroke. Drawn for %s's stroke %d._\n\n", short(focus.String()), stroke+1)
}
}
if boardWork(f, h) > maxBoardWork {
s += "_This hole is too detailed to draw here: " + md("play it in 3D", playLink(e)) + "._\n\n"
} else {
b := board(e, h, f, mine, now)
leg, walls := legend(f)
s += "```\n" + b + "```\n\n"
s += key(b, walls) + leg + "\n\n"
}
s += "## Play\n\n"
// the one number a text player cannot read off the board: where the cup is
from, who := h.Start(), "the tee"
if mine != nil {
from, who = mine.ball(), "the ball"
}
a, d := aim(from, h.Cup())
s += ufmt.Sprintf("From %s the cup is **%.0f°** away, **%.1f** units in a straight line (0° = right, 90° = down). %s\n\n", who, a, d, flatRolls)
s += "_Rounds played here have no aim preview, so they go on the **Pro** board. A shot needs a gno.land wallet (Adena); the 3D game previews shots for free._\n\n"
s += "<gno-form exec=\"Launch\">\n"
s += ufmt.Sprintf("<gno-input name=\"hole\" value=\"%s\" readonly=\"true\" description=\"this hole\" required=\"true\" />\n", e.id)
s += "<gno-input name=\"angle\" description=\"angle in degrees: 0 = right, 90 = down\" placeholder=\"e.g. 12.5\" required=\"true\" />\n"
s += "<gno-input name=\"power\" description=\"power: above 0, up to 10\" placeholder=\"e.g. 6\" required=\"true\" />\n"
s += "</gno-form>\n\n"
s += ufmt.Sprintf("_After your shot, see your ball at `%s:%s/<your address>`._\n\n", hub, e.id)
s += "A round under way you would rather start afresh? Put your ball back on the tee (a holed round needs nothing: the next shot starts a new one):\n\n"
s += "<gno-form exec=\"Reset\">\n"
s += ufmt.Sprintf("<gno-input name=\"hole\" value=\"%s\" readonly=\"true\" description=\"this hole\" required=\"true\" />\n", e.id)
s += "</gno-form>\n\n"
if e.official && e.next == "" {
s += "Took a gno.land name after saving rounds? " + md("Claim", hub+"$help&func=Claim") + " puts them on the boards now.\n\n"
}
s += ufmt.Sprintf("## Best rounds\n\n%d rounds under way here; finished: %d assisted, %d pro.", e.roundTree().Size(), e.bests(assisted).Size(), e.bests(pro).Size())
if e.board(assisted).Size()+e.board(pro).Size() == 0 {
s += " No named player has finished it yet.\n\n"
} else {
s += " The named players' bests: each keeps its round, which the 3D game replays as a ghost to race.\n\n"
}
for m := 0; m < modes; m++ {
rows := ""
n, walked := 0, 0
e.board(m).Iterate("", "", func(k, v string) bool {
walked++
p := v
if name := nameOf(p); name != "" { // a name deleted since is skipped
n++
rows += ufmt.Sprintf("| %d | [@%s](%s:%s/%s) | %d | %s |\n", n, name, hub, e.id, p, boardStrokes(k), race(e, p, "race"))
}
return n >= topSize || walked >= maxWalked
})
if rows != "" {
s += "### " + modeTitles[m] + "\n\n| # | player | score | ghost |\n|---|---|---|---|\n" + rows + "\n"
}
}
return s + "\n_This hole is " + source(e) + " — read it before you trust it with a round._\n"
}
// roundSummary is how a player stands on the hole: their round under way, if
// any, and their best in each mode, with where it puts them on the hole's
// board, or why nowhere. A holed round is not kept: its best is.
func roundSummary(e *entry, p address, r *round) string {
who := short(p.String())
name := nameOf(p.String())
if name != "" {
who = "@" + name
}
s := ""
if r != nil {
over := ""
if r.period < Period()-1 {
over = " Its weather is over: Reset (below) before the next shot."
}
s = ufmt.Sprintf("> %s's round: %s so far, not holed yet.%s\n>\n> %s\n>\n", who, count(r.strokes, "stroke"), over, shotsOf(r.shots))
}
for m := 0; m < modes; m++ {
v := bestOfPlayer(e, m, p.String())
if v == "" {
continue
}
best := bestStrokes(v)
s += ufmt.Sprintf("> **%s's best here: %d** (par %d, %s), %s. ", who, best, e.par, vsPar(best-e.par), modeNames[m])
b := e.board(m)
switch k := boardKey(v, p.String()); {
case b.Has(k):
s += ufmt.Sprintf("**#%d of %d** on the %s board. %s.\n>\n", b.index(k)+1, b.Size(), modeNames[m], race(e, p.String(), "Race this ghost in 3D"))
case e.copies(m).Has(p.String()):
s += "Not ranked: it is a record of the board sent again (Fair play, on the course's page).\n>\n"
case name == "":
s += "Not on the board: only players with a gno.land name are ranked.\n>\n"
case e.official && e.next == "":
s += "Not on the board yet: the name came after this round. Claim (below, or the game's \"Rank them\") ranks it now.\n>\n"
default: // Claim seats the course's current holes only
s += "Not on the board yet: the name came after this round. Finish it again: a named player's every finish puts their best on the board.\n>\n"
}
_, _, shots := bestFields(v)
s += "> " + shotsOf(shots) + "\n>\n"
}
if s == "" {
return "> [!NOTE]\n> " + who + " has no round on this hole yet.\n\n"
}
return "> [!NOTE]\n" + strings.TrimSuffix(s, ">\n") + "\n"
}
// shotsOf is a round's shots for a page: golf's own "%.4f,%.4f,%d", digits
// and punctuation only.
func shotsOf(shots string) string {
return "Shots: `" + strings.ReplaceAll(shots, ";", "; ") + "`"
}
// renderData is a data version's page: where it came from, its versions,
// and its data, which is all the hole there is.
func renderData(e *entry) string {
pkgs := strings.Replace(officialPrefix, "gno.land/r/", "/p/", 1) // the course's packages, as "/p/<ns>/"
s := "# " + e.name + ": its data\n\n**" + e.id + "**, version " + strconv.Itoa(e.version) + " of " + md(e.slot, hub+":"+e.slot) +
", published at height " + strconv.FormatInt(e.height, 10) + " by " + who(e.by.String()) + ". " + md("Play it", hub+":"+e.id) + ".\n\n"
if e.note != "" {
s += "> " + e.note + "\n\n"
}
if e.next != "" {
s += "_Archived: " + md(e.next, hub+":"+e.next) + " took its place._\n\n"
}
s += "## Versions\n\n| version | height | by | sha256 | note |\n|---|---|---|---|---|\n"
now := find(current(e.slot))
for n := firstVersion(now); n <= now.version; n++ {
v := find(e.slot + "/v" + strconv.Itoa(n))
if v == nil {
continue // (one before this course's first here: imported from v1, with v1's number)
}
s += "| " + md(v.id, hub+":"+v.id+"/data") + " | " + strconv.FormatInt(v.height, 10) + " | " + who(v.by.String()) + " | `" + v.sha[:16] + "…` | " + v.note + " |\n"
}
data, _ := holeData.Get(e.id)
s += "\n## The data\n\n" + strconv.Itoa(len(data)) + " bytes of GG1, sha256 `" + e.sha + "`. " +
"Every call decodes it with " + md("course", pkgs+"course$source") + " and plays it with " + md("physics", pkgs+"physics$source") +
"; " + md("golf", hub+"$source") + " checked it once, when it was published. HoleData gives it back as hex:\n\n"
return s + "```\n" + hex.EncodeToString([]byte(data)) + "\n```\n"
}
// board rasterises the hole: wear, then zones, posts, walls, cup, and mine,
// the focused player's round (nil for none); now is this period's forecast.
func board(e *entry, h *course.Simple, f *physics.Field, mine *round, now course.Forecast) string {
bw, bh := h.W, h.H
g := make([][]rune, bh)
wear := e.wearGrid()
for y := 0; y < bh; y++ {
row := make([]rune, bw)
for x := 0; x < bw; x++ {
row[x] = wearRune(wear, x*course.WearW/bw, y*course.WearH/bh)
}
g[y] = row
}
// the walls, traced once: drawn, and what the flood fill stops at
wall := make([][]rune, bh)
for y := range wall {
wall[y] = make([]rune, bw)
}
for _, w := range f.Walls {
trace(wall, w.Seg, mark(w.Mark, markWall))
}
// the last flight first, so the pieces drawn over it stay visible
if mine != nil {
fc := now
if mine.period != now.Period { // a round begun in the period before
fc = weatherOf(e, h, mine.period)
}
for _, p := range lastShot(h, mine, fc).Path {
put(g, p, '·')
}
}
tunnel := 0
for i := range f.Zones {
z := &f.Zones[i]
m := mark(z.Mark, '?')
if z.Kind == physics.Tunnel && tunnel < maxTunnels {
// a tunnel's mouth and exit share a digit
tunnel++
m = rune('0' + tunnel)
}
drawZone(g, z, m)
}
for y := range wall {
for x, c := range wall[y] {
if c != 0 {
g[y][x] = c
}
}
}
for _, p := range f.Posts {
fill(g, p.Circle, mark(p.Mark, markPost))
put(g, p.C, mark(p.Mark, markPost)) // a small post still shows
}
tunnel = 0
for _, z := range f.Zones {
if z.Kind == physics.Tunnel && tunnel < maxTunnels {
tunnel++
put(g, z.Vec, rune('0'+tunnel))
}
}
put(g, h.Start(), markTee)
put(g, h.Cup(), markCup)
// ground no ball can reach is not green: blank it, as the 3D client does
blankUnreachable(g, wall, f, h.Start(), h.Cup())
// only your own ball: everyone's at once would bury the board
if mine != nil {
put(g, mine.ball(), '@')
}
var sb strings.Builder
for _, row := range g {
sb.WriteString(string(row) + "\n")
}
return sb.String()
}
// drawZone marks the cells whose centre the zone holds, as the physics sees it
// (physics.Zone.Contains): a polygon's row from where the centre line crosses
// its edges, an ellipse's as the run the physics' test finds from its middle.
func drawZone(g [][]rune, z *physics.Zone, m rune) {
bh := len(g)
if bh == 0 {
return
}
bw := len(g[0])
x0, x1 := boxCells(z.Min.X, z.Max.X, bw)
y0, y1 := boxCells(z.Min.Y, z.Max.Y, bh)
if x0 >= x1 {
return
}
poly := len(z.Poly) >= 3
var flip []bool
if poly {
flip = make([]bool, x1+1)
}
for y := y0; y < y1; y++ {
row, py := g[y], float64(y)+0.5
switch {
case poly:
// even-odd, as inPoly: a sweep from the right flips at each
// crossing's cell. No sort: a row costs its edges and cells.
for x := x0; x <= x1; x++ {
flip[x] = false
}
a := z.Poly[len(z.Poly)-1]
for _, b := range z.Poly { // the edge from a to b
if (a.Y > py) != (b.Y > py) {
c := cellAt(a.X+(py-a.Y)*(b.X-a.X)/(b.Y-a.Y), x0, x1)
flip[c] = !flip[c]
}
a = b
}
in := false
for x := x1 - 1; x >= x0; x-- {
if flip[x+1] {
in = !in
}
if in != z.Outside {
row[x] = m
}
}
case z.Round:
hx, hy := (z.Max.X-z.Min.X)/2, (z.Max.Y-z.Min.Y)/2
dy := (py - z.Min.Y - hy) / hy
in := func(x int) bool {
dx := (float64(x) + 0.5 - z.Min.X - hx) / hx
return dx*dx+dy*dy < 1
}
// the cells nearest the middle: if neither is in, none is
mid := int(math.Floor(z.Min.X + hx - 0.5))
c := -1
for _, x := range [2]int{mid, mid + 1} {
if x < x0 {
x = x0
}
if x >= x1 {
x = x1 - 1
}
if c < 0 && in(x) {
c = x
}
}
if c >= 0 {
from := firstCell(x0, c, in)
to := firstCell(c, x1, func(x int) bool { return !in(x) })
fillRow(row, from, to, m)
}
default:
fillRow(row, x0, x1, m)
}
}
}
// boxCells is the cells from int(lo) to int(hi), within 0..n, whose centre
// lies in [lo, hi): the cells the physics' box test takes.
func boxCells(lo, hi float64, n int) (int, int) {
a, b := span(lo, hi, n)
if a >= b {
return a, a
}
a = firstCell(a, b, func(x int) bool { return float64(x)+0.5 >= lo })
return a, firstCell(a, b, func(x int) bool { return !(float64(x)+0.5 < hi) })
}
// cellAt is the first cell in [lo, hi), lo >= 0, whose centre is at or past c
// (!(x+0.5 < c), as the physics compares), hi if none: ceil(c-0.5).
func cellAt(c float64, lo, hi int) int {
if !(float64(lo)+0.5 < c) { // NaN too, as a search would find
return lo
}
if c >= float64(hi) {
return hi
}
x := int(c) // c > 0.5: its floor
if float64(x)+0.5 < c {
x++
}
if x > hi {
x = hi
}
return x
}
// firstCell is the first x in [lo, hi) where ok turns true, hi if it never
// does: ok is false up to some x, and true from there.
func firstCell(lo, hi int, ok func(x int) bool) int {
for lo < hi {
mid := (lo + hi) / 2
if ok(mid) {
hi = mid
} else {
lo = mid + 1
}
}
return lo
}
func fillRow(row []rune, from, to int, m rune) {
for x := from; x < to; x++ {
row[x] = m
}
}
// span is the cells from int(lo) to int(hi), within 0..n.
func span(lo, hi float64, n int) (int, int) {
a, b := int(lo), int(hi)
if a < 0 {
a = 0
}
if b > n {
b = n
}
return a, b
}
// maxBoardWork bounds a board's drawing, in thousands of gas (boardWork):
// past it the page does not draw, far under the 3e9 a query may use.
const maxBoardWork = 600000
// boardWork estimates board's cost in thousands of gas, with measured weights:
// a board cell; a cell and a polygon edge per row of a zone's box (every edge
// counted as crossing, as a zigzag's do); a step along a wall; a cell of a
// post's box.
func boardWork(f *physics.Field, h *course.Simple) int {
bw, bh := h.W, h.H
n := 32 * bw * bh
for i := range f.Zones {
z := &f.Zones[i]
x0, x1 := span(z.Min.X, z.Max.X, bw)
y0, y1 := span(z.Min.Y, z.Max.Y, bh)
if x1 > x0 && y1 > y0 {
n += (y1 - y0) * (5*(x1-x0) + 16*len(z.Poly))
}
}
for i := range f.Walls {
n += 10 * (int(f.Walls[i].Seg.B.Sub(f.Walls[i].Seg.A).Len()*2) + 2)
}
for i := range f.Posts {
d := int(2*f.Posts[i].R) + 2
n += 20 * d * d
}
return n
}
// key names the board's fixed marks it shows (tee and cup always), with the
// skins of the walls drawn `#`.
func key(b, walls string) string {
// what the board shows, read once: a big board is thousands of runes
var on [128]bool
shot := false // '·', the one mark past ASCII
for _, c := range b {
if c < 128 {
on[c] = true
} else if c == '·' {
shot = true
}
}
s := "`*` tee · `U` cup"
for _, k := range []struct{ marks, what string }{
{"@", "the ball"}, {"·", "its last shot"}, {"#", "wall"},
{":;x%", "wear (worn by past shots)"},
} {
shown := k.marks == "·" && shot
for i := 0; i < len(k.marks) && k.marks[i] < 128; i++ {
shown = shown || on[k.marks[i]]
}
if shown {
s += " · `" + k.marks + "` " + k.what
if k.marks == "#" && walls != "" {
s += " (" + walls + ")"
}
}
}
// tunnels are numbered from 1: name the digits the board has
digits := ""
for c := '1'; c <= '9'; c++ {
if on[c] {
digits += string(c)
}
}
switch len(digits) {
case 0:
case 1:
s += " · `" + digits + "` a tunnel and its exit"
default:
s += " · `" + digits + "` tunnels, each with its exit"
}
return s
}
// legend names the pieces the hole gave a skin (a slope with the way it
// falls), and the skins of its `#` walls.
func legend(f *physics.Field) (string, string) {
s, walls := "", ""
add := func(m rune, def rune, skin string) {
if skin == "" {
return
}
r := mark(m, def)
if r == markWall {
// the key's own wall: name its skins there, once each
if !strings.Contains(", "+walls+", ", ", "+skin+", ") {
if walls != "" {
walls += ", "
}
walls += skin
}
return
}
// once each: a mark with two meanings (two slopes' ways) says both
item := ufmt.Sprintf(" · `%s` %s", string(r), skin)
if strings.Contains(s+" · ", item+" · ") {
return
}
s += item
}
for _, z := range f.Zones {
if z.Kind == physics.Tunnel {
continue // numbered on the board
}
name := cleanSkin(z.Skin)
if name == "" || name == z.Kind.String() {
name = z.Kind.String()
} else {
name += " (" + z.Kind.String() + ")"
}
// a slope says which way it takes the ball, in the shot's degrees (the wind's, the cup's)
if z.Kind == physics.Slope && (z.Vec.X != 0 || z.Vec.Y != 0) {
a, _ := aim(physics.Vec2{}, z.Vec)
if z.Air {
name += ufmt.Sprintf(", pushes toward %.0f°", a)
} else {
name += ufmt.Sprintf(", falls toward %.0f°", a)
}
}
add(z.Mark, '?', name)
}
for _, p := range f.Posts {
add(p.Mark, markPost, cleanSkin(p.Skin))
}
for _, w := range f.Walls {
add(w.Mark, markWall, cleanSkin(w.Skin))
}
return s, walls
}
// mark is what a piece shows on the text board. Marks come from the hole's
// author, and the board sits in a code block: only a printable ASCII
// character that cannot close the block or start markdown is kept.
func mark(m, def rune) rune {
if m <= ' ' || m > '~' || strings.ContainsRune("`[]()<>*_#|\\!@oU0123456789", m) {
return def
}
return m
}
// wearRune takes wear-cell coordinates.
func wearRune(wear []int, x, y int) rune {
i := y*course.WearW + x
if i < 0 || i >= len(wear) {
return rune(wearRunes[0])
}
switch v := wear[i]; {
case v == 0:
return rune(wearRunes[0])
case v <= wearLight:
return rune(wearRunes[1])
case v <= wearWorn:
return rune(wearRunes[2])
case v <= wearGroove:
return rune(wearRunes[3])
default:
return rune(wearRunes[4])
}
}
// trace draws a wall as points every half unit, put inlined: a board has
// thousands.
func trace(g [][]rune, s physics.Segment, c rune) {
bh := len(g)
if bh == 0 {
return
}
bw := len(g[0])
d := s.B.Sub(s.A)
steps := int(d.Len()*2) + 1
for i := 0; i <= steps; i++ {
k := float64(i) / float64(steps)
x, y := int(s.A.X+d.X*k), int(s.A.Y+d.Y*k)
if x == bw {
x = bw - 1
}
if y == bh {
y = bh - 1
}
if x >= 0 && x < bw && y >= 0 && y < bh {
g[y][x] = c
}
}
}
// fill draws a post: the cells whose centre is within its radius. LenCmp
// skips Len's software square root.
func fill(g [][]rune, c physics.Circle, r rune) {
bh := len(g)
if bh == 0 {
return
}
bw := len(g[0])
for y := int(c.C.Y - c.R); y <= int(c.C.Y+c.R); y++ {
gy := y
if gy == bh {
gy = bh - 1
}
if gy < 0 || gy >= bh {
continue
}
for x := int(c.C.X - c.R); x <= int(c.C.X+c.R); x++ {
gx := x
if gx == bw {
gx = bw - 1
}
if gx >= 0 && gx < bw && (physics.Vec2{X: float64(x) + 0.5, Y: float64(y) + 0.5}).Sub(c.C).LenCmp(c.R) <= 0 {
g[gy][gx] = r
}
}
}
}
func put(g [][]rune, p physics.Vec2, c rune) {
x, y := int(p.X), int(p.Y)
bh := len(g)
if bh == 0 {
return
}
bw := len(g[0])
// the far edge belongs to the last cell, not off the board
if x == bw {
x = bw - 1
}
if y == bh {
y = bh - 1
}
if x < 0 || x >= bw || y < 0 || y >= bh {
return
}
g[y][x] = c
}
func short(addr string) string {
if len(addr) <= 12 {
return addr
}
return addr[:8] + "…" + addr[len(addr)-4:]
}
// blankUnreachable clears the cells no ball can reach: a flood fill from the
// tee, the cup and where tunnels and hazards put the ball, stopped by walls.
func blankUnreachable(g, wall [][]rune, f *physics.Field, seeds ...physics.Vec2) {
bh := len(g)
if bh == 0 {
return
}
bw := len(g[0])
for _, z := range f.Zones {
if z.Kind == physics.Tunnel || z.Kind == physics.Hazard {
seeds = append(seeds, z.Vec)
}
}
// a row's run at a time, no closure: a board has thousands of cells
seen := make([][]bool, bh)
for y := range seen {
seen[y] = make([]bool, bw)
}
var stack []int // y*bw + x: a cell whose run is yet to fill
for _, p := range seeds {
if x, y := int(p.X), int(p.Y); x >= 0 && y >= 0 && x < bw && y < bh {
stack = append(stack, y*bw+x)
}
}
for len(stack) > 0 {
c := stack[len(stack)-1]
stack = stack[:len(stack)-1]
x, y := c%bw, c/bw
s, w := seen[y], wall[y]
if s[x] || w[x] != 0 {
continue
}
l, r := x, x+1
for l > 0 && !s[l-1] && w[l-1] == 0 {
l--
}
for r < bw && !s[r] && w[r] == 0 {
r++
}
for i := l; i < r; i++ {
s[i] = true
}
// the rows above and below: a cell for each open run under this one
for ny := y - 1; ny <= y+1; ny += 2 {
if ny < 0 || ny >= bh {
continue
}
ns, nw := seen[ny], wall[ny]
open := false
for i := l; i < r; i++ {
o := !ns[i] && nw[i] == 0
if o && !open {
stack = append(stack, ny*bw+i)
}
open = o
}
}
}
for y := 0; y < bh; y++ {
for x := 0; x < bw; x++ {
if !seen[y][x] && wall[y][x] == 0 {
g[y][x] = ' '
}
}
}
}
// race is the 3D game's dare link (by=): this hole against p's best's ghost.
func race(e *entry, p, label string) string { return md(label, playLink(e)+"&by="+p) }
// byName is a player by their gno.land name when they have one.
func byName(addr string) string {
if n := nameOf(addr); n != "" {
return md("@"+n, "/u/"+n)
}
return who(addr)
}
// count is n things, said right for one.
func count(n int, what string) string {
if n == 1 {
return "1 " + what
}
return strconv.Itoa(n) + " " + what + "s"
}
state.gno
package golf
import (
"math"
"strconv"
"strings"
"gno.land/p/nym-alexiscolin000/gnogolf/course"
"gno.land/p/nym-alexiscolin000/gnogolf/physics"
"gno.land/p/nt/ufmt/v0"
)
// HoleState is the hole as JSON for a client: geometry, skins (names the
// client looks up), weather and wear, all it needs to draw the hole and aim.
// hole is a version's id or an alias; "hole" in the answer is always the
// version's id, the one to write with, with its "slot" and "v", and an
// archived one's "next".
//
// A shot's path (Round, Simulate*) is the flight the chain computed: replay
// it, never re-simulate. Points far apart are a tunnel: do not interpolate.
func HoleState(hole string) string {
e := readHole(hole)
h := e.hole()
f := h.Field()
var sb strings.Builder
sb.WriteString("{" + versionJSON +
`,"hole":` + jstr(e.id) +
`,"name":` + jstr(e.name) +
`,"official":` + strconv.FormatBool(e.official))
if e.slot != "" {
sb.WriteString(`,"slot":` + jstr(e.slot) + `,"v":` + strconv.Itoa(e.version))
}
if e.next != "" {
sb.WriteString(`,"next":` + jstr(e.next))
}
p := Period()
sb.WriteString(boardJSON(h) +
`,"par":` + strconv.Itoa(e.par) +
`,"world":` + jstr(e.world) + `,"order":` + jnum(e.order) +
`,"timed":` + strconv.FormatBool(h.Varies()) +
`,"period":` + strconv.FormatInt(p, 10) +
`,"weather":` + forecastJSON("", weatherOf(e, h, p)) +
`,"start":` + jvec(h.Start()) +
`,"cup":` + jvec(h.Cup()) +
`,"cupR":` + jnum(h.CupRadius) + `,"ballR":` + jnum(f.Radius))
// the hole's work before the weather (newWork): the client splits a save
// and sets its gas by it
w := newWork(h, nil)
sb.WriteString(ufmt.Sprintf(`,"work":{"walls":%d,"pieces":%d,"setup":%d}`, w.walls, w.pieces, w.setup))
sb.WriteString(`,"walls":` + wallsJSON(f.Walls) + `,"posts":` + postsJSON(f.Posts))
sb.WriteString(`,"zones":` + zonesJSON(f.Zones, true))
sb.WriteString(`,"wear":{"w":` + strconv.Itoa(course.WearW) + `,"h":` + strconv.Itoa(course.WearH) + `,"cells":[`)
for i, c := range e.wearGrid() {
sb.WriteString(sep(i))
sb.WriteString(strconv.Itoa(c))
}
sb.WriteString("]}}")
return sb.String()
}
// roundJSON is one player's round: ball rounded, rest exact (for SimulateFrom)
// and the last stroke replayed: rounds store shots, not paths.
func roundJSON(e *entry, h *course.Simple, player string, r *round) string {
var sb strings.Builder
sb.WriteString("{" + versionJSON + `,"player":` + jstr(player) +
`,"ball":` + jvec(r.ball()) + `,"rest":` + jexact(r.ball()) +
ufmt.Sprintf(`,"strokes":%d,"period":%d`, r.strokes, r.period) +
`,"mode":` + jstr(modeNames[r.mode]) +
`,"shots":` + jstr(r.shots))
shot := lastShot(h, r, weatherOf(e, h, r.period))
sb.WriteString(`,"path":[` + pathJSON(shot.Path) + `],"air":` + jstr(airOf(shot)) + `,"cause":` + jstr(string(shot.Cause)))
sb.WriteString("}")
return sb.String()
}
// lastShot replays a round's last stroke, read-only, with its stroke number,
// tick and weather (fc, its period's forecast): the same flight, less the
// wear. Empty before a first one.
func lastShot(h *course.Simple, r *round, fc course.Forecast) physics.Shot {
if r.strokes == 0 || r.shots == "" {
return physics.Shot{}
}
s := r.shots
if i := strings.LastIndex(s, ";"); i >= 0 {
s = s[i+1:]
}
angle, power, tick := parseShot(s)
from := physics.Vec2{X: r.fx, Y: r.fy}
shot, holed := h.PreviewWith(from, angle*math.Pi/180, power, r.strokes-1, tick, fc.Zones)
return back(h, from, shot, holed)
}
// pathJSON is a shot's path points, comma separated.
func pathJSON(ps []physics.Vec2) string {
var sb strings.Builder
for i, p := range ps {
sb.WriteString(sep(i))
sb.WriteString(jvec(p))
}
return sb.String()
}
// airOf is a shot's air flags, one character per path point: "0001100…".
func airOf(s physics.Shot) string {
b := make([]byte, len(s.Path))
for i := range b {
b[i] = '0'
if i < len(s.Air) && s.Air[i] {
b[i] = '1'
}
}
return string(b)
}
// Round is one player's round under way on a hole with its last stroke's
// path, or null if they have none: never started, holed (its best is kept:
// Ghost) or Reset. It costs one stroke of gas.
func Round(hole string, player address) string {
e := readHole(hole)
v, ok := e.roundTree().Get(player.String())
if !ok {
return "null"
}
return roundJSON(e, e.hole(), player.String(), decodeRound(v))
}
func sep(i int) string {
if i == 0 {
return ""
}
return ","
}
// jnum is a number with 3 decimals, the bytes of ufmt's "%.3f" at a fraction
// of its gas. NaN and Inf, not JSON, print 0. Below 1e12, v*1000 is within
// 1.2e-4 of the exact decimal, so its integer part decides the rounding
// unless the fraction is within 1e-3 of a half: those, and huge numbers, go
// to strconv, which is exact.
func jnum(v float64) string {
if math.IsNaN(v) || math.IsInf(v, 0) {
return "0"
}
a := v * 1000
if a < 0 {
a = -a
}
if a >= 1e12 {
return strconv.FormatFloat(v, 'f', 3, 64)
}
k := int64(a)
switch f := a - float64(k); {
case f > 0.499 && f < 0.501:
return strconv.FormatFloat(v, 'f', 3, 64)
case f > 0.5:
k++
}
frac := k % 1000
s := strconv.FormatInt(k/1000, 10) + "."
if frac < 100 {
s += "0"
}
if frac < 10 {
s += "0"
}
s += strconv.FormatInt(frac, 10)
if math.Signbit(v) { // "%.3f" keeps the sign of a negative that rounds to 0
s = "-" + s
}
return s
}
// jexact is a point exactly, as the shortest decimals that read back as the
// same float64: what a client hands back to SimulateFrom.
func jexact(v physics.Vec2) string {
return "[" + strconv.FormatFloat(v.X, 'g', -1, 64) + "," + strconv.FormatFloat(v.Y, 'g', -1, 64) + "]"
}
// versionJSON opens every object a read returns.
const versionJSON = `"version":1`
func jvec(v physics.Vec2) string { return "[" + jnum(v.X) + "," + jnum(v.Y) + "]" }
// jstr quotes an author's string so it cannot break out of its JSON. Every
// byte below 0x20 is escaped: one in one hole's name would make Holes()
// invalid JSON for every client. Most strings need nothing escaped: they go
// out as they are, without the copy (a byte at a time costs gas).
func jstr(s string) string {
for i := 0; i < len(s); i++ {
if c := s[i]; c == '"' || c == '\\' || c < 0x20 {
return jescape(s)
}
}
return `"` + s + `"`
}
// jid quotes a version's id or alias, which golf builds of nothing to escape
// (a world and order, or an address and a slug: validSlug): not scanned.
func jid(s string) string { return `"` + s + `"` }
func jescape(s string) string {
const hex = "0123456789abcdef"
b := make([]byte, 0, len(s)+2)
b = append(b, '"')
for i := 0; i < len(s); i++ {
c := s[i]
switch {
case c == '"' || c == '\\':
b = append(b, '\\', c)
case c < 0x20:
b = append(b, '\\', 'u', '0', '0', hex[c>>4], hex[c&15])
default:
b = append(b, c)
}
}
return string(append(b, '"'))
}
// Holes lists at most maxListed holes for a client's menu, as listed orders
// them: the course's current holes, its latest archived versions, then
// community holes, newest first, perAuthor an address, none hidden (the rest
// are in Community). official marks the course's holes, the only ones in a
// cup and the course ranking; next is the version that replaced a hole, slot
// its alias, play the 3D client's link, successor the realm that took the
// course over ("" if none). It decodes nothing.
func Holes() string {
var sb strings.Builder
sb.WriteString("{" + versionJSON + `,"play":` + jstr(playURL) + `,"successor":` + jstr(successor) + `,"holes":[`)
for i, e := range listed() {
sb.WriteString(sep(i) + holeRow(e))
}
sb.WriteString("]}")
return sb.String()
}
// holeRow is one hole as Holes and Community list it.
func holeRow(e *entry) string {
s := `{"id":` + jid(e.id) +
`,"name":` + jstr(e.name) +
`,"official":` + strconv.FormatBool(e.official) +
`,"plays":` + strconv.Itoa(e.plays) +
`,"best":` + strconv.Itoa(e.rec(assisted).best) +
`,"proBest":` + strconv.Itoa(e.rec(pro).best) +
`,"par":` + strconv.Itoa(e.par) +
`,"world":` + jstr(e.world) + `,"order":` + jnum(e.order) + `,"next":` + jid(e.next)
if e.slot != "" {
s += `,"slot":` + jid(e.slot)
}
return s + "}"
}
// Community is a page of every community hole, every version of each, by id:
// all that Holes leaves out. It is paged like Records.
func Community(after string, limit int) string {
var sb strings.Builder
sb.WriteString("{" + versionJSON + `,"rows":[`)
next := page(community.Iterate, after, limit, func(i int, _ string, v string) {
sb.WriteString(sep(i) + holeRow(decodeEntry(v)))
})
sb.WriteString(`],"next":` + jstr(next) + "}")
return sb.String()
}
// perAuthor is the most published holes of one address Holes and the hub
// list: one address publishing a hundred cannot push everyone else's out.
const perAuthor = 3
// listed is the holes in list order, at most maxListed: every current course
// hole in course order; then, if minCommunity places stay free, up to
// maxArchived archived course versions, latest archived first; then, in the
// room left, the newest shown community holes (current, not hidden) among
// each author's perAuthor newest, by block height then alias, last first. An
// author fills perAuthor rows at most, however many holes they publish.
//
// It reads about what it lists: authors latest first, perAuthor keys each,
// until an author's latest is older than every row kept (room+1 authors at
// most). Hidden holes have no byAuthor row: nothing hidden is walked.
func listed() []*entry {
list := make([]*entry, 0, maxListed)
full := func() bool { return len(list) >= maxListed }
slots.Iterate("", "", func(_, v string) bool {
list = append(list, find(v))
return full()
})
if room := maxListed - minCommunity - len(list); room > 0 {
if room > maxArchived {
room = maxArchived
}
archived.ReverseIterate("", "", func(_, v string) bool {
list = append(list, find(v))
room--
return room == 0
})
}
room := maxListed - len(list)
if room <= 0 {
return list
}
// the newest room of the rows seen, newest first, by recentKey(height,
// alias): an author walked later has only older holes than the one
// before's latest, so a row past room never comes back
type seen struct{ key, id string }
top := make([]seen, 0, room)
byAuthor.ReverseIterate("", authorRows, func(ak, _ string) bool {
if len(top) == room && ak < top[room-1].key {
return true // their latest, and so all theirs, are older than all kept
}
a := ak[13:] + " "
n := 0
byAuthor.ReverseIterate(a, a[:len(a)-1]+"!", func(k, v string) bool {
// "<address> <height> <slug>" -> "<height> <address>/<slug>"
key := k[len(a):len(a)+12] + " " + a[:len(a)-1] + "/" + k[len(a)+13:]
i := len(top)
for i > 0 && top[i-1].key < key {
i--
}
if i < room {
if len(top) < room {
top = append(top, seen{})
}
copy(top[i+1:], top[i:len(top)-1])
top[i] = seen{key, v}
}
n++
return n == perAuthor
})
return false
})
for _, s := range top {
list = append(list, find(s.id))
}
return list
}
// authorRows is past the last of byAuthor's author rows ("<height> <address>")
// and before its first hole ("g1…"): no key is ":".
const authorRows = ":"
// maxArchived bounds the archived course versions Holes and the hub list,
// and minCommunity is the room they leave for community holes.
const (
maxArchived = 20
minCommunity = 20
)
// SimulateFrom previews one shot, read-only: from an exact ball (a "rest"
// answered before), shot "angle,power,tick", its stroke number (0 is the
// first; timed and pulse holes change with it) and any period not ahead.
// It is what PlayRoundAt would play, for one shot's gas. As a vm/qeval query
// it needs no transaction or wallet: a client animates a shot the instant it
// is released.
func SimulateFrom(hole string, ballX, ballY float64, shot string, stroke int, period int64) string {
notAhead(period)
validStroke(stroke)
angle, power, tick := parseShot(shot)
e := readHole(hole)
h := e.hole()
ball := onBoard(h, ballX, ballY)
angle, power = validShot(angle, power)
sh, holed := resolve(h.PreviewWith(ball, angle*math.Pi/180, power, stroke, tick, weatherOf(e, h, period).Zones))
sh = back(h, ball, sh, holed)
return "{" + versionJSON + `,"holed":` + strconv.FormatBool(holed) + `,"bounces":` + strconv.Itoa(sh.Bounces) + shotJSON(sh) + "}"
}
func validStroke(stroke int) {
if stroke < 0 || stroke >= maxRoundStrokes {
panic("golf: a stroke is between 0 and 59")
}
}
// onBoard refuses a ball off the board (or NaN): no round leaves one there.
func onBoard(h *course.Simple, x, y float64) physics.Vec2 {
w, hh := h.W, h.H
if !(x >= 0 && x <= float64(w) && y >= 0 && y <= float64(hh)) {
panic("golf: the ball must be on the board")
}
return physics.Vec2{X: x, Y: y}
}
// shotJSON is a shot's path, air, cause, work (Shot.Work, which a client adds
// up as a commit does) and exact resting point.
func shotJSON(shot physics.Shot) string {
return `,"path":[` + pathJSON(shot.Path) + `],"air":` + jstr(airOf(shot)) + `,"cause":` + jstr(string(shot.Cause)) +
`,"work":` + strconv.Itoa(shot.Work) + `,"rest":` + jexact(shot.Rest())
}
// SimulateRound replays a shot list from the tee, read-only, and returns its
// last shot and stroke count: what PlayRound would record, refusals included.
// Continue from an exact "rest" (SimulateFrom): rounded points are for drawing.
func SimulateRound(hole string, shots string) string {
return simulateRound(hole, nil, 0, shots, Period())
}
// SimulateRoundAt is SimulateRound in a period's weather, the current one or
// the one before, as a round's first stroke: it agrees with PlayRoundAt.
func SimulateRoundAt(hole string, shots string, period int64) string {
playablePeriod(period)
return simulateRound(hole, nil, 0, shots, period)
}
// SimulateRoundIn is SimulateRound in any period gone by, to check a recorded
// round as the chain played it. Weather still to come is refused.
func SimulateRoundIn(hole string, shots string, period int64) string {
notAhead(period)
return simulateRound(hole, nil, 0, shots, period)
}
// SimulateCommit previews the next PlayRoundAt (or PlayRoundPro) commit,
// read-only: shots from the exact ball ("rest") at stroke number stroke (0 is
// the first) in period's weather. It refuses what that commit would (too much
// work, too many strokes, a weather over), so a client checks every commit
// before it signs any. JSON as SimulateRound; strokes counts after the commit.
func SimulateCommit(hole string, ballX, ballY float64, stroke int, shots string, period int64) string {
if stroke == 0 {
playablePeriod(period)
} else {
notAhead(period)
notOver(period)
}
validStroke(stroke)
return simulateRound(hole, &physics.Vec2{X: ballX, Y: ballY}, stroke, shots, period)
}
// simulateRound is the SimulateRound* and SimulateCommit replay: from nil is
// the tee, and the first shot is stroke number strokes.
func simulateRound(hole string, from *physics.Vec2, strokes int, shots string, period int64) string {
e := readHole(hole)
h := e.hole()
ball := h.Start()
if from != nil {
ball = onBoard(h, from.X, from.Y)
}
fc := weatherOf(e, h, period)
weather := fc.Zones
list := shotList(shots)
w := newWork(h, weather)
w.fixed = fixedGas(e, fc)
holed := false
var last physics.Shot
for _, s := range list {
if strokes >= maxRoundStrokes {
panic(errStrokeLimit)
}
w.next(h)
angle, power, tick := parseShot(s)
angle, power = validShot(angle, power)
last, holed = resolve(h.PreviewWith(ball, angle*math.Pi/180, power, strokes, tick, weather))
last = back(h, ball, last, holed)
w.add(last)
ball = last.Rest()
strokes++
if holed {
break
}
}
return "{" + versionJSON + `,"holed":` + strconv.FormatBool(holed) + `,"strokes":` + strconv.Itoa(strokes) +
`,"bounces":` + strconv.Itoa(last.Bounces) + `,"period":` + strconv.FormatInt(period, 10) +
shotJSON(last) + "}"
}
func boardJSON(h *course.Simple) string {
w, hh := h.W, h.H
return `,"board":{"w":` + strconv.Itoa(w) + `,"h":` + strconv.Itoa(hh) + "}"
}
func wallsJSON(ws []physics.Wall) string {
var sb strings.Builder
sb.WriteString("[")
for i := range ws {
w := &ws[i]
sb.WriteString(sep(i) + "{" + `"a":` + jvec(w.Seg.A) + `,"b":` + jvec(w.Seg.B) +
`,"skin":` + jstr(cleanSkin(w.Skin)) + timingJSON(w.Every, w.On, w.Phase) + "}")
}
sb.WriteString("]")
return sb.String()
}
func postsJSON(ps []physics.Post) string {
var sb strings.Builder
sb.WriteString("[")
for i := range ps {
p := &ps[i]
sb.WriteString(sep(i) + "{" + `"c":` + jvec(p.C) + `,"r":` + jnum(p.R) +
`,"skin":` + jstr(cleanSkin(p.Skin)) + "}")
}
sb.WriteString("]")
return sb.String()
}
// zonesJSON is a hole's zones, or the weather's (forecastJSON: no flags).
// With flags, "air" and "capped" are printed only when true.
func zonesJSON(zs []physics.Zone, flags bool) string {
var sb strings.Builder
sb.WriteString("[")
for i := range zs {
z := &zs[i]
sb.WriteString(sep(i) + "{" + `"kind":` + jstr(z.Kind.String()) +
`,"min":` + jvec(z.Min) + `,"max":` + jvec(z.Max) +
`,"vec":` + jvec(z.Vec) + `,"scale":` + jnum(z.Scale) +
`,"round":` + strconv.FormatBool(z.Round) + polyJSON(z) + timingJSON(z.Every, z.On, z.Phase))
if flags && z.Air {
sb.WriteString(`,"air":true`)
}
if flags && z.Capped {
sb.WriteString(`,"capped":true`)
}
sb.WriteString(`,"skin":` + jstr(cleanSkin(z.Skin)) + "}")
}
sb.WriteString("]")
return sb.String()
}
// timingJSON is a timed piece's clock (a tram, a storm's gusts); nothing for
// an untimed one.
func timingJSON(every, on, phase int) string {
if every <= 0 {
return ""
}
return `,"every":` + strconv.Itoa(every) + `,"on":` + strconv.Itoa(on) + `,"phase":` + strconv.Itoa(phase)
}
// polyJSON is a polygon zone's outline, and whether it is the outside of it;
// nothing for the usual rectangle or ellipse.
func polyJSON(z *physics.Zone) string {
if len(z.Poly) < 3 {
return ""
}
return `,"poly":[` + pathJSON(z.Poly) + `],"outside":` + strconv.FormatBool(z.Outside)
}
// Extras is what a timed hole adds at one stroke of a round (0 is the first),
// to draw over HoleState's field. Empty for other holes.
func Extras(hole string, stroke int) string {
h := readHole(hole).hole()
if stroke < 0 {
return "{" + versionJSON + `,"walls":[],"posts":[],"zones":[]}`
}
ws, ps := h.Extras(stroke)
return "{" + versionJSON + `,"walls":` + wallsJSON(ws) + `,"posts":` + postsJSON(ps) + `,"zones":` + zonesJSON(h.ExtraZones(stroke), true) + "}"
}
// Leaderboard is a mode's course-wide top ten ("assisted" or "pro"): named
// players' bests on the current course holes, summed; most holes, then the
// best score against par (strokes - par), then the first there. Its cost does
// not grow with players.
func Leaderboard(mode string) string {
m := modeOf(mode)
var sb strings.Builder
// holes: the course's current ones, the only ones that count
sb.WriteString("{" + versionJSON + `,"mode":` + jstr(modeNames[m]) + `,"holes":` + strconv.Itoa(slots.Size()) + `,"rows":[`)
n := 0
eachRanked(m, func(r *row, name string) {
sb.WriteString(sep(n) + standingRow(r.player, name, r))
n++
})
sb.WriteString("]}")
return sb.String()
}
// eachRanked walks a mode's top ten: the first named players of its ranking,
// with their names. A name deleted since is skipped, not shown.
func eachRanked(m int, fn func(r *row, name string)) {
n, walked := 0, 0
ranks[m].Iterate("", "", func(_, v string) bool {
walked++ // skipped names count: the walk stays bounded
p := v
if name := nameOf(p); name != "" {
fn(rowOf(m, p), name)
n++
}
return n >= topSize || walked >= maxWalked
})
}
// maxWalked is the most rows a top ten walks, skipped names included.
const maxWalked = 4 * topSize
// strokesRow and standingRow are a player's best or standing row; name is ""
// on the reads that resolve no names. A standing's par is its holes' pars
// summed: strokes - par is its score against par.
func strokesRow(p, name string, strokes int) string {
return `{"player":` + jstr(p) + nameField(name) + `,"strokes":` + strconv.Itoa(strokes) + "}"
}
func standingRow(p, name string, r *row) string {
return `{"player":` + jstr(p) + nameField(name) + standingFields(r) + "}"
}
// standingFields is a standing's numbers: holes, strokes and par.
func standingFields(r *row) string {
return `,"holes":` + strconv.Itoa(r.holes) + `,"strokes":` + strconv.Itoa(r.strokes) + `,"par":` + strconv.Itoa(r.par)
}
func nameField(name string) string {
if name == "" {
return ""
}
return `,"name":` + jstr(name)
}
// Rank is a player's place in a mode's course ranking, with their standing:
// "rank" 1 is the top, out of "of"; 0 if unnamed or no current course hole
// finished. A name deleted since keeps its place until its next change, so a
// rank may be that many too low.
func Rank(mode string, player address) string {
m := modeOf(mode)
p := player.String()
rank, r := 0, &row{}
if v, ok := totals[m].Get(p); ok {
r = decodeRow(v)
if key := rankKey(r); ranks[m].Has(key) {
rank = ranks[m].index(key) + 1
}
}
return "{" + versionJSON + `,"mode":` + jstr(modeNames[m]) + `,"player":` + jstr(p) +
`,"rank":` + strconv.Itoa(rank) + `,"of":` + strconv.Itoa(ranks[m].Size()) + standingFields(r) + "}"
}
// CourseLeaderboard is a page of a mode's course ranking, paged like
// HoleLeaderboard. holes is the course's current holes, players how many the
// ranking holds.
func CourseLeaderboard(mode string, offset, limit int) string {
m := modeOf(mode)
limit = clampLimit(limit)
size := ranks[m].Size()
if offset < 0 {
offset = 0
}
if offset > size {
offset = size // and offset+limit cannot overflow
}
var sb strings.Builder
sb.WriteString("{" + versionJSON + `,"mode":` + jstr(modeNames[m]) + `,"holes":` + strconv.Itoa(slots.Size()) +
`,"players":` + strconv.Itoa(size) + `,"offset":` + strconv.Itoa(offset) + `,"rows":[`)
n := 0
ranks[m].IterateByOffset(offset, limit, func(_, v string) bool {
p := v
name := nameOf(p)
if name == "" {
return false // a name deleted since
}
sb.WriteString(sep(n) + standingRow(p, name, rowOf(m, p)))
n++
return false
})
next := 0
if offset+limit < size {
next = offset + limit
}
sb.WriteString(`],"next":` + strconv.Itoa(next) + "}")
return sb.String()
}
// Ghost is a player's best round on a hole in a mode, named or not, with its
// height (the first to a score ranks first), period and shots, or null: what a
// duel races. It replays in its own weather (SimulateRoundIn for the first
// stroke, then SimulateFrom from each rest).
func Ghost(hole, mode string, player address) string {
e, m := readHole(hole), modeOf(mode)
v := bestOfPlayer(e, m, player.String())
if v == "" {
return "null"
}
strokes := bestStrokes(v)
at, period, shots := bestFields(v)
return "{" + versionJSON + `,"hole":` + jstr(e.id) + `,"mode":` + jstr(modeNames[m]) + `,"player":` + jstr(player.String()) +
`,"height":` + strconv.FormatInt(at, 10) + `,"strokes":` + strconv.Itoa(strokes) + `,"period":` + strconv.FormatInt(period, 10) + `,"shots":` + jstr(shots) + "}"
}
// HoleRank is a player's place on a hole's board in a mode, with their best,
// as Rank: 0 if unnamed or no finish there.
func HoleRank(hole, mode string, player address) string {
e, m := readHole(hole), modeOf(mode)
p := player.String()
v := bestOfPlayer(e, m, p)
rank, strokes := 0, bestStrokes(v)
if strokes > 0 {
if k := boardKey(v, p); e.board(m).Has(k) {
rank = e.board(m).index(k) + 1
}
}
return "{" + versionJSON + `,"hole":` + jstr(e.id) + `,"mode":` + jstr(modeNames[m]) + `,"player":` + jstr(p) +
`,"rank":` + strconv.Itoa(rank) + `,"of":` + strconv.Itoa(e.board(m).Size()) + `,"strokes":` + strconv.Itoa(strokes) + "}"
}
// maxListed bounds Holes() and the hub: anyone can add a hole.
const maxListed = 120
// HoleLeaderboard is a page of a hole's board in a mode: named players' bests,
// fewest strokes then first there, from rank offset+1 (clamped to
// 0..players), at most limit rows (1..100). players is the named players,
// finished anyone who finished; next is the next offset, 0 at the end. A name
// deleted since is skipped, so a page may hold fewer rows. A page reads its
// own rows only.
func HoleLeaderboard(hole, mode string, offset, limit int) string {
e, m := readHole(hole), modeOf(mode)
limit = clampLimit(limit)
board := e.board(m)
size := board.Size()
if offset < 0 {
offset = 0
}
if offset > size {
offset = size // and offset+limit cannot overflow
}
var sb strings.Builder
sb.WriteString("{" + versionJSON + `,"hole":` + jstr(e.id) + `,"mode":` + jstr(modeNames[m]) +
`,"par":` + strconv.Itoa(e.par) + `,"players":` + strconv.Itoa(size) + `,"finished":` + strconv.Itoa(e.bests(m).Size()) +
`,"offset":` + strconv.Itoa(offset) + `,"rows":[`)
n := 0
board.IterateByOffset(offset, limit, func(k, v string) bool {
p := v
name := nameOf(p)
if name == "" {
return false // a name deleted since
}
sb.WriteString(sep(n) + strokesRow(p, name, boardStrokes(k)))
n++
return false
})
next := 0
if offset+limit < size {
next = offset + limit
}
sb.WriteString(`],"next":` + strconv.Itoa(next) + "}")
return sb.String()
}
// pageMax is the most rows one page of a read returns.
const pageMax = 100
// clampLimit keeps a page's size to 1..pageMax.
func clampLimit(n int) int {
if n < 1 {
return 1
}
if n > pageMax {
return pageMax
}
return n
}
// maxFriends bounds the addresses one Bests or Standings read takes.
const maxFriends = 50
// friends splits a comma-separated list of addresses: each valid one once,
// at most maxFriends. Junk and repeats are skipped and use up nothing.
func friends(list string) []string {
var out []string
seen := map[string]bool{}
for _, p := range strings.Split(list, ",") {
if len(out) == maxFriends {
break
}
if p = strings.TrimSpace(p); p != "" && !seen[p] && address(p).IsValid() {
seen[p] = true
out = append(out, p)
}
}
return out
}
// Bests is the best finished round on one hole, in a mode, of each of the
// given players (comma-separated addresses, named or not): a board of
// friends, where no stranger and no bot can push anyone off.
func Bests(hole, mode, players string) string {
e, m := readHole(hole), modeOf(mode)
var sb strings.Builder
sb.WriteString("{" + versionJSON + `,"hole":` + jstr(e.id) + `,"mode":` + jstr(modeNames[m]) + `,"par":` + strconv.Itoa(e.par) + `,"rows":[`)
n := 0
for _, p := range friends(players) {
if v := bestOfPlayer(e, m, p); v != "" {
sb.WriteString(sep(n) + strokesRow(p, "", bestStrokes(v)))
n++
}
}
sb.WriteString("]}")
return sb.String()
}
// Standings is each given player's course-wide standing in a mode: how many
// of the course's current holes they finished, in how many strokes, and
// those holes' pars summed.
func Standings(mode, players string) string {
m := modeOf(mode)
var sb strings.Builder
sb.WriteString("{" + versionJSON + `,"mode":` + jstr(modeNames[m]) + `,"holes":` + strconv.Itoa(slots.Size()) + `,"rows":[`)
n := 0
for _, p := range friends(players) {
if v, ok := totals[m].Get(p); ok {
sb.WriteString(sep(n) + standingRow(p, "", decodeRow(v)))
n++
}
}
sb.WriteString("]}")
return sb.String()
}
// Records is a page of every player's best on a hole in a mode, named or not,
// with the height that ranks it before a later tie: all a successor needs to
// carry the boards over in their order.
// The paged reads (Records, Players, Community) walk everything by
// key: after is the last key of the page before ("" for the first), limit is
// clamped to 1..100, next is the after of the next page ("" at the end).
func Records(hole, mode, after string, limit int) string {
e, m := readHole(hole), modeOf(mode)
var sb strings.Builder
sb.WriteString("{" + versionJSON + `,"hole":` + jstr(e.id) + `,"mode":` + jstr(modeNames[m]) + `,"rows":[`)
next := page(e.bests(m).Iterate, after, limit, func(i int, p string, v string) {
at, _, _ := bestFields(v)
sb.WriteString(sep(i) + `{"player":` + jstr(p) + `,"strokes":` + strconv.Itoa(bestStrokes(v)) + `,"height":` + strconv.FormatInt(at, 10) + "}")
})
sb.WriteString(`],"next":` + jstr(next) + "}")
return sb.String()
}
// Players is a page of every course standing in a mode, named or not: its
// holes, strokes and par (all the ranking's key reads) and the height of the
// finish that last improved it (the tie-break), paged like Records.
func Players(mode, after string, limit int) string {
m := modeOf(mode)
var sb strings.Builder
sb.WriteString("{" + versionJSON + `,"mode":` + jstr(modeNames[m]) + `,"rows":[`)
next := page(totals[m].Iterate, after, limit, func(i int, p string, v string) {
r := decodeRow(v)
sb.WriteString(sep(i) + `{"player":` + jstr(p) + standingFields(r) + `,"height":` + strconv.FormatInt(r.height, 10) + "}")
})
sb.WriteString(`],"next":` + jstr(next) + "}")
return sb.String()
}
// walk is a tree's Iterate: what page reads.
type walk func(start, end string, cb func(key, v string) bool) bool
// rowOf is a ranked player's course standing in mode m (a row that ranks has one).
func rowOf(m int, p string) *row {
v, ok := totals[m].Get(p)
if !ok {
panic("golf: no standing for a ranked player: " + p) // ranks and totals move together: cannot happen
}
return decodeRow(v)
}
// page walks up to limit entries of t after the key after, and returns the
// key to continue from, "" at the end.
func page(t walk, after string, limit int, fn func(i int, key string, v string)) string {
limit = clampLimit(limit)
start := ""
if after != "" {
start = after + "\x00" // the first key past after
}
n, next, last := 0, "", ""
t(start, "", func(k, v string) bool {
if n == limit {
next = last
return true
}
fn(n, k, v)
last = k
n++
return false
})
return next
}
weather.gno
package golf
import (
"strconv"
"time"
"gno.land/p/nym-alexiscolin000/gnogolf/course"
"gno.land/p/nt/ufmt/v0"
)
// The weather changes every five minutes of chain time, differs from hole to
// hole and is the same for everyone (course.ForecastFor hashes hole and
// period). A round is played in the weather of the period it started in, and
// records it, so anyone can replay it.
// PeriodSeconds is how long one weather lasts.
const PeriodSeconds = 5 * 60
// Period is the weather period of the chain's current block time.
func Period() int64 { return time.Now().Unix() / PeriodSeconds }
// weatherOf is the hole's weather in a period: seeded by its id, so each
// version of a slot has weather of its own.
func weatherOf(e *entry, h *course.Simple, period int64) course.Forecast {
return course.ForecastFor(e.id, e.world, h, period)
}
// forecastJSON is a forecast as an object, head its first fields if any
// (as `"version":1,`). Zones' air and capped are not printed: only the wind
// has them, always.
func forecastJSON(head string, f course.Forecast) string {
return "{" + head + `"period":` + strconv.FormatInt(f.Period, 10) + `,"kind":` + jstr(f.Kind) +
`,"wind":` + jvec(f.Wind) + `,"zones":` + zonesJSON(f.Zones, false) + "}"
}
// Weather is a hole's weather in a period, as JSON: the zones a client draws
// and the chain plays under. Its "gas" is what a commit there spends before
// its first shot (decoding and forecast), counted against the commit's
// budget: a client adds it to its shots' estimate. A future period panics.
func Weather(hole string, period int64) string {
notAhead(period)
e := readHole(hole)
fc := weatherOf(e, e.hole(), period)
return forecastJSON(versionJSON+`,"gas":`+strconv.FormatInt(fixedGas(e, fc), 10)+",", fc)
}
// notAhead refuses a period still to come. It is no secret (ForecastFor is
// pure): this only keeps reads to the weather a round can be played in.
func notAhead(period int64) {
if period > Period() {
panic("golf: that weather has not come yet")
}
}
// notOver refuses a round's weather two periods or more behind: a round left
// for later cannot be finished days on in the weather it picked.
func notOver(period int64) {
if period < Period()-1 {
panic(ufmt.Sprintf("golf: this round's weather (period %d) is over: Reset to play again", period))
}
}
// playablePeriod checks the period a round starts under: the current one, or
// the one just gone, for a round that ran over the turn of the period.
func playablePeriod(period int64) {
now := Period()
if period != now && period != now-1 {
panic(ufmt.Sprintf("golf: period %d is not the current weather (%d) or the one before", period, now))
}
}