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

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

Playground

arena.gno

// Package arena holds Gnomepit's online matches. A challenger posts a sealed deck and
// round-1 plan; an acceptor answers face up; the challenger reveals each round with the
// seal of the next, and the shared duel engine checks and resolves every move. A session
// key is bound to the match of the first call it signs: it then acts in no other match and
// posts or accepts nothing more. Calls the wallet signs are never bound.
package arena

import (
	"encoding/base64"
	"strconv"
	"strings"
	"time"

	"gno.land/p/g188vafzutzvlfw6wt7u3s62xtuvm0epmu8ufmfz/gnomepit/engine"
)

const (
	moveWindow = 24 * 60 * 60     // seconds a player has for each move
	openWindow = 7 * 24 * 60 * 60 // seconds an open challenge stays on the board
	maxBox     = 104              // bytes
	maxPage    = 50
	maxCleared = 8 // expired challenges one Challenge deletes at most
	idDigits   = 10
)

const (
	phaseOpen    = "open"
	phaseReveal  = "reveal"
	phasePlay    = "play"
	phaseEnded   = "ended"
	phaseExpired = "expired" // reported for an open match past its expiry, never stored
)

var lastID int

// OpenChallenge is an open challenge as the board lists it.
type OpenChallenge struct {
	ID, Challenger, Clan, Opponent string
	Posted, Expires                int64
}

// Challenge posts a challenge for clan with the seals of the challenger's deck and
// round-1 plan, the box holding both, and an opponent who alone may accept, or none.
// It returns the new match's id. It first deletes up to 8 expired challenges, whoever
// posted them.
func Challenge(cur realm, clan, deckSeal, planSeal, box string, opponent address) string {
	rules := engine.ProofOfConcept()
	c := clanNumber(rules, clan)
	if c == 0 {
		panic("unknown clan")
	}
	if !validSeal(deckSeal) || !validSeal(planSeal) {
		panic("invalid seal")
	}
	raw := boxBytes(box)
	if opponent != "" && !canonical(opponent) {
		panic("invalid opponent")
	}
	now := time.Now().Unix()
	for _, id := range openClear(now, maxCleared) {
		if m, ok := loadMatch(rules, id); ok {
			forget(id, m.challenger)
		}
	}

	lastID++
	m := record{
		phase:      phaseOpen,
		deadline:   now + openWindow,
		challenger: cur.Previous().Address(),
		opponent:   opponent,
		deckSeal:   deckSeal,
		seal:       planSeal,
		box:        raw,
	}
	m.clans[0] = c
	join(cur.Previous().IsUser(), m.challenger, lastID)
	saveMatch(rules, lastID, m)
	openAdd(lastID, m.deadline)
	tellBoard(lastID, clan+" posted a challenge.")
	return strconv.Itoa(lastID)
}

// Open lists open, unexpired challenges, newest first: limit of them after skipping
// offset. limit is 1 to 50.
func Open(offset, limit int) []OpenChallenge {
	checkPage(offset, limit)
	rules := engine.ProofOfConcept()
	list := []OpenChallenge{}
	for _, id := range openNewest(time.Now().Unix(), offset, limit) {
		m, ok := loadMatch(rules, id)
		if !ok {
			continue
		}
		list = append(list, OpenChallenge{
			ID:         strconv.Itoa(id),
			Challenger: m.challenger.String(),
			Clan:       clanName(rules, m.clans[0]),
			Opponent:   m.opponent.String(),
			Posted:     m.deadline - openWindow,
			Expires:    m.deadline,
		})
	}
	return list
}

// forget deletes open challenge id and its place among its challenger's matches. Its
// entry on the open list is the caller's to remove.
func forget(id int, challenger address) {
	dropMatch(id)
	p := loadPlayer(challenger)
	p.remove(id)
	savePlayer(challenger, p)
}

func (m record) expired(now int64) bool {
	return m.phase == phaseOpen && now > m.deadline
}

func checkPage(offset, limit int) {
	if offset < 0 {
		panic("offset must not be negative")
	}
	if limit < 1 || limit > maxPage {
		panic("limit must be 1 to 50")
	}
}

// boxBytes decodes a box argument: the standard base64 of 1 to maxBox bytes, in the one
// form that encodes them, so Match returns every box exactly as it was sent.
func boxBytes(text string) string {
	if len(text) == 0 || len(text) > base64.StdEncoding.EncodedLen(maxBox) {
		panic("invalid box")
	}
	raw, err := base64.StdEncoding.DecodeString(text)
	if err != nil || len(raw) > maxBox || base64.StdEncoding.EncodeToString(raw) != text {
		panic("invalid box")
	}
	return string(raw)
}

// canonical accepts a valid address in the lowercase form callers carry. bech32 also
// allows uppercase, which would never equal a caller's address.
func canonical(a address) bool {
	return a.IsValid() && string(a) == strings.ToLower(string(a))
}

// validSeal accepts a sha256 sum in lowercase hex.
func validSeal(s string) bool {
	if len(s) != 64 {
		return false
	}
	for i := 0; i < len(s); i++ {
		c := s[i]
		if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
			return false
		}
	}
	return true
}

codec.gno

package arena

import (
	"encoding/binary"
	"encoding/hex"

	"gno.land/p/g188vafzutzvlfw6wt7u3s62xtuvm0epmu8ufmfz/gnomepit/engine"
)

// Everything stored by the arena is a byte string laid out here, big-endian. This file
// is the only code that reads or writes those bytes.

const (
	chunkSize   = 64 // match ids per chunk
	addressSize = 40 // bytes in an address's text
	sealSize    = 32 // bytes in a raw sha256 seal
	lockSize    = addressSize + 4 + 4
	openSize    = 4 + 4
	standingFix = 2 + 2 + 2 + 2 + 1 // a standing's bytes before its per-clan counts
	clanSize    = 2 + 4 + 4 + 4

	planBits   = 20 // bits per round in a side's plans: 2 for the length, 6 per card
	cardBits   = 6
	maxPlanLen = 3
	maxRound   = 3
	maxPool    = 16 // cards in a clan's pool; a deck is one bit per pool card
)

// ---- Bit fields

// bitsAt returns the width bits of v starting at bit at.
func bitsAt(v uint64, at, width uint) uint64 {
	return (v >> at) & mask(width)
}

// withBits returns v with the width bits at bit at replaced by x.
func withBits(v uint64, at, width uint, x uint64) uint64 {
	if x&^mask(width) != 0 {
		panic("value does not fit")
	}
	return v&^(mask(width)<<at) | x<<at
}

func mask(width uint) uint64 {
	if width >= 64 {
		return ^uint64(0)
	}
	return 1<<width - 1
}

// ---- Plans

// planAt returns the plan made for round, or nil when it is not yet made.
func planAt(plans uint64, round int) engine.Plan {
	at := planOffset(round)
	n := int(bitsAt(plans, at, 2))
	if n == 0 {
		return nil
	}
	p := make(engine.Plan, n)
	for i := range p {
		p[i] = engine.CardID(bitsAt(plans, at+2+uint(i)*cardBits, cardBits))
	}
	return p
}

// withPlan returns plans with round's plan set to p.
func withPlan(plans uint64, round int, p engine.Plan) uint64 {
	if len(p) < 1 || len(p) > maxPlanLen {
		panic("invalid plan")
	}
	at := planOffset(round)
	v := withBits(0, 0, 2, uint64(len(p)))
	for i, id := range p {
		if id < 0 || id >= 1<<cardBits {
			panic("invalid plan")
		}
		v = withBits(v, 2+uint(i)*cardBits, cardBits, uint64(id))
	}
	return withBits(plans, at, planBits, 0) | v<<at
}

// plansMade counts the rounds from the first that have a plan.
func plansMade(plans uint64) int {
	n := 0
	for n < maxRound && bitsAt(plans, planOffset(n+1), 2) != 0 {
		n++
	}
	return n
}

