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.

play.gno

9.22 Kb · 359 lines
  1package arena
  2
  3import (
  4	"crypto/sha256"
  5	"encoding/hex"
  6	"strconv"
  7	"strings"
  8	"time"
  9
 10	"gno.land/p/nym-gfanton001/gnomepit/engine/v0"
 11)
 12
 13// Accept answers open challenge id as clan, with deck and the round-1 plan in plain
 14// text. When the challenge names an opponent, only that address may accept.
 15func Accept(cur realm, id, clan, deck, plan string) {
 16	mustBeOpen()
 17	rules := engine.ProofOfConcept()
 18	n, m := find(rules, id)
 19	now := time.Now().Unix()
 20	if m.phase != phaseOpen {
 21		panic("wrong phase")
 22	}
 23	if m.expired(now) {
 24		panic("challenge expired")
 25	}
 26	caller := cur.Previous().Address()
 27	if m.opponent != "" && caller != m.opponent {
 28		panic("not the named opponent")
 29	}
 30	c := clanNumber(rules, clan)
 31	if c == 0 {
 32		panic("unknown clan")
 33	}
 34	bits := deckBits(rules, rules.Clans[c-1], deck)
 35	b := planOf(rules, plan)
 36	if !legal(rules, stateOf(rules, m), engine.SideB, bits, b) {
 37		panic("illegal plan")
 38	}
 39
 40	m.acceptor = caller
 41	m.opponent = ""
 42	join(cur.Previous().IsUser(), caller, n)
 43	m.clans[1] = c
 44	m.decks[1] = bits
 45	m.plans[1] = withPlan(m.plans[1], 1, b)
 46	m.phase = phaseReveal
 47	m.deadline = now + moveWindow
 48	saveMatch(rules, n, m)
 49	openRemove(n)
 50	tellBoard(n, "Challenge "+strconv.Itoa(n)+" was taken.")
 51	tell("Turn", m.challenger, caller, n, clan+" accepted your challenge. Your move within 24 hours.")
 52}
 53
 54// Reveal opens the challenger's sealed plan for the round being played, and on the
 55// first reveal the sealed deck, then resolves the round. A match that goes on needs
 56// nextSeal and nextBox for the challenger's next plan; one that ends takes neither.
 57func Reveal(cur realm, id, deck, deckSalt, plan, planSalt, nextSeal, nextBox string) {
 58	rules := engine.ProofOfConcept()
 59	n, m := find(rules, id)
 60	now := time.Now().Unix()
 61	caller := cur.Previous().Address()
 62	guard(cur.Previous().IsUser(), caller, m, n)
 63	m.checkMove(caller, phaseReveal, m.challenger, now)
 64
 65	s := stateOf(rules, m)
 66	first := s.Round == 1
 67	bits := m.decks[0]
 68	if first {
 69		if deck == "" {
 70			panic("deck required")
 71		}
 72		checkSeal(m.deckSeal, deckSalt, deck)
 73		bits = deckBits(rules, rules.Clans[m.clans[0]-1], deck)
 74	} else if deck != "" || deckSalt != "" {
 75		panic("deck already revealed")
 76	}
 77	checkSeal(m.seal, planSalt, plan)
 78	a := planOf(rules, plan)
 79	if !legal(rules, s, engine.SideA, bits, a) {
 80		panic("illegal plan")
 81	}
 82	o := rules.Resolve(s, a, planAt(m.plans[1], s.Round))
 83	var box string
 84	if o.Result == engine.Ongoing {
 85		if nextSeal == "" {
 86			panic("next seal required")
 87		}
 88		if !validSeal(nextSeal) {
 89			panic("invalid seal")
 90		}
 91		box = boxBytes(nextBox)
 92	} else if nextSeal != "" || nextBox != "" {
 93		panic("unexpected next seal")
 94	}
 95
 96	if first {
 97		m.decks[0] = bits
 98		m.deckSeal = ""
 99	}
100	m.plans[0] = withPlan(m.plans[0], s.Round, a)
101	for side, g := range o.State.Gnomes {
102		m.hp[s.Round-1][side] = g.HP
103		m.carried[side] = engine.Vitals{Vulnerable: g.Vulnerable, Strength: g.Strength}
104	}
105	m.seal, m.box = nextSeal, box
106	if o.Result != engine.Ongoing {
107		m.end(resultName(o.Result), reasonOf(o.State))
108		saveMatch(rules, n, m)
109		report(cur, rules, m)
110		tellEnded(m, n, caller)
111		return
112	}
113	m.phase = phasePlay
114	m.deadline = now + moveWindow
115	saveMatch(rules, n, m)
116	hp := m.hp[s.Round-1]
117	tell("Turn", m.acceptor, caller, n, "Round "+strconv.Itoa(s.Round)+" is over: you "+strconv.Itoa(hp[1])+
118		" HP, them "+strconv.Itoa(hp[0])+". Your move within 24 hours.")
119}
120
121// Play records the acceptor's plan for the round being played.
122func Play(cur realm, id, plan string) {
123	rules := engine.ProofOfConcept()
124	n, m := find(rules, id)
125	now := time.Now().Unix()
126	caller := cur.Previous().Address()
127	guard(cur.Previous().IsUser(), caller, m, n)
128	m.checkMove(caller, phasePlay, m.acceptor, now)
129	s := stateOf(rules, m)
130	b := planOf(rules, plan)
131	if !legal(rules, s, engine.SideB, m.decks[1], b) {
132		panic("illegal plan")
133	}
134	m.plans[1] = withPlan(m.plans[1], s.Round, b)
135	m.phase = phaseReveal
136	m.deadline = now + moveWindow
137	saveMatch(rules, n, m)
138	tell("Turn", m.challenger, caller, n, clanName(rules, m.clans[1])+" played round "+strconv.Itoa(s.Round)+". Your move within 24 hours.")
139}
140
141// Resign withdraws the caller's open challenge, expired or not, deleting it, or concedes
142// a running match.
143func Resign(cur realm, id string) {
144	rules := engine.ProofOfConcept()
145	n, m := find(rules, id)
146	caller := cur.Previous().Address()
147	guard(cur.Previous().IsUser(), caller, m, n)
148	switch m.phase {
149	case phaseOpen:
150		if caller != m.challenger {
151			panic("not your challenge")
152		}
153		openRemove(n)
154		forget(n, m.challenger)
155		tellBoard(n, "Challenge "+strconv.Itoa(n)+" was withdrawn.")
156	case phaseReveal, phasePlay:
157		switch caller {
158		case m.challenger:
159			m.end("b", "resign")
160		case m.acceptor:
161			m.end("a", "resign")
162		default:
163			panic("not a player")
164		}
165		saveMatch(rules, n, m)
166		report(cur, rules, m)
167		tellEnded(m, n, caller)
168	default:
169		panic("wrong phase")
170	}
171}
172
173// ClaimForfeit ends a running match whose deadline has passed: the player who had to
174// move loses. Any wallet may claim it; a session may claim only a match its wallet plays.
175func ClaimForfeit(cur realm, id string) {
176	rules := engine.ProofOfConcept()
177	n, m := find(rules, id)
178	caller := cur.Previous().Address()
179	guard(cur.Previous().IsUser(), caller, m, n)
180	var result string
181	switch m.phase {
182	case phaseReveal:
183		result = "b"
184	case phasePlay:
185		result = "a"
186	default:
187		panic("wrong phase")
188	}
189	if time.Now().Unix() <= m.deadline {
190		panic("deadline not passed")
191	}
192	m.end(result, "forfeit")
193	saveMatch(rules, n, m)
194	report(cur, rules, m)
195	tellEnded(m, n, caller)
196}
197
198func find(rules *engine.Ruleset, id string) (int, record) {
199	n, m, ok := lookup(rules, id)
200	if !ok {
201		panic("unknown match")
202	}
203	return n, m
204}
205
206// lookup returns the match id names, false when there is none. Only an id's own decimal
207// text names it, never "01" or "+1".
208func lookup(rules *engine.Ruleset, id string) (int, record, bool) {
209	if len(id) == 0 || len(id) > idDigits {
210		return 0, record{}, false
211	}
212	n, err := strconv.Atoi(id)
213	if err != nil || strconv.Itoa(n) != id {
214		return 0, record{}, false
215	}
216	m, ok := loadMatch(rules, n)
217	return n, m, ok
218}
219
220func (m record) checkMove(caller address, phase string, mover address, now int64) {
221	if m.phase != phase {
222		panic("wrong phase")
223	}
224	if caller != mover {
225		panic("not your move")
226	}
227	if now > m.deadline {
228		panic("deadline passed")
229	}
230}
231
232func (m *record) end(result, reason string) {
233	m.phase = phaseEnded
234	m.result = result
235	m.reason = reason
236	m.deckSeal, m.seal, m.box = "", "", ""
237}
238
239// stateOf rebuilds the engine state the next round of m starts from. A round is resolved
240// once the challenger's plan for it is stored; the specials of resolved rounds are spent.
241func stateOf(rules *engine.Ruleset, m record) engine.State {
242	resolved := plansMade(m.plans[0])
243	s := rules.Start()
244	s.Round = resolved + 1
245	for side := range s.Gnomes {
246		g := &s.Gnomes[side]
247		if resolved > 0 {
248			g.HP = m.hp[resolved-1][side]
249		}
250		g.Vulnerable = m.carried[side].Vulnerable
251		g.Strength = m.carried[side].Strength
252		for round := 1; round <= resolved; round++ {
253			for _, id := range planAt(m.plans[side], round) {
254				if rules.Cards[id].Special {
255					g.Spent |= uint64(1) << uint(id)
256				}
257			}
258		}
259	}
260	return s
261}
262
263// checkSeal panics unless seal is the sha256 of salt's bytes followed by text.
264func checkSeal(seal, salt, text string) {
265	if !validSeal(salt) {
266		panic("invalid salt")
267	}
268	b, _ := hex.DecodeString(salt)
269	sum := sha256.Sum256(append(b, text...))
270	if hex.EncodeToString(sum[:]) != seal {
271		panic("seal mismatch")
272	}
273}
274
275// clanNumber is clan's index in rules plus one, as a record stores it, or 0 when no clan
276// has that name.
277func clanNumber(rules *engine.Ruleset, clan string) int {
278	for i, c := range rules.Clans {
279		if c.Name == clan {
280			return i + 1
281		}
282	}
283	return 0
284}
285
286// clanName is the name of the clan a record stores as n, "" for none.
287func clanName(rules *engine.Ruleset, n int) string {
288	if n == 0 {
289		return ""
290	}
291	return rules.Clans[n-1].Name
292}
293
294// planOf maps comma-separated card names to the engine's ids.
295func planOf(rules *engine.Ruleset, text string) engine.Plan {
296	p, ok := rules.PlanOf(strings.Split(text, ",")...)
297	if !ok {
298		panic("unknown card")
299	}
300	return p
301}
302
303// deckBits returns deck as the engine's bit set, panicking unless it is legal for c. A
304// card named twice is illegal, so a legal deck text holds exactly the deck's names.
305func deckBits(rules *engine.Ruleset, c engine.Clan, deck string) uint64 {
306	var bits uint64
307	for _, id := range planOf(rules, deck) {
308		bit := uint64(1) << uint(id)
309		if bits&bit != 0 {
310			panic("illegal deck")
311		}
312		bits |= bit
313	}
314	if !rules.LegalDeck(c, bits) {
315		panic("illegal deck")
316	}
317	return bits
318}
319
320func legal(rules *engine.Ruleset, s engine.State, side engine.Side, deck uint64, p engine.Plan) bool {
321	for _, q := range rules.LegalPlans(s, side, deck) {
322		if samePlan(p, q) {
323			return true
324		}
325	}
326	return false
327}
328
329func samePlan(p, q engine.Plan) bool {
330	if len(p) != len(q) {
331		return false
332	}
333	for i := range p {
334		if p[i] != q[i] {
335			return false
336		}
337	}
338	return true
339}
340
341func resultName(r engine.Result) string {
342	switch r {
343	case engine.AWins:
344		return "a"
345	case engine.BWins:
346		return "b"
347	case engine.Draw:
348		return "draw"
349	}
350	return ""
351}
352
353// reasonOf says why a finished match ended: a gnome at 0 HP or less is a knockout.
354func reasonOf(s engine.State) string {
355	if s.Gnomes[0].HP <= 0 || s.Gnomes[1].HP <= 0 {
356		return "knockout"
357	}
358	return "hp"
359}