1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
//! Crabs: the spawner holes, the walking pass, and what happens when one
//! arrives somewhere - a castle, a turnstile, or a lure calling it home.
use super::*;
/// How often a mania's flood comes, in ticks.
const MANIA_EVERY: u64 = 8;
/// How many holes a mania's flood comes out of at a time, whatever the
/// beach has: the two the mania was sized on.
const MANIA_HOLES: usize = 2;
impl Board {
/// Place a crab directly (puzzle setups and tests; spawner tiles handle
/// the normal case). The crab immediately wall-resolves so it never starts
/// a tick facing a wall.
pub fn spawn_crab(&mut self, x: u8, y: u8, dir: Direction, handed: Handedness, kind: CrabKind) {
assert!(
self.in_bounds(i32::from(x), i32::from(y)),
"crab off the board"
);
let tile = self.index(i32::from(x), i32::from(y));
assert_ne!(
self.grid.tiles[tile as usize],
TileKind::Rock,
"crab on a rock"
);
let id = self.next_crab_id;
self.next_crab_id += 1;
let mut crab = Crab {
id,
tile,
dir,
progress: 0,
prev: Pose {
tile,
dir,
progress: 0,
},
handed,
kind,
};
self.resolve_walls(&mut crab);
self.crabs.push(crab);
}
/// Whether a golden crab can come out this round: rolled like any kind
/// where nobody calls one, and where one is called, only if the round
/// lasts past the earliest a call lands, a third of a stretch in. A
/// one-minute versus round is over on that tick, so it never has one.
pub fn golden_crab_can_come(&self) -> bool {
let every = u64::from(self.rules.golden_every);
every == 0
|| self
.rules
.round_length
.is_none_or(|len| every / 3 < u64::from(len))
}
/// Call the next golden crab at the start of each stretch, and send it
/// out of its hole on the tick it was called for, past the crab cap and
/// any mania: it was promised to the whole table.
pub(super) fn run_golden_call(&mut self) {
let every = u64::from(self.rules.golden_every);
if every == 0 {
return;
}
if let Some((at, tile)) = self.golden_call
&& at == self.tick
{
self.golden_call = None;
if let TileKind::Spawner(s) = self.grid.tiles[usize::from(tile)] {
let (x, y) = self.coords_u8(tile);
let handed = self.roll_handedness();
self.spawn_crab(x, y, s.dir, handed, CrabKind::Golden);
}
}
if !self.tick.is_multiple_of(every) {
return;
}
let holes: Vec<u16> = (0..self.grid.tiles.len())
.filter(|&t| matches!(self.grid.tiles[t], TileKind::Spawner(_)))
.map(|t| t as u16)
.collect();
if holes.is_empty() {
return;
}
let at = self.tick + every / 3 + u64::from(self.rng.next_u32()) % (every / 3).max(1);
let hole = holes[self.rng.next_u32() as usize % holes.len()];
let in_round = self
.rules
.round_length
.is_none_or(|len| at < u64::from(len));
self.golden_call = in_round.then_some((at, hole));
}
/// The holes that open this tick, in reading order. A mania overrides
/// each hole's cadence with a flood: every 8 ticks, the holes taking
/// turns two at a time. Every hole every 8 ticks made the flood as big
/// as the beach had holes, and a four-player table, with a hole for all
/// but one of them, flooded three times as fast as the two-hole beaches
/// the mania was sized on. Otherwise each hole keeps its own cadence,
/// at [`Self::hole_period`].
fn holes_opening(&self) -> Vec<usize> {
let holes = (0..self.grid.tiles.len())
.filter(|&t| matches!(self.grid.tiles[t], TileKind::Spawner(_)));
match self.tide.mania {
Some((Mania::Crab | Mania::Gull, _)) => {
let count = holes.clone().count();
let turns = count.div_ceil(MANIA_HOLES).max(1);
let turn = (self.tick / MANIA_EVERY) as usize % turns;
match self.tick.is_multiple_of(MANIA_EVERY) {
true => holes
.enumerate()
.filter(|(i, _)| i % turns == turn)
.map(|(_, t)| t)
.collect(),
false => Vec::new(),
}
}
None => holes
.filter(|&t| {
matches!(self.grid.tiles[t], TileKind::Spawner(s)
if self.tick.is_multiple_of(u64::from(self.hole_period(s.period))))
})
.collect(),
}
}
/// How many ticks apart a hole of cadence `period` opens right now:
/// twice as often while Speed Up runs. Walking faster alone changed
/// nothing a table could feel, since how much the beach scores is set
/// by how fast the holes fill it, not how fast it empties; doubling
/// the holes too gives the event its rush of crabs. The crab cap still
/// holds, so a full beach waits as it always does.
pub fn hole_period(&self, period: u32) -> u32 {
match self.tide.tempo {
Some((Tempo::Fast, _)) => (period / 2).max(1),
Some((Tempo::Slow, _)) | None => period,
}
}
/// How many live crabs the holes fill the beach to this tick. The beach
/// fills to the cap and then waits for it to clear. Crab Mania floods
/// past it, which is the event, but only to twice the cap, the same way
/// Gull Mania stops at three flocks: unbounded, it buried the board
/// under two crabs a tile.
fn crab_ceiling(&self) -> usize {
match self.tide.mania {
Some((Mania::Crab, _)) => self.crab_cap() * 2,
_ => self.crab_cap(),
}
}
/// Send a crab, or under Gull Mania a gull, out of each hole opening
/// this tick, while the beach is under its ceiling.
pub(super) fn run_spawners(&mut self) {
let mut open = self.holes_opening();
let ceiling = self.crab_ceiling();
// When the room left under the cap is less than the holes opening,
// which holes get it is drawn ([`Rules::fair_spawns`]). Only a tick
// that leaves a hole out draws, so a beach that never fills plays
// as it did in reading order.
let room = ceiling.saturating_sub(self.crabs.len());
if self.rules.fair_spawns
&& !matches!(self.tide.mania, Some((Mania::Gull, _)))
&& room > 0
&& room < open.len()
{
let first = self.rng.next_u32() as usize % open.len();
open.rotate_left(first);
}
for t in open {
let TileKind::Spawner(s) = self.grid.tiles[t] else {
continue;
};
if let Some((Mania::Gull, _)) = self.tide.mania {
// Balance: the mania flood is dramatic but bounded. Beyond
// three flocks' worth the beach becomes unplayable for the
// rest of the round (mania gulls only leave by raiding).
if self.gulls.len() < usize::from(self.rules.gull_cap) * 3 {
let (x, y) = self.coords(t as u16);
self.spawn_gull(x as u8, y as u8, s.dir);
}
continue;
}
if self.crabs.len() >= ceiling {
continue;
}
let handed = self.roll_handedness();
// Weighted kind mix so live boards show the whole population:
// mostly commons, a scattering of juveniles, the odd giant or
// molting crab, and once in a blue tide a golden jackpot.
//
// Molting is 3%, down from 4%, the point going to the commons:
// it is the only kind whose effect outlives the banking, so its
// rate and `LURE_COOLDOWN` set lure uptime together, and one in
// twenty-five kept the beach under a lure for a third of a
// round.
//
// Sparkling is 4%, up from 2%, the points coming from the
// commons: at one in fifty a round saw about two tide events,
// too few for the wheel to be a thing players play around.
let kind = match self.rng.next_u32() % 100 {
0..=67 => CrabKind::Common,
68..=82 => CrabKind::Juvenile,
83..=90 => CrabKind::Giant,
91..=93 => CrabKind::Molting,
// A board that calls its golden crabs never rolls one.
94..=95 if self.rules.golden_every > 0 => CrabKind::Common,
94..=95 => CrabKind::Golden,
96.. => CrabKind::Sparkling,
};
let id = self.next_crab_id;
self.next_crab_id += 1;
let mut crab = Crab {
id,
tile: t as u16,
dir: s.dir,
progress: 0,
prev: Pose {
tile: t as u16,
dir: s.dir,
progress: 0,
},
handed,
kind,
};
self.resolve_walls(&mut crab);
self.crabs.push(crab);
}
}
/// How many live crabs the ambient spawners will fill the beach to.
/// Proportional to the board, so an XL arena still feels busy and the
/// smallest puzzle board is not starved.
pub(super) fn crab_cap(&self) -> usize {
(self.grid.tiles.len() / CRAB_CAP_TILES_PER_CRAB).max(8)
}
pub(super) fn move_crabs(&mut self) {
// One board scan per tick, not one per crab arrival (refreshed on
// banks below, which is when a lure can start mid-tick).
let mut lure_target = self.lure_target();
let mut banked: Vec<usize> = Vec::new();
for i in 0..self.crabs.len() {
let mut crab = self.crabs[i];
crab.prev = crab.pose();
// Arrival resolution guarantees the exit direction is passable
// except for a crab sealed in on all four sides; that crab waits.
if !self.passable(crab.tile, crab.dir) {
self.crabs[i] = crab;
continue;
}
crab.progress += self.walk_step(crab.tile, crab.kind.speed());
let mut was_banked = false;
while crab.progress >= SUBUNITS_PER_TILE {
crab.progress -= SUBUNITS_PER_TILE;
crab.tile = self.neighbor(crab.tile, crab.dir);
if self.resolve_arrival(&mut crab, lure_target) {
was_banked = true;
// A molting bank starts a lure that later arrivals this
// same tick must already obey, as they always did.
lure_target = self.lure_target();
break;
}
}
if was_banked {
banked.push(i);
} else {
self.crabs[i] = crab;
}
}
// Remove back-to-front so earlier indices stay valid and the stable
// creature order (our fixed resolution order) is preserved.
for &i in banked.iter().rev() {
self.crabs.remove(i);
}
// Sparkling banks spin the roulette only now: events like Monopoly
// drain the crab list, which must not happen mid-iteration.
let queued = std::mem::take(&mut self.tide.queue);
for banker in queued {
self.spin_tide_event(banker);
}
}
/// Spec §4.1 resolution on arriving at a tile centre. Returns `true` if
/// the crab banked and must despawn.
///
/// Frozen decision for spec §9 open question 2: a signpost pointing into
/// a wall is *followed*, and wall resolution then applies from the
/// signpost's direction.
///
/// While a molting lure is active (spec §3.2), loose crabs ignore
/// signposts entirely and greedily head for the luring player's castle;
/// wall resolution still applies.
pub(super) fn resolve_arrival(&mut self, crab: &mut Crab, lure_target: Option<u16>) -> bool {
let t = crab.tile as usize;
if let TileKind::Castle(owner) = self.grid.tiles[t] {
let points = self.credit_bank(owner, crab);
self.walked_home.push(WalkedHome {
crab: crab.id,
owner,
tile: crab.tile,
points,
at: self.tick,
});
match crab.kind {
// A molt banked during a lure (anyone's) or in the quiet
// spell after one banks for its points and nothing more.
CrabKind::Molting => {
if self.lure_ready() {
self.lure = Some((owner, LURE_TICKS));
} else {
self.refused_lures.push(RefusedLure {
crab: crab.id,
running: self.lure.is_some(),
at: self.tick,
});
}
}
CrabKind::Sparkling => self.tide.queue.push(owner),
CrabKind::Golden | CrabKind::Common | CrabKind::Juvenile | CrabKind::Giant => {}
}
return true;
}
if self.turnstile_deflect(crab.tile, &mut crab.dir, crab.handed, Walker::Crab) {
return false;
}
if let Some(dir) = self.lure_step(crab.tile, lure_target) {
crab.dir = dir;
} else if let Some(sp) = self.signposts[t]
&& self.turns_crab(&sp, crab.handed)
{
crab.dir = sp.dir;
}
self.resolve_walls(crab);
false
}
/// One fair coin flip of the sim's PRNG stream.
pub(super) fn roll_handedness(&mut self) -> Handedness {
if self.rng.next_u32() & 1 == 0 {
Handedness::Left
} else {
Handedness::Right
}
}
/// The luring player's castle tile, if a lure is active and that player
/// still has a castle. Computed once per tick and threaded through
/// arrivals, so the board scan is not repeated per crab.
pub(super) fn lure_target(&self) -> Option<u16> {
let (owner, _) = self.lure?;
self.grid
.tiles
.iter()
.position(|t| *t == TileKind::Castle(owner))
.map(|t| t as u16)
}
/// Greedy step direction from `from` toward the cached lure target.
pub(super) fn lure_step(&self, from: u16, lure_target: Option<u16>) -> Option<Direction> {
let castle = lure_target?;
// On a wrapping board the short way may be through the seam.
let (dx, dy) = self.displacement(from, castle);
if dx == 0 && dy == 0 {
return None;
}
Some(Direction::toward(dx, dy))
}
}