func planOffset(round int) uint {
	if round < 1 || round > maxRound {
		panic("invalid plan")
	}
	return uint(round-1) * planBits
}

// ---- Decks

// deckOnPool returns deck, a set of card ids, as one bit per card of pool in id order.
func deckOnPool(pool, deck uint64) uint16 {
	if cardsIn(pool) > maxPool {
		panic("pool holds more than 16 cards")
	}
	if deck&^pool != 0 {
		panic("deck outside the pool")
	}
	var bits uint16
	k := uint(0)
	for id := uint(0); id < 64; id++ {
		if pool&(1<<id) == 0 {
			continue
		}
		if deck&(1<<id) != 0 {
			bits |= 1 << k
		}
		k++
	}
	return bits
}

// deckFromPool is the inverse of deckOnPool.
func deckFromPool(pool uint64, bits uint16) uint64 {
	if cardsIn(pool) > maxPool {
		panic("pool holds more than 16 cards")
	}
	var deck uint64
	k := uint(0)
	for id := uint(0); id < 64; id++ {
		if pool&(1<<id) == 0 {
			continue
		}
		if bits&(1<<k) != 0 {
			deck |= 1 << id
		}
		k++
	}
	if uint64(bits)>>k != 0 {
		panic("deck outside the pool")
	}
	return deck
}

func cardsIn(pool uint64) uint {
	n := uint(0)
	for ; pool != 0; pool &= pool - 1 {
		n++
	}
	return n
}

// ---- Byte reading and writing

type writer struct{ b []byte }

func (w *writer) u8(x uint64)   { w.b = append(w.b, byte(x)) }
func (w *writer) text(s string) { w.b = append(w.b, s...) }

func (w *writer) u16(x uint64) {
	var t [2]byte
	binary.BigEndian.PutUint16(t[:], uint16(x))
	w.b = append(w.b, t[:]...)
}

func (w *writer) u32(x uint64) {
	var t [4]byte
	binary.BigEndian.PutUint32(t[:], uint32(x))
	w.b = append(w.b, t[:]...)
}

func (w *writer) u64(x uint64) {
	var t [8]byte
	binary.BigEndian.PutUint64(t[:], x)
	w.b = append(w.b, t[:]...)
}

// addr writes a's 40 characters.
func (w *writer) addr(a address) {
	if len(a) != addressSize {
		panic("invalid address")
	}
	w.text(string(a))
}

// seal writes a seal, 64 hex characters, as 32 raw bytes.
func (w *writer) seal(s string) {
	raw, err := hex.DecodeString(s)
	if err != nil || len(raw) != sealSize {
		panic("invalid seal")
	}
	w.b = append(w.b, raw...)
}

func (w *writer) String() string { return string(w.b) }

type reader struct {
	s  string
	at int
}

func (r *reader) left() int { return len(r.s) - r.at }

func (r *reader) text(n int) string {
	if r.left() < n {
		panic("truncated record")
	}
	s := r.s[r.at : r.at+n]
	r.at += n
	return s
}

func (r *reader) u8() uint64    { return uint64(r.text(1)[0]) }
func (r *reader) u16() uint64   { return uint64(binary.BigEndian.Uint16([]byte(r.text(2)))) }
func (r *reader) u32() uint64   { return uint64(binary.BigEndian.Uint32([]byte(r.text(4)))) }
func (r *reader) u64() uint64   { return binary.BigEndian.Uint64([]byte(r.text(8))) }
func (r *reader) addr() address { return address(r.text(addressSize)) }

// seal reads 32 raw bytes as 64 hex characters.
func (r *reader) seal() string { return hex.EncodeToString([]byte(r.text(sealSize))) }

// ---- Match record

// record is a match as the arena works on it, decoded from its stored bytes. clans holds
// each side's index in the ruleset plus one, 0 for none; decks and plans are the engine's
// card sets and the packed plans of withPlan; hp is the HP after each round, per side;
// carried holds only the Vulnerable and Strength left after the last resolved round.
// deckSeal and seal are 64 hex characters; box is the raw bytes, up to maxBox, stored with a 2-byte length.
type record struct {
	phase, result, reason string
	clans                 [2]int
	deadline              int64
	decks                 [2]uint64
	plans                 [2]uint64
	hp                    [3][2]int
	carried               [2]engine.Vitals
	challenger, acceptor  address
	opponent              address
	deckSeal, seal, box   string
}

const (
	flagOpponent = 1 << iota
	flagDeckSeal
	flagSealBox
)

// The value of each name is its index; 0 of result and reason is none.
var (
	phaseNames  = []string{phaseOpen, phaseReveal, phasePlay, phaseEnded}
	resultNames = []string{"", "a", "b", "draw"}
	reasonNames = []string{"", "hp", "knockout", "forfeit", "resign"}
)

func nameIndex(names []string, s, what string) uint64 {
	for i, n := range names {
		if n == s {
			return uint64(i)
		}
	}
	panic("unknown " + what)
}

func nameAt(names []string, i uint64, what string) string {
	if i >= uint64(len(names)) {
		panic("unknown " + what)
	}
	return names[i]
}

func encodeMatch(rules *engine.Ruleset, m record) string {
	var flags uint64
	if m.opponent != "" {
		flags |= flagOpponent
	}
	if m.deckSeal != "" {
		flags |= flagDeckSeal
	}
	if m.seal != "" || m.box != "" {
		flags |= flagSealBox
	}

	w := &writer{}
	w.u8(nameIndex(phaseNames, m.phase, "phase") |
		nameIndex(resultNames, m.result, "result")<<3 |
		nameIndex(reasonNames, m.reason, "reason")<<5)
	w.u8(clanNibble(rules, m.clans[0])<<4 | clanNibble(rules, m.clans[1]))
	w.u8(flags)
	w.u32(uint64(m.deadline))
	for side := 0; side < 2; side++ {
		w.u16(uint64(deckOnPool(poolOf(rules, m.clans[side]), m.decks[side])))
	}
	w.u64(m.plans[0])
	w.u64(m.plans[1])
	for _, round := range m.hp {
		for _, hp := range round {
			if hp < -128 || hp > 127 {
				panic("hp does not fit a byte")
			}
			w.u8(uint64(int8(hp)))
		}
	}
	for _, v := range m.carried {
		if v.Vulnerable < 0 || v.Vulnerable > 15 || v.Strength < 0 || v.Strength > 15 {
			panic("carried state does not fit")
		}
		w.u8(uint64(v.Vulnerable)<<4 | uint64(v.Strength))
	}
	w.addr(m.challenger)
	if m.phase != phaseOpen {
		w.addr(m.acceptor)
	}
	if flags&flagOpponent != 0 {
		w.addr(m.opponent)
	}
	if flags&flagDeckSeal != 0 {
		w.seal(m.deckSeal)
	}
	if flags&flagSealBox != 0 {
		if len(m.box) > maxBox {
			panic("box too long")
		}
		w.seal(m.seal)
		w.u16(uint64(len(m.box)))
		w.text(m.box)
	}
	return w.String()
}

func decodeMatch(rules *engine.Ruleset, b string) record {
	var m record
	r := &reader{s: b}
	first := r.u8()
	m.phase = nameAt(phaseNames, first&7, "phase")
	m.result = nameAt(resultNames, first>>3&3, "result")
	m.reason = nameAt(reasonNames, first>>5, "reason")
	clans := r.u8()
	m.clans = [2]int{int(clans >> 4), int(clans & 15)}
	flags := r.u8()
	m.deadline = int64(r.u32())
	for side := 0; side < 2; side++ {
		m.decks[side] = deckFromPool(poolOf(rules, m.clans[side]), uint16(r.u16()))
	}
	m.plans[0] = r.u64()
	m.plans[1] = r.u64()
	for round := range m.hp {
		for side := range m.hp[round] {
			m.hp[round][side] = int(int8(r.u8()))
		}
	}
	for side := range m.carried {
		v := r.u8()
		m.carried[side] = engine.Vitals{Vulnerable: int(v >> 4), Strength: int(v & 15)}
	}
	m.challenger = r.addr()
	if m.phase != phaseOpen {
		m.acceptor = r.addr()
	}
	if flags&flagOpponent != 0 {
		m.opponent = r.addr()
	}
	if flags&flagDeckSeal != 0 {
		m.deckSeal = r.seal()
	}
	if flags&flagSealBox != 0 {
		m.seal = r.seal()
		m.box = r.text(int(r.u16()))
	}
	if r.left() != 0 {
		panic("trailing bytes in record")
	}
	return m
}

