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
//! 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::*;
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);
}
/// 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));
}
pub(super) fn run_spawners(&mut self) {
for t in 0..self.grid.tiles.len() {
let TileKind::Spawner(s) = self.grid.tiles[t] else {
continue;
};
// Manias override the cadence: floods every 8 ticks.
let period = match self.tide.mania {
Some((Mania::Crab | Mania::Gull, _)) => 8,
None => u64::from(s.period),
};
if !self.tick.is_multiple_of(period) {
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;
}
// 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.
let ceiling = match self.tide.mania {
Some((Mania::Crab, _)) => self.crab_cap() * 2,
_ => self.crab_cap(),
};
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.
let kind = match self.rng.next_u32() % 100 {
0..=69 => CrabKind::Common,
70..=84 => CrabKind::Juvenile,
85..=92 => CrabKind::Giant,
93..=95 => CrabKind::Molting,
// A board that calls its golden crabs never rolls one.
96..=97 if self.rules.golden_every > 0 => CrabKind::Common,
96..=97 => CrabKind::Golden,
98.. => 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] {
self.credit_bank(owner, crab);
self.crabs_banked += 1;
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.is_none() && self.lure_cooldown == 0 {
self.lure = Some((owner, LURE_TICKS));
}
}
CrabKind::Golden => self.golden_banked += 1,
CrabKind::Sparkling => self.tide.queue.push(owner),
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] {
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?;
let (fx, fy) = self.coords(from);
let (cx, cy) = self.coords(castle);
let (mut dx, mut dy) = (cx - fx, cy - fy);
if dx == 0 && dy == 0 {
return None;
}
// On a wrapping board the short way may be through the seam.
if self.wrap {
let (w, h) = (i32::from(self.width()), i32::from(self.height()));
if dx.abs() * 2 > w {
dx -= dx.signum() * w;
}
if dy.abs() * 2 > h {
dy -= dy.signum() * h;
}
}
Some(Direction::toward(dx, dy))
}
}