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.

game.gno

9.02 Kb · 335 lines
  1// Package game is the match engine: the board, the coins and the rules for
  2// one turn. It has no idea where moves come from, so the arena and bot
  3// authors (for local testing) can both drive it.
  4//
  5// A game is stored compactly: the seed plus one byte per move. Everything
  6// else (positions, gold, coins, replays) is rebuilt from those, because the
  7// rules are deterministic. That keeps on-chain storage, which is paid per
  8// byte, to a few hundred bytes per match.
  9package game
 10
 11import (
 12	"strings"
 13
 14	"gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/bot"
 15)
 16
 17const (
 18	// CoinCount is how many coins a board starts with.
 19	CoinCount = 9
 20	// RespawnEvery is how often (in turns) a new mirrored pair of coins
 21	// appears, so the board never runs dry.
 22	RespawnEvery = 5
 23	// MaxCoins caps how many coins can be on the board at once.
 24	MaxCoins = 12
 25)
 26
 27// Game is one match in progress. Side 0 starts top-left, side 1 bottom-right.
 28type Game struct {
 29	Seed  int
 30	Turn  int
 31	CellA int    // side 0's square, as X*Size+Y
 32	CellB int    // side 1's square
 33	GoldA int    // side 0's gold
 34	GoldB int    // side 1's gold
 35	Coins string // one byte per coin still on the board, X*Size+Y
 36	Moves string // two bytes per turn played: side 0's action, side 1's action
 37}
 38
 39// Events is what happened in one turn besides the moves themselves.
 40type Events struct {
 41	Stole   [2]bool // side took a coin from the enemy with an attack
 42	Parried [2]bool // side defended against an attack and took a coin back
 43	Spawned int     // coins that appeared at the end of the turn
 44}
 45
 46// Snapshot is the board after some turn, for replays.
 47type Snapshot struct {
 48	Turn   int
 49	Pos    [2]bot.Pos
 50	Gold   [2]int
 51	Coins  []bot.Pos
 52	Act    [2]bot.Action // actions of this turn (zero at turn 0)
 53	Events Events        // what happened this turn
 54}
 55
 56func cell(p bot.Pos) int      { return p.X*bot.Size + p.Y }
 57func pos(c int) bot.Pos       { return bot.Pos{c / bot.Size, c % bot.Size} }
 58func coinByte(p bot.Pos) byte { return byte(cell(p)) }
 59
 60// New makes a board from seed. Coins are placed point-symmetric around the
 61// centre, so neither starting corner has an advantage.
 62func New(seed int) *Game {
 63	return &Game{
 64		Seed:  seed,
 65		CellA: cell(bot.Pos{0, 0}),
 66		CellB: cell(bot.Pos{bot.Size - 1, bot.Size - 1}),
 67		Coins: startCoins(seed),
 68	}
 69}
 70
 71func startCoins(seed int) string {
 72	mid := bot.Size / 2
 73	coins := []bot.Pos{{mid, mid}}
 74	r := uint32(seed)*2654435761 + 12345
 75	for len(coins) < CoinCount {
 76		r = r*1103515245 + 12345
 77		x := int((r >> 8) % bot.Size)
 78		r = r*1103515245 + 12345
 79		y := int((r >> 8) % bot.Size)
 80		p := bot.Pos{x, y}
 81		mirror := bot.Pos{bot.Size - 1 - x, bot.Size - 1 - y}
 82		if p == mirror || isCorner(p) || containsPos(coins, p) {
 83			continue
 84		}
 85		coins = append(coins, p, mirror)
 86	}
 87	var sb strings.Builder
 88	for _, c := range coins {
 89		sb.WriteByte(coinByte(c))
 90	}
 91	return sb.String()
 92}
 93
 94func isCorner(p bot.Pos) bool {
 95	return (p.X == 0 || p.X == bot.Size-1) && (p.Y == 0 || p.Y == bot.Size-1)
 96}
 97
 98func containsPos(ps []bot.Pos, p bot.Pos) bool {
 99	for _, q := range ps {
100		if q == p {
101			return true
102		}
103	}
104	return false
105}
106
107// Pos returns side's square.
108func (g *Game) Pos(side int) bot.Pos {
109	if side == 0 {
110		return pos(g.CellA)
111	}
112	return pos(g.CellB)
113}
114
115// Gold returns side's gold.
116func (g *Game) Gold(side int) int {
117	if side == 0 {
118		return g.GoldA
119	}
120	return g.GoldB
121}
122
123// CoinList returns the coins still on the board.
124func (g *Game) CoinList() []bot.Pos {
125	out := make([]bot.Pos, 0, len(g.Coins))
126	for i := 0; i < len(g.Coins); i++ {
127		out = append(out, pos(int(g.Coins[i])))
128	}
129	return out
130}
131
132// Over reports whether all turns have been played.
133func (g *Game) Over() bool { return g.Turn >= bot.Turns }
134
135// View is what side sees: a fresh copy of the board from its point of view.
136func (g *Game) View(matchID, side int) bot.State {
137	other := 1 - side
138	var last [2]bot.Action
139	if n := len(g.Moves); n >= 2 {
140		last = [2]bot.Action{bot.Action(g.Moves[n-2]), bot.Action(g.Moves[n-1])}
141	}
142	return bot.State{
143		Match:     matchID,
144		Turn:      g.Turn,
145		Me:        g.Pos(side),
146		Enemy:     g.Pos(other),
147		MyGold:    g.Gold(side),
148		EnemyGold: g.Gold(other),
149		Coins:     g.CoinList(),
150		MyLast:    last[side],
151		EnemyLast: last[other],
152	}
153}
154
155// Step plays one turn and reports what happened. The rules, in order:
156//  1. Invalid actions count as Stay.
157//  2. Fights, only when the two bots are adjacent:
158//     - Attack against anything but Defend steals one coin from the enemy.
159//     - Attack against Defend is parried: the defender takes one coin from
160//       the attacker instead.
161//     - Two attacks both land, so they cancel out.
162//     A bot with no gold has nothing to lose.
163//  3. Moves: both bots move at the same time, and never share a square. If
164//     both step onto the same square, the bot with priority this turn gets it
165//     (PriorityAt: side 0 on even turns, side 1 on odd turns) and the other
166//     stays put. A bot can't step into the other's square or swap with it.
167//  4. Pickup: a bot on a coin takes it.
168//  5. Every RespawnEvery turns a new mirrored pair of coins appears on free
169//     squares, up to MaxCoins on the board.
170func (g *Game) Step(a, b bot.Action) (ev Events) {
171	if g.Over() {
172		panic("game is over")
173	}
174	act := [2]bot.Action{a, b}
175	for i := range act {
176		if !act[i].Valid() {
177			act[i] = bot.Stay
178		}
179	}
180	p := [2]bot.Pos{g.Pos(0), g.Pos(1)}
181	gold := [2]int{g.GoldA, g.GoldB}
182
183	if bot.Adjacent(p[0], p[1]) {
184		var gain [2]int // coins each side takes from the other
185		for side := 0; side < 2; side++ {
186			other := 1 - side
187			if act[side] != bot.Attack {
188				continue
189			}
190			if act[other] == bot.Defend {
191				if gold[side] > 0 {
192					gain[other]++
193					ev.Parried[other] = true
194				}
195			} else if gold[other] > 0 {
196				gain[side]++
197				ev.Stole[side] = true
198			}
199		}
200		gold[0] += gain[0] - gain[1]
201		gold[1] += gain[1] - gain[0]
202	}
203
204	p = g.move(p, act)
205
206	coins := g.Coins
207	for side := 0; side < 2; side++ {
208		var got bool
209		if coins, got = takeCoin(coins, p[side]); got {
210			gold[side]++
211		}
212	}
213
214	g.CellA, g.CellB = cell(p[0]), cell(p[1])
215	g.GoldA, g.GoldB = gold[0], gold[1]
216	g.Moves += string([]byte{byte(act[0]), byte(act[1])})
217	g.Turn++
218	if g.Turn%RespawnEvery == 0 && g.Turn < bot.Turns {
219		before := len(coins)
220		coins = g.spawn(coins, p)
221		ev.Spawned = len(coins) - before
222	}
223	g.Coins = coins
224	return ev
225}
226
227// PriorityAt is the side that wins a contested square on turn t.
228func PriorityAt(t int) int { return t % 2 }
229
230// move resolves both moves so the bots never share a square.
231func (g *Game) move(p [2]bot.Pos, act [2]bot.Action) [2]bot.Pos {
232	t := [2]bot.Pos{bot.Apply(p[0], act[0]), bot.Apply(p[1], act[1])}
233	if t[0] == p[1] && t[1] == p[0] {
234		return p // swapping places: both blocked
235	}
236	if t[0] == t[1] {
237		// both want the same square, or one steps into a bot that stays
238		mover0, mover1 := t[0] != p[0], t[1] != p[1]
239		switch {
240		case mover0 && mover1:
241			loser := 1 - PriorityAt(g.Turn)
242			t[loser] = p[loser]
243		case mover0:
244			t[0] = p[0]
245		default:
246			t[1] = p[1]
247		}
248	}
249	// a bot stepping into the square the other one keeps is blocked
250	if t[0] == t[1] {
251		if t[0] != p[0] {
252			t[0] = p[0]
253		} else {
254			t[1] = p[1]
255		}
256	}
257	return t
258}
259
260// spawn adds one mirrored pair of coins on free squares, chosen from the seed
261// and the turn so replays are exact.
262func (g *Game) spawn(coins string, bots [2]bot.Pos) string {
263	if len(coins)+2 > MaxCoins {
264		return coins
265	}
266	r := uint32(g.Seed)*2654435761 + uint32(g.Turn)*40503 + 7
267	for tries := 0; tries < 30; tries++ {
268		r = r*1103515245 + 12345
269		x := int((r >> 8) % bot.Size)
270		r = r*1103515245 + 12345
271		y := int((r >> 8) % bot.Size)
272		p := bot.Pos{x, y}
273		m := bot.Pos{bot.Size - 1 - x, bot.Size - 1 - y}
274		if p == m || p == bots[0] || p == bots[1] || m == bots[0] || m == bots[1] {
275			continue
276		}
277		if strings.IndexByte(coins, coinByte(p)) >= 0 || strings.IndexByte(coins, coinByte(m)) >= 0 {
278			continue
279		}
280		return coins + string([]byte{coinByte(p), coinByte(m)})
281	}
282	return coins
283}
284
285func takeCoin(coins string, p bot.Pos) (string, bool) {
286	if i := strings.IndexByte(coins, coinByte(p)); i >= 0 {
287		return coins[:i] + coins[i+1:], true
288	}
289	return coins, false
290}
291
292// Winner returns 0 or 1 for the side with more gold, or -1 for a draw.
293func (g *Game) Winner() int {
294	switch {
295	case g.GoldA > g.GoldB:
296		return 0
297	case g.GoldB > g.GoldA:
298		return 1
299	}
300	return -1
301}
302
303// Timeline replays the match once and returns what happened on each turn:
304// element i is turn i+1.
305func (g *Game) Timeline() []Events {
306	r := New(g.Seed)
307	out := make([]Events, 0, g.Turn)
308	for i := 0; i < g.Turn; i++ {
309		out = append(out, r.Step(bot.Action(g.Moves[2*i]), bot.Action(g.Moves[2*i+1])))
310	}
311	return out
312}
313
314// At rebuilds the board after turn t (0 is the starting board) by replaying
315// the recorded moves on a fresh board with the same seed.
316func (g *Game) At(t int) Snapshot {
317	if t > g.Turn {
318		t = g.Turn
319	}
320	if t < 0 {
321		t = 0
322	}
323	r := New(g.Seed)
324	var s Snapshot
325	for i := 0; i < t; i++ {
326		a, b := bot.Action(g.Moves[2*i]), bot.Action(g.Moves[2*i+1])
327		s.Events = r.Step(a, b)
328		s.Act = [2]bot.Action{a, b}
329	}
330	s.Turn = t
331	s.Pos = [2]bot.Pos{r.Pos(0), r.Pos(1)}
332	s.Gold = [2]int{r.GoldA, r.GoldB}
333	s.Coins = r.CoinList()
334	return s
335}