// clanNibble is a clan's stored form, its ruleset index plus one, checked against rules.
func clanNibble(rules *engine.Ruleset, clan int) uint64 {
	poolOf(rules, clan)
	return uint64(clan)
}

// poolOf returns the card pool of clan, 0 for no clan.
func poolOf(rules *engine.Ruleset, clan int) uint64 {
	if clan == 0 {
		return 0
	}
	if clan < 0 || clan > len(rules.Clans) {
		panic("unknown clan")
	}
	return rules.Clans[clan-1].Pool
}

// ---- Chunks

// A chunk holds, for each match id in order, a 2-byte record length and the record. A
// removed match keeps its place with length 0.

// chunkRecord returns the record in slot, or "" when it is removed or beyond the chunk.
func chunkRecord(chunk string, slot int) string {
	r := &reader{s: chunk}
	for i := 0; r.left() > 0; i++ {
		rec := r.text(int(r.u16()))
		if i == slot {
			return rec
		}
	}
	return ""
}

// withChunkRecord returns chunk with slot's record set to rec, adding empty slots up to it.
func withChunkRecord(chunk string, slot int, rec string) string {
	if slot < 0 || slot >= chunkSize {
		panic("slot outside the chunk")
	}
	if len(rec) > 0xFFFF {
		panic("record too long")
	}
	r := &reader{s: chunk}
	w := &writer{}
	for i := 0; i <= slot || r.left() > 0; i++ {
		var old string
		if r.left() > 0 {
			old = r.text(int(r.u16()))
		}
		if i == slot {
			old = rec
		}
		w.u16(uint64(len(old)))
		w.text(old)
	}
	return w.String()
}

// ---- Players

// playerRecord is what the arena keeps per player: the ids of their matches, oldest
// first, their standing, nil until their first rated match, and the session locks that
// bind a session key to one match.
type playerRecord struct {
	ids      []int
	standing *standing
	locks    []sessionLock
}

// standing is a player's rated record. lastClan is the clan number, index plus one, of
// their last rated match; perClan[i] counts their rated matches with clan number i + 1.
type standing struct {
	rating, wins, losses, draws int
	lastClan                    int
	perClan                     []int
}

type sessionLock struct {
	session address
	id      int
	expires int64
}

// A player's bytes are a 2-byte id count, the ids at 4 bytes each, a 1-byte standing
// length, 0 for none, the standing, then the locks. A standing is the rating, wins, losses
// and draws at 2 bytes each, the last clan at 1, then a 2-byte count per clan.
// ceiling: joining a match or changing a lock rewrites all of a player's ids, up to 65,535, so
// gas grows with their matches; an avl index of ids per player if some play thousands.
func decodePlayer(s string) playerRecord {
	var p playerRecord
	if s == "" {
		return p
	}
	r := &reader{s: s}
	for n := r.u16(); n > 0; n-- {
		p.ids = append(p.ids, int(r.u32()))
	}
	p.standing = readStanding(r)
	if r.left()%lockSize != 0 {
		panic("malformed player")
	}
	for r.left() > 0 {
		p.locks = append(p.locks, sessionLock{session: r.addr(), id: int(r.u32()), expires: int64(r.u32())})
	}
	return p
}

// decodeStanding reads only the standing of a player's bytes, skipping their ids, so
// its cost does not grow with the player's matches; nil when they have none.
func decodeStanding(s string) *standing {
	if s == "" {
		return nil
	}
	r := &reader{s: s}
	r.text(4 * int(r.u16()))
	return readStanding(r)
}

// withStanding returns a player's bytes s with their standing replaced by st. It copies the
// ids and locks without reading them, so its cost does not grow with the player's matches.
func withStanding(s string, st *standing) string {
	if s == "" {
		return encodePlayer(playerRecord{standing: st})
	}
	r := &reader{s: s}
	r.text(4 * int(r.u16()))
	head := r.at
	readStanding(r)
	w := &writer{}
	w.text(s[:head])
	writeStanding(w, st)
	w.text(s[r.at:])
	return w.String()
}

func readStanding(r *reader) *standing {
	n := int(r.u8())
	if n == 0 {
		return nil
	}
	if n < standingFix || (n-standingFix)%2 != 0 {
		panic("malformed player")
	}
	st := &standing{rating: int(r.u16()), wins: int(r.u16()), losses: int(r.u16()), draws: int(r.u16()), lastClan: int(r.u8())}
	for i := standingFix; i < n; i += 2 {
		st.perClan = append(st.perClan, int(r.u16()))
	}
	return st
}

func encodePlayer(p playerRecord) string {
	if len(p.ids) > 0xFFFF {
		panic("too many matches")
	}
	w := &writer{}
	w.u16(uint64(len(p.ids)))
	for _, id := range p.ids {
		w.u32(uint64(id))
	}
	writeStanding(w, p.standing)
	for _, l := range p.locks {
		w.addr(l.session)
		w.u32(uint64(l.id))
		w.u32(uint64(l.expires))
	}
	return w.String()
}

func writeStanding(w *writer, st *standing) {
	if st == nil {
		w.u8(0)
		return
	}
	w.u8(uint64(standingFix + 2*len(st.perClan)))
	w.u16(uint64(st.rating))
	w.u16(uint64(st.wins))
	w.u16(uint64(st.losses))
	w.u16(uint64(st.draws))
	w.u8(uint64(st.lastClan))
	for _, n := range st.perClan {
		w.u16(uint64(n))
	}
}

// ladderKey orders the ladder: highest rating first, then address order.
func ladderKey(rating int, player address) string {
	w := &writer{}
	w.u16(uint64(maxRating - rating))
	w.text(string(player))
	return w.String()
}

// ---- Clan records

// clanRecord is a clan's rating and its record in rated matches against other clans.
type clanRecord struct {
	rating, wins, losses, draws int
}

// The clan records are one string holding, per clan in ruleset order, the rating at 2
// bytes and the wins, losses and draws at 4 each. decodeClans returns n clans; a clan
// past the end of s has no rated match yet.
func decodeClans(s string, n int) []clanRecord {
	if len(s)%clanSize != 0 {
		panic("malformed clans")
	}
	r := &reader{s: s}
	c := make([]clanRecord, n)
	for i := range c {
		if r.left() == 0 {
			c[i] = clanRecord{rating: startRating}
			continue
		}
		c[i] = clanRecord{rating: int(r.u16()), wins: int(r.u32()), losses: int(r.u32()), draws: int(r.u32())}
	}
	return c
}

func encodeClans(c []clanRecord) string {
	w := &writer{}
	for _, x := range c {
		w.u16(uint64(x.rating))
		w.u32(uint64(x.wins))
		w.u32(uint64(x.losses))
		w.u32(uint64(x.draws))
	}
	return w.String()
}

// ---- Open challenges

// openEntry is a challenge on the board: its match id and expiry in Unix seconds.
type openEntry struct {
	id      int
	expires int64
}

func openEntries(s string) []openEntry {
	if len(s)%openSize != 0 {
		panic("malformed open list")
	}
	r := &reader{s: s}
	var entries []openEntry
	for r.left() > 0 {
		entries = append(entries, openEntry{id: int(r.u32()), expires: int64(r.u32())})
	}
	return entries
}

func encodeOpen(entries []openEntry) string {
	w := &writer{}
	for _, e := range entries {
		w.u32(uint64(e.id))
		w.u32(uint64(e.expires))
	}
	return w.String()
}

gnomod.toml

module = "gno.land/r/g188vafzutzvlfw6wt7u3s62xtuvm0epmu8ufmfz/gnomepit/arena"
gno = "0.9"

[addpkg]
  creator = "g188vafzutzvlfw6wt7u3s62xtuvm0epmu8ufmfz"
  height = 685519
  max_deposit = "50000000ugnot"

lock.gno

package arena

import (
	"chain/runtime"
	"strconv"
	"time"
)

// guard binds the session that signed the transaction to match id, held in m, saving the
// caller's record only when its locks change.
func guard(fromUser bool, caller address, m record, id int) {
	session, expires, ok := signingSession(fromUser)
	if !ok {
		return
	}
	if caller != m.challenger && caller != m.acceptor {
		panic("not a player")
	}
	p := loadPlayer(caller)
	if p.lock(session, expires, id, false, time.Now().Unix()) {
		savePlayer(caller, p)
	}
}

// join adds match id to the caller's record and binds the session that signed the
// transaction to it, refused when that session is bound to a match already.
func join(fromUser bool, caller address, id int) {
	p := loadPlayer(caller)
	if session, expires, ok := signingSession(fromUser); ok {
		p.lock(session, expires, id, true, time.Now().Unix())
	}
	p.add(id)
	savePlayer(caller, p)
}

// signingSession returns the signing session key and its expiry when fromUser: a session
// signs the whole transaction, so a call through another realm is left unchecked.
func signingSession(fromUser bool) (address, int64, bool) {
	if !fromUser {
		return "", 0, false
	}
	session, expires, _, ok := runtime.GetSessionInfo()
	return session, expires, ok
}

// lock binds session to match id in p's locks, panicking when it is refused, and reports
// whether the locks changed.
func (p *playerRecord) lock(session address, expires int64, id int, opening bool, now int64) bool {
	locks, changed, refusal := lockSession(p.locks, session, expires, id, opening, now)
	if refusal != "" {
		panic(refusal)
	}
	p.locks = locks
	return changed
}

// lockSession binds session to match id, refused when bound to another, or any when opening.
// It drops expired locks and any lock its key holds under another expiry (Unix seconds, 0 never).
func lockSession(locks []sessionLock, session address, expires int64, id int, opening bool, now int64) (kept []sessionLock, changed bool, refusal string) {
	for _, l := range locks {
		expired := l.expires != 0 && l.expires <= now
		stale := l.session == session && l.expires != expires
		if !expired && !stale {
			kept = append(kept, l)
		}
	}
	changed = len(kept) != len(locks)
	for _, l := range kept {
		if l.session != session {
			continue
		}
		if opening || l.id != id {
			return kept, changed, "session locked to match " + strconv.Itoa(l.id)
		}
		return kept, changed, ""
	}
	return append(kept, sessionLock{session: session, id: id, expires: expires}), true, ""
}

notify.gno

package arena

import (
	"chain"
	"strconv"

	"gno.land/r/nym-gfanton001/gnotif/v1"
)

// self is the arena's package path; a deploy under another path changes it.
var self string

// pagePath is where the page lives on its origin, the start of every trigger's link; the
// registry accepts only a link that starts with "/".
const pagePath = "/gnomepit/"

// init sets the arena's three gnotif triggers and keeps no handle, so they stay as set
// for this deploy. A Turn or Ended event carries the address it notifies in "to", so a
// browser opts in with its wallet's address; a Board event notifies every browser that
// opted in.
func init(cur realm) {
	self = cur.PkgPath()
	me := cur.Sub(gnotif.Subpath)
	h := gnotif.Open(cross(me))
	h.Set(cross(me), "turn", gnotif.Trigger{Event: "Turn", Param: "to", Title: "Your move in Gnomepit", Body: "{text}", Link: pagePath + "#match={match}"})
	h.Set(cross(me), "ended", gnotif.Trigger{Event: "Ended", Param: "to", Title: "Match over", Body: "{text}", Link: pagePath + "#match={match}"})
	h.Set(cross(me), "board", gnotif.Trigger{Event: "Board", Title: "Gnomepit challenges", Body: "{text}", Link: pagePath})
}

// tell emits kind to player about match id. It emits nothing when player made the call,
// so an event never names its caller.
func tell(kind string, player, caller address, id int, text string) {
	if player == caller {
		return
	}
	chain.Emit(kind, "to", player.String(), "match", strconv.Itoa(id), "text", text)
}

// tellBoard emits Board about match id, whose change altered the open-challenge list. It
// names no address, so a caller cannot aim it at one player's browser.
func tellBoard(id int, text string) {
	chain.Emit("Board", "match", strconv.Itoa(id), "text", text)
}

// tellEnded sends Ended to each player of the finished match m, numbered id, but caller,
// one event each, since gnotif reads only the first value of a repeated attribute.
func tellEnded(m record, id int, caller address) {
	tell("Ended", m.challenger, caller, id, endText(m, 0))
	if m.acceptor != m.challenger {
		tell("Ended", m.acceptor, caller, id, endText(m, 1))
	}
}

// endText says how m ended to the player on side.
func endText(m record, side int) string {
	won := m.result == "a" && side == 0 || m.result == "b" && side == 1
	switch m.reason {
	case "hp":
		last := m.hp[plansMade(m.plans[0])-1]
		score := strconv.Itoa(last[side]) + " to " + strconv.Itoa(last[1-side]) + "."
		switch {
		case m.result == "draw":
			return "Draw on HP, " + score
		case won:
			return "You won on HP, " + score
		}
		return "You lost on HP, " + score
	case "knockout":
		switch {
		case m.result == "draw":
			return "Both gnomes fell: a draw."
		case won:
			return "You won by knockout."
		}
		return "You lost by knockout."
	case "resign":
		if won {
			return "Your opponent resigned. You won."
		}
		return "You resigned."
	}
	if won {
		return "You won by forfeit."
	}
	return "You lost by forfeit."
}

play.gno

package arena

import (
	"crypto/sha256"
	"encoding/hex"
	"strconv"
	"strings"
	"time"

	"gno.land/p/g188vafzutzvlfw6wt7u3s62xtuvm0epmu8ufmfz/gnomepit/engine"
)

// Accept answers open challenge id as clan, with deck and the round-1 plan in plain
// text. When the challenge names an opponent, only that address may accept.
func Accept(cur realm, id, clan, deck, plan string) {
	rules := engine.ProofOfConcept()
	n, m := find(rules, id)
	now := time.Now().Unix()
	if m.phase != phaseOpen {
		panic("wrong phase")
	}
	if m.expired(now) {
		panic("challenge expired")
	}
	caller := cur.Previous().Address()
	if m.opponent != "" && caller != m.opponent {
		panic("not the named opponent")
	}
	c := clanNumber(rules, clan)
	if c == 0 {
		panic("unknown clan")
	}
	bits := deckBits(rules, rules.Clans[c-1], deck)
	b := planOf(rules, plan)
	if !legal(rules, stateOf(rules, m), engine.SideB, bits, b) {
		panic("illegal plan")
	}

	m.acceptor = caller
	m.opponent = ""
	join(cur.Previous().IsUser(), caller, n)
	m.clans[1] = c
	m.decks[1] = bits
	m.plans[1] = withPlan(m.plans[1], 1, b)
	m.phase = phaseReveal
	m.deadline = now + moveWindow
	saveMatch(rules, n, m)
	openRemove(n)
	tellBoard(n, "Challenge "+strconv.Itoa(n)+" was taken.")
	tell("Turn", m.challenger, caller, n, clan+" accepted your challenge. Your move within 24 hours.")
}

// Reveal opens the challenger's sealed plan for the round being played, and on the
// first reveal the sealed deck, then resolves the round. A match that goes on needs
// nextSeal and nextBox for the challenger's next plan; one that ends takes neither.
func Reveal(cur realm, id, deck, deckSalt, plan, planSalt, nextSeal, nextBox string) {
	rules := engine.ProofOfConcept()
	n, m := find(rules, id)
	now := time.Now().Unix()
	caller := cur.Previous().Address()
	guard(cur.Previous().IsUser(), caller, m, n)
	m.checkMove(caller, phaseReveal, m.challenger, now)

	s := stateOf(rules, m)
	first := s.Round == 1
	bits := m.decks[0]
	if first {
		if deck == "" {
			panic("deck required")
		}
		checkSeal(m.deckSeal, deckSalt, deck)
		bits = deckBits(rules, rules.Clans[m.clans[0]-1], deck)
	} else if deck != "" || deckSalt != "" {
		panic("deck already revealed")
	}
	checkSeal(m.seal, planSalt, plan)
	a := planOf(rules, plan)
	if !legal(rules, s, engine.SideA, bits, a) {
		panic("illegal plan")
	}
	o := rules.Resolve(s, a, planAt(m.plans[1], s.Round))
	var box string
	if o.Result == engine.Ongoing {
		if nextSeal == "" {
			panic("next seal required")
		}
		if !validSeal(nextSeal) {
			panic("invalid seal")
		}
		box = boxBytes(nextBox)
	} else if nextSeal != "" || nextBox != "" {
		panic("unexpected next seal")
	}

	if first {
		m.decks[0] = bits
		m.deckSeal = ""
	}
	m.plans[0] = withPlan(m.plans[0], s.Round, a)
	for side, g := range o.State.Gnomes {
		m.hp[s.Round-1][side] = g.HP
		m.carried[side] = engine.Vitals{Vulnerable: g.Vulnerable, Strength: g.Strength}
	}
	m.seal, m.box = nextSeal, box
	if o.Result != engine.Ongoing {
		m.end(resultName(o.Result), reasonOf(o.State))
		saveMatch(rules, n, m)
		rate(rules, m)
		tellEnded(m, n, caller)
		return
	}
	m.phase = phasePlay
	m.deadline = now + moveWindow
	saveMatch(rules, n, m)
	hp := m.hp[s.Round-1]
	tell("Turn", m.acceptor, caller, n, "Round "+strconv.Itoa(s.Round)+" is over: you "+strconv.Itoa(hp[1])+
		" HP, them "+strconv.Itoa(hp[0])+". Your move within 24 hours.")
}

// Play records the acceptor's plan for the round being played.
func Play(cur realm, id, plan string) {
	rules := engine.ProofOfConcept()
	n, m := find(rules, id)
	now := time.Now().Unix()
	caller := cur.Previous().Address()
	guard(cur.Previous().IsUser(), caller, m, n)
	m.checkMove(caller, phasePlay, m.acceptor, now)
	s := stateOf(rules, m)
	b := planOf(rules, plan)
	if !legal(rules, s, engine.SideB, m.decks[1], b) {
		panic("illegal plan")
	}
	m.plans[1] = withPlan(m.plans[1], s.Round, b)
	m.phase = phaseReveal
	m.deadline = now + moveWindow
	saveMatch(rules, n, m)
	tell("Turn", m.challenger, caller, n, clanName(rules, m.clans[1])+" played round "+strconv.Itoa(s.Round)+". Your move within 24 hours.")
}

// Resign withdraws the caller's open challenge, expired or not, deleting it, or concedes
// a running match.
func Resign(cur realm, id string) {
	rules := engine.ProofOfConcept()
	n, m := find(rules, id)
	caller := cur.Previous().Address()
	guard(cur.Previous().IsUser(), caller, m, n)
	switch m.phase {
	case phaseOpen:
		if caller != m.challenger {
			panic("not your challenge")
		}
		openRemove(n)
		forget(n, m.challenger)
		tellBoard(n, "Challenge "+strconv.Itoa(n)+" was withdrawn.")
	case phaseReveal, phasePlay:
		switch caller {
		case m.challenger:
			m.end("b", "resign")
		case m.acceptor:
			m.end("a", "resign")
		default:
			panic("not a player")
		}
		saveMatch(rules, n, m)
		rate(rules, m)
		tellEnded(m, n, caller)
	default:
		panic("wrong phase")
	}
}

// ClaimForfeit ends a running match whose deadline has passed: the player who had to
// move loses. Any wallet may claim it; a session may claim only a match its wallet plays.
func ClaimForfeit(cur realm, id string) {
	rules := engine.ProofOfConcept()
	n, m := find(rules, id)
	caller := cur.Previous().Address()
	guard(cur.Previous().IsUser(), caller, m, n)
	var result string
	switch m.phase {
	case phaseReveal:
		result = "b"
	case phasePlay:
		result = "a"
	default:
		panic("wrong phase")
	}
	if time.Now().Unix() <= m.deadline {
		panic("deadline not passed")
	}
	m.end(result, "forfeit")
	saveMatch(rules, n, m)
	rate(rules, m)
	tellEnded(m, n, caller)
}

func find(rules *engine.Ruleset, id string) (int, record) {
	n, m, ok := lookup(rules, id)
	if !ok {
		panic("unknown match")
	}
	return n, m
}

// lookup returns the match id names, false when there is none. Only an id's own decimal
// text names it, never "01" or "+1".
func lookup(rules *engine.Ruleset, id string) (int, record, bool) {
	if len(id) == 0 || len(id) > idDigits {
		return 0, record{}, false
	}
	n, err := strconv.Atoi(id)
	if err != nil || strconv.Itoa(n) != id {
		return 0, record{}, false
	}
	m, ok := loadMatch(rules, n)
	return n, m, ok
}

func (m record) checkMove(caller address, phase string, mover address, now int64) {
	if m.phase != phase {
		panic("wrong phase")
	}
	if caller != mover {
		panic("not your move")
	}
	if now > m.deadline {
		panic("deadline passed")
	}
}

func (m *record) end(result, reason string) {
	m.phase = phaseEnded
	m.result = result
	m.reason = reason
	m.deckSeal, m.seal, m.box = "", "", ""
}

// stateOf rebuilds the engine state the next round of m starts from. A round is resolved
// once the challenger's plan for it is stored; the specials of resolved rounds are spent.
func stateOf(rules *engine.Ruleset, m record) engine.State {
	resolved := plansMade(m.plans[0])
	s := rules.Start()
	s.Round = resolved + 1
	for side := range s.Gnomes {
		g := &s.Gnomes[side]
		if resolved > 0 {
			g.HP = m.hp[resolved-1][side]
		}
		g.Vulnerable = m.carried[side].Vulnerable
		g.Strength = m.carried[side].Strength
		for round := 1; round <= resolved; round++ {
			for _, id := range planAt(m.plans[side], round) {
				if rules.Cards[id].Special {
					g.Spent |= uint64(1) << uint(id)
				}
			}
		}
	}
	return s
}

// checkSeal panics unless seal is the sha256 of salt's bytes followed by text.
func checkSeal(seal, salt, text string) {
	if !validSeal(salt) {
		panic("invalid salt")
	}
	b, _ := hex.DecodeString(salt)
	sum := sha256.Sum256(append(b, text...))
	if hex.EncodeToString(sum[:]) != seal {
		panic("seal mismatch")
	}
}

// clanNumber is clan's index in rules plus one, as a record stores it, or 0 when no clan
// has that name.
func clanNumber(rules *engine.Ruleset, clan string) int {
	for i, c := range rules.Clans {
		if c.Name == clan {
			return i + 1
		}
	}
	return 0
}

// clanName is the name of the clan a record stores as n, "" for none.
func clanName(rules *engine.Ruleset, n int) string {
	if n == 0 {
		return ""
	}
	return rules.Clans[n-1].Name
}

// planOf maps comma-separated card names to the engine's ids.
func planOf(rules *engine.Ruleset, text string) engine.Plan {
	p, ok := rules.PlanOf(strings.Split(text, ",")...)
	if !ok {
		panic("unknown card")
	}
	return p
}

// deckBits returns deck as the engine's bit set, panicking unless it is legal for c. A
// card named twice is illegal, so a legal deck text holds exactly the deck's names.
func deckBits(rules *engine.Ruleset, c engine.Clan, deck string) uint64 {
	var bits uint64
	for _, id := range planOf(rules, deck) {
		bit := uint64(1) << uint(id)
		if bits&bit != 0 {
			panic("illegal deck")
		}
		bits |= bit
	}
	if !rules.LegalDeck(c, bits) {
		panic("illegal deck")
	}
	return bits
}

func legal(rules *engine.Ruleset, s engine.State, side engine.Side, deck uint64, p engine.Plan) bool {
	for _, q := range rules.LegalPlans(s, side, deck) {
		if samePlan(p, q) {
			return true
		}
	}
	return false
}

func samePlan(p, q engine.Plan) bool {
	if len(p) != len(q) {
		return false
	}
	for i := range p {
		if p[i] != q[i] {
			return false
		}
	}
	return true
}

func resultName(r engine.Result) string {
	switch r {
	case engine.AWins:
		return "a"
	case engine.BWins:
		return "b"
	case engine.Draw:
		return "draw"
	}
	return ""
}

// reasonOf says why a finished match ended: a gnome at 0 HP or less is a knockout.
func reasonOf(s engine.State) string {
	if s.Gnomes[0].HP <= 0 || s.Gnomes[1].HP <= 0 {
		return "knockout"
	}
	return "hp"
}

query.gno

package arena

import (
	"encoding/base64"
	"strconv"
	"strings"
	"time"

	"gno.land/p/g188vafzutzvlfw6wt7u3s62xtuvm0epmu8ufmfz/gnomepit/engine"
	"gno.land/p/nt/avl/v0"
	"gno.land/r/sys/users"
)

// MatchSummary is one match as a player's list shows it. Round is the round being
// played, or the last one resolved once the match is over. ToMove is the address that
// must move next, empty when none. Deadline is the end of the current move's 24 hours,
// or the expiry of an open challenge, in Unix seconds. Opponent is the address an open
// challenge is reserved for, "" when anyone can accept it and once accepted.
type MatchSummary struct {
	ID, Phase                    string
	Round                        int
	Challenger, Acceptor         string
	ChallengerClan, AcceptorClan string
	ToMove                       string
	Deadline                     int64
	Result, Reason               string
	Opponent                     string
}

// MatchView is everything one match screen needs. Plans holds [challenger, acceptor]
// for each resolved round, and for the round being played while the match runs, ""
// while a plan is sealed or not yet made; HP holds both sides' HP after each resolved
// round; Box is the challenger's encrypted pending plan, in base64.
type MatchView struct {
	MatchSummary
	ChallengerDeck, AcceptorDeck string
	Plans                        [][]string
	Box                          string
	HP                           [][]int
	DeadlinePassed               bool
}

// SessionLock binds the session key at address Session to the match whose id is Match.
// Expires is the session's expiry in Unix seconds, 0 for none.
type SessionLock struct {
	Session, Match string
	Expires        int64
}

// Standing is one player's place on the ladder. Rank is 1 for the highest rating and
// equal ratings share it; Rank is 0 and Rating 1000 for a player with no rated match.
// Name is the player's gno.land name, "" without one. MainClan is "" until their
// first rated match.
type Standing struct {
	Rank                   int
	Player, Name, MainClan string
	Rating                 int
	Wins, Losses, Draws    int
}

// ClanStanding is one clan's record across rated cross-clan matches.
type ClanStanding struct {
	Rank                int
	Clan                string
	Rating              int
	Wins, Losses, Draws int
}

// Leaderboard lists rated players, highest rating first: limit of them after skipping offset.
func Leaderboard(offset, limit int) []Standing {
	checkPage(offset, limit)
	rules := engine.ProofOfConcept()
	list := []Standing{}
	ladder.TraverseByOffset(offset, limit, true, true, func(n *avl.Node) bool {
		s := standingOf(rules, address(n.Key()[2:]))
		switch {
		case len(list) == 0:
			s.Rank = rankOf(s.Rating)
		case list[len(list)-1].Rating == s.Rating:
			s.Rank = list[len(list)-1].Rank
		default:
			s.Rank = offset + len(list) + 1
		}
		list = append(list, s)
		return false
	})
	return list
}

// StandingOf returns player's standing, rated or not.
func StandingOf(player address) Standing {
	s := standingOf(engine.ProofOfConcept(), player)
	if s.MainClan != "" {
		s.Rank = rankOf(s.Rating)
	}
	return s
}

// RatedPlayers counts the players on the ladder.
func RatedPlayers() int {
	return ladder.Size()
}

// ClanStandings lists every clan of the ruleset, highest rating first; equal ratings keep
// ruleset order and share a rank.
func ClanStandings() []ClanStanding {
	rules := engine.ProofOfConcept()
	list := []ClanStanding{}
	for i, c := range decodeClans(clanRecords, len(rules.Clans)) {
		list = append(list, ClanStanding{Clan: rules.Clans[i].Name, Rating: c.rating, Wins: c.wins, Losses: c.losses, Draws: c.draws})
	}
	for i := 1; i < len(list); i++ {
		for j := i; j > 0 && list[j].Rating > list[j-1].Rating; j-- {
			list[j], list[j-1] = list[j-1], list[j]
		}
	}
	for i := range list {
		if i > 0 && list[i].Rating == list[i-1].Rating {
			list[i].Rank = list[i-1].Rank
		} else {
			list[i].Rank = i + 1
		}
	}
	return list
}

// standingOf is player's standing without its rank.
func standingOf(rules *engine.Ruleset, player address) Standing {
	s := Standing{Player: player.String(), Name: nameOf(player), Rating: startRating}
	st := loadStanding(player)
	if st == nil {
		return s
	}
	s.MainClan = clanName(rules, st.mainClan())
	s.Rating, s.Wins, s.Losses, s.Draws = st.rating, st.wins, st.losses, st.draws
	return s
}

// nameOf is player's gno.land name, "" when they have none.
func nameOf(player address) string {
	u := users.ResolveAddress(player)
	if u.IsDeleted() {
		return ""
	}
	return u.Name()
}

// Locks lists player's session locks. It can include locks whose session has expired.
func Locks(player address) []SessionLock {
	list := []SessionLock{}
	for _, l := range loadPlayer(player).locks {
		list = append(list, SessionLock{Session: l.session.String(), Match: strconv.Itoa(l.id), Expires: l.expires})
	}
	return list
}

// Matches lists player's matches, newest first: limit of them after skipping offset.
func Matches(player address, offset, limit int) []MatchSummary {
	checkPage(offset, limit)
	rules := engine.ProofOfConcept()
	now := time.Now().Unix()
	list := []MatchSummary{}
	for _, id := range loadPlayer(player).newest(offset, limit) {
		m, ok := loadMatch(rules, id)
		if !ok {
			continue
		}
		list = append(list, m.summary(rules, id, now))
	}
	return list
}

// Match returns the view of match id.
func Match(id string) MatchView {
	rules := engine.ProofOfConcept()
	n, m := find(rules, id)
	return m.view(rules, n, time.Now().Unix())
}

func (m record) view(rules *engine.Ruleset, id int, now int64) MatchView {
	v := MatchView{
		MatchSummary:   m.summary(rules, id, now),
		ChallengerDeck: deckText(rules, m.decks[0]),
		AcceptorDeck:   deckText(rules, m.decks[1]),
		Plans:          [][]string{},
		Box:            base64.StdEncoding.EncodeToString([]byte(m.box)),
		HP:             [][]int{},
		DeadlinePassed: m.running() && now > m.deadline,
	}
	resolved := plansMade(m.plans[0])
	rounds := resolved
	if m.running() {
		rounds++
	}
	for r := 1; r <= rounds; r++ {
		a := planText(rules, planAt(m.plans[0], r))
		b := planText(rules, planAt(m.plans[1], r))
		v.Plans = append(v.Plans, []string{a, b})
	}
	for r := 0; r < resolved; r++ {
		v.HP = append(v.HP, []int{m.hp[r][0], m.hp[r][1]})
	}
	return v
}

func (m record) summary(rules *engine.Ruleset, id int, now int64) MatchSummary {
	resolved := plansMade(m.plans[0])
	s := MatchSummary{
		ID:             strconv.Itoa(id),
		Phase:          m.phase,
		Round:          resolved + 1,
		Challenger:     m.challenger.String(),
		Acceptor:       m.acceptor.String(),
		ChallengerClan: clanName(rules, m.clans[0]),
		AcceptorClan:   clanName(rules, m.clans[1]),
		Result:         m.result,
		Reason:         m.reason,
		Opponent:       m.opponent.String(),
	}
	switch m.phase {
	case phaseOpen:
		s.Deadline = m.deadline
		if m.expired(now) {
			s.Phase = phaseExpired
		}
	case phaseReveal:
		s.ToMove = s.Challenger
		s.Deadline = m.deadline
	case phasePlay:
		s.ToMove = s.Acceptor
		s.Deadline = m.deadline
	case phaseEnded:
		if resolved > 0 {
			s.Round = resolved
		}
	}
	return s
}

func (m record) running() bool {
	return m.phase == phaseReveal || m.phase == phasePlay
}

// deckText names the cards of deck in card id order.
func deckText(rules *engine.Ruleset, deck uint64) string {
	var names []string
	for i := range rules.Cards {
		if deck&(uint64(1)<<uint(i)) != 0 {
			names = append(names, rules.Cards[i].Name)
		}
	}
	return strings.Join(names, ",")
}

// planText names the cards of p in play order.
func planText(rules *engine.Ruleset, p engine.Plan) string {
	names := make([]string, len(p))
	for i, id := range p {
		names[i] = rules.Cards[id].Name
	}
	return strings.Join(names, ",")
}

rating.gno

package arena

import "gno.land/p/g188vafzutzvlfw6wt7u3s62xtuvm0epmu8ufmfz/gnomepit/engine"

const (
	startRating = 1000
	maxRating   = 0xFFFF // a ladder key holds the rating in 2 bytes
	playerK     = 32
	clanK       = 16
)

// expectedTable is the expected score, in thousandths, of a side whose opponent is rated
// 0, 25, …, 400 points above it: 1 / (1 + 10^(d / 400)), rounded.
var expectedTable = [17]int{500, 464, 429, 394, 360, 327, 297, 267, 240, 215, 192, 170, 151, 133, 118, 104, 91}

// expected is the expected score, in thousandths, of a side rated a against one rated b.
// The gap is capped at 400 points and rounded to the nearest 25.
func expected(a, b int) int {
	d := b - a
	if d < 0 {
		return 1000 - expected(b, a)
	}
	if d > 400 {
		d = 400
	}
	return expectedTable[(d+12)/25]
}

// eloChange is the change, rounded to the nearest point, of a side rated a that scored
// score thousandths (1000 a win, 500 a draw, 0 a loss) against one rated b.
func eloChange(a, b, score, k int) int {
	x := k * (score - expected(a, b))
	if x < 0 {
		return -((-x + 500) / 1000)
	}
	return (x + 500) / 1000
}

// applyChange gives a the change delta and b its negative, each kept within 0 to maxRating.
func applyChange(a, b, delta int) (int, int) {
	return clampRating(a + delta), clampRating(b - delta)
}

func clampRating(r int) int {
	if r < 0 {
		return 0
	}
	if r > maxRating {
		return maxRating
	}
	return r
}

// rate counts match m, which has just ended, in both players' standings and on the
// ladder, and in the clan records when two different clans met. A match its challenger
// accepted is not rated.
func rate(rules *engine.Ruleset, m record) {
	if m.challenger == m.acceptor {
		return
	}
	score := scoreOf(m.result)
	a, b := ratedStanding(rules, m.challenger), ratedStanding(rules, m.acceptor)
	a.rating, b.rating = applyChange(a.rating, b.rating, eloChange(a.rating, b.rating, score, playerK))
	a.count(score, m.clans[0])
	b.count(1000-score, m.clans[1])
	ladder, _ = ladder.Set(ladderKey(a.rating, m.challenger), nil)
	ladder, _ = ladder.Set(ladderKey(b.rating, m.acceptor), nil)
	saveStanding(m.challenger, a)
	saveStanding(m.acceptor, b)

	if m.clans[0] == m.clans[1] {
		return
	}
	c := decodeClans(clanRecords, len(rules.Clans))
	ca, cb := &c[m.clans[0]-1], &c[m.clans[1]-1]
	ca.rating, cb.rating = applyChange(ca.rating, cb.rating, eloChange(ca.rating, cb.rating, score, clanK))
	tally(score, &ca.wins, &ca.losses, &ca.draws)
	tally(1000-score, &cb.wins, &cb.losses, &cb.draws)
	clanRecords = encodeClans(c)
}

// ratedStanding returns a's standing, created at startRating for a first rated match, with
// a count for every clan of rules, and takes its key off the ladder until it is counted.
func ratedStanding(rules *engine.Ruleset, a address) *standing {
	st := loadStanding(a)
	if st == nil {
		st = &standing{rating: startRating}
	} else {
		ladder, _, _, _ = ladder.Remove(ladderKey(st.rating, a))
	}
	for len(st.perClan) < len(rules.Clans) {
		st.perClan = append(st.perClan, 0)
	}
	return st
}

// scoreOf is the challenger's score, in thousandths, in a match that ended with result.
func scoreOf(result string) int {
	switch result {
	case "a":
		return 1000
	case "b":
		return 0
	case "draw":
		return 500
	}
	panic("unknown result")
}

// count adds a match scored score thousandths and played as clan number clan.
func (s *standing) count(score, clan int) {
	tally(score, &s.wins, &s.losses, &s.draws)
	s.lastClan = clan
	s.perClan[clan-1]++
}

func tally(score int, wins, losses, draws *int) {
	switch score {
	case 1000:
		*wins++
	case 0:
		*losses++
	default:
		*draws++
	}
}

// mainClan is the clan number s has finished the most rated matches with, 0 for none. A
// tie goes to the last match's clan when it is one of the tied, else to ruleset order.
func (s standing) mainClan() int {
	best := 0
	for i, n := range s.perClan {
		if n > 0 && (best == 0 || n > s.perClan[best-1]) {
			best = i + 1
		}
	}
	if best != 0 && s.lastClan >= 1 && s.lastClan <= len(s.perClan) && s.perClan[s.lastClan-1] == s.perClan[best-1] {
		return s.lastClan
	}
	return best
}

// rankOf is the rank a rating holds: 1 plus the number of players rated above it.
func rankOf(rating int) int {
	i, _, _ := ladder.Get(ladderKey(rating, ""))
	return i + 1
}

render.gno

package arena

import (
	"strconv"
	"strings"
	"time"

	"gno.land/p/g188vafzutzvlfw6wt7u3s62xtuvm0epmu8ufmfz/gnomepit/engine"
)

const notFound = "# Not found\n\nThe arena has no page at this path.\n"

// Render serves the board of open challenges at "", one player's matches at
// "player/<address>", and one match at "match/<id>".
func Render(path string) string {
	switch {
	case path == "":
		return renderBoard()
	case strings.HasPrefix(path, "player/"):
		player := address(strings.TrimPrefix(path, "player/"))
		if !canonical(player) {
			return notFound
		}
		return renderPlayer(player)
	case strings.HasPrefix(path, "match/"):
		rules := engine.ProofOfConcept()
		n, m, ok := lookup(rules, strings.TrimPrefix(path, "match/"))
		if !ok {
			return notFound
		}
		return renderMatch(m.view(rules, n, time.Now().Unix()))
	}
	return notFound
}

func renderBoard() string {
	var b strings.Builder
	b.WriteString("# Gnomepit arena\n\nOpen challenges, newest first.\n\n")
	list := Open(0, maxPage)
	if len(list) == 0 {
		b.WriteString("No open challenge.\n")
	}
	for _, c := range list {
		who := "open to anyone"
		if c.Opponent != "" {
			who = "reserved for " + c.Opponent
		}
		b.WriteString("- " + matchLink(c.ID) + ": " + c.Clan + ", posted by " + c.Challenger + ", " + who + ", expires " + date(c.Expires) + "\n")
	}
	return b.String()
}

func renderPlayer(player address) string {
	var b strings.Builder
	b.WriteString("# Matches of " + player.String() + "\n\n")
	list := Matches(player, 0, maxPage)
	if len(list) == 0 {
		b.WriteString("No match.\n")
	}
	for _, s := range list {
		b.WriteString("- " + matchLink(s.ID) + ": " + s.ChallengerClan + " against " + orNone(s.AcceptorClan) + ", " + s.Phase + "\n")
	}
	return b.String()
}

func renderMatch(v MatchView) string {
	var b strings.Builder
	b.WriteString("# Match " + v.ID + "\n\n")
	b.WriteString(v.ChallengerClan + " (" + v.Challenger + ") against " + orNone(v.AcceptorClan))
	if v.Acceptor != "" {
		b.WriteString(" (" + v.Acceptor + ")")
	}
	b.WriteString("\n\n")
	switch v.Phase {
	case phaseOpen:
		who := "open to anyone"
		if v.Opponent != "" {
			who = "reserved for " + v.Opponent
		}
		b.WriteString("Open challenge, " + who + ", until " + date(v.Deadline) + ".\n")
	case phaseReveal, phasePlay:
		b.WriteString("Round " + strconv.Itoa(v.Round) + ", waiting for " + v.ToMove + " until " + date(v.Deadline) + ".\n")
	case phaseEnded:
		b.WriteString("Over: " + outcome(v.Result, v.Reason) + ".\n")
	default:
		b.WriteString(strings.ToUpper(v.Phase[:1]) + v.Phase[1:] + ".\n")
	}
	if len(v.HP) > 0 {
		b.WriteString("\n| HP after | Challenger | Acceptor |\n|---|---|---|\n")
		for i, hp := range v.HP {
			b.WriteString("| Round " + strconv.Itoa(i+1) + " | " + strconv.Itoa(hp[0]) + " | " + strconv.Itoa(hp[1]) + " |\n")
		}
	}
	return b.String()
}

func outcome(result, reason string) string {
	winner := "the challenger won"
	switch result {
	case "b":
		winner = "the acceptor won"
	case "draw":
		winner = "a draw"
	}
	switch reason {
	case "hp":
		return winner + " on HP"
	case "knockout":
		return winner + " by knockout"
	case "resign":
		return winner + " by resignation"
	}
	return winner + " by forfeit"
}

func matchLink(id string) string {
	return "[Match " + id + "](" + strings.TrimPrefix(self, "gno.land") + ":match/" + id + ")"
}

func date(unix int64) string {
	return time.Unix(unix, 0).UTC().Format("2006-01-02 15:04 UTC")
}

func orNone(s string) string {
	if s == "" {
		return "nobody yet"
	}
	return s
}

store.gno

package arena

import (
	"encoding/binary"

	"gno.land/p/g188vafzutzvlfw6wt7u3s62xtuvm0epmu8ufmfz/gnomepit/engine"
	"gno.land/p/nt/avl/v0"
)

var (
	chunks      avl.Tree  // 4-byte chunk number → chunk string
	players     avl.Tree  // address → player string
	ladder      *avl.Node // ladderKey of every rated player → nil
	clanRecords string
	openList    string
)

func chunkKey(id int) string {
	var k [4]byte
	binary.BigEndian.PutUint32(k[:], uint32((id-1)/chunkSize))
	return string(k[:])
}

// loadMatch returns match id, or false when it does not exist or was removed.
func loadMatch(rules *engine.Ruleset, id int) (record, bool) {
	if id < 1 || id > lastID {
		return record{}, false
	}
	rec := chunkRecord(stringAt(&chunks, chunkKey(id)), (id-1)%chunkSize)
	if rec == "" {
		return record{}, false
	}
	return decodeMatch(rules, rec), true
}

func saveMatch(rules *engine.Ruleset, id int, m record) {
	putRecord(id, encodeMatch(rules, m))
}

// dropMatch removes match id; an absent id is left alone.
func dropMatch(id int) {
	if id < 1 {
		return
	}
	if chunkRecord(stringAt(&chunks, chunkKey(id)), (id-1)%chunkSize) != "" {
		putRecord(id, "")
	}
}

func putRecord(id int, rec string) {
	chunks.Set(chunkKey(id), withChunkRecord(stringAt(&chunks, chunkKey(id)), (id-1)%chunkSize, rec))
}

// stringAt returns the string under key, "" when there is none.
func stringAt(t *avl.Tree, key string) string {
	v := t.Get(key)
	if v == nil {
		return ""
	}
	return v.(string)
}

func loadPlayer(a address) playerRecord {
	return decodePlayer(stringAt(&players, string(a)))
}

func savePlayer(a address, p playerRecord) {
	players.Set(string(a), encodePlayer(p))
}

// loadStanding returns a's standing, nil before their first rated match.
func loadStanding(a address) *standing {
	return decodeStanding(stringAt(&players, string(a)))
}

func saveStanding(a address, st *standing) {
	players.Set(string(a), withStanding(stringAt(&players, string(a)), st))
}

// add appends id unless the player already has it.
func (p *playerRecord) add(id int) {
	for _, have := range p.ids {
		if have == id {
			return
		}
	}
	p.ids = append(p.ids, id)
}

func (p *playerRecord) remove(id int) {
	for i, have := range p.ids {
		if have == id {
			p.ids = append(p.ids[:i:i], p.ids[i+1:]...)
			return
		}
	}
}

// newest returns up to limit ids, newest first, after skipping offset of them.
func (p playerRecord) newest(offset, limit int) []int {
	var out []int
	for i := len(p.ids) - 1 - offset; i >= 0 && len(out) < limit; i-- {
		out = append(out, p.ids[i])
	}
	return out
}

// ceiling: each change rewrites the whole open list, 8 bytes per open challenge, so its gas
// grows with the board; an avl index keyed by expiry and id if the board holds thousands.
func openAdd(id int, expires int64) {
	openList += encodeOpen([]openEntry{{id: id, expires: expires}})
}

func openRemove(id int) {
	entries := openEntries(openList)
	for i, e := range entries {
		if e.id == id {
			openList = encodeOpen(append(entries[:i:i], entries[i+1:]...))
			return
		}
	}
}

// openNewest returns up to limit unexpired ids, newest first, after skipping offset of them.
func openNewest(now int64, offset, limit int) []int {
	entries := openEntries(openList)
	var out []int
	for i := len(entries) - 1; i >= 0 && entries[i].expires >= now; i-- {
		if offset > 0 {
			offset--
			continue
		}
		if len(out) == limit {
			break
		}
		out = append(out, entries[i].id)
	}
	return out
}

// openClear removes up to max expired entries from the front and returns their ids.
func openClear(now int64, max int) []int {
	entries := openEntries(openList)
	n := 0
	var ids []int
	for n < len(entries) && n < max && entries[n].expires < now {
		ids = append(ids, entries[n].id)
		n++
	}
	openList = encodeOpen(entries[n:])
	return ids
}