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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! The determinism fingerprint (spec §7.5).
use super::*;
impl Board {
/// Fingerprint of the complete simulation state, in a fixed field order.
/// Two boards fed the same seed and inputs must agree on this after every
/// tick, on every platform: the determinism contract of spec §7.5.
pub fn state_hash(&self) -> u64 {
// A census of every field, exhaustive on purpose and with no rest
// pattern, so adding one to `Board` stops compiling until it is
// either hashed below or named here as deliberately left out. A
// field that escapes the fingerprint is a desync no peer can see:
// both sides play differently and both report agreement, which is
// how `lure_cooldown` escaped.
let Self {
// hash_terrain
grid:
Grid {
width: _,
height: _,
h_walls: _,
v_walls: _,
tiles: _,
},
signposts: _,
// hash_creatures
crabs: _,
scores: _,
rng: _,
gulls: _,
next_gull_id: _,
// hash_round
tick: _,
signpost_seq: _,
next_crab_id: _,
rules:
Rules {
signpost_cap: _,
cap_policy: _,
gull_period: _,
gull_cap: _,
gull_turnover: _,
golden_every: _,
timed_lock: _,
sweep_flight: _,
round_length: _,
castle_raids: _,
},
lure: _,
lure_cooldown: _,
crabs_banked: _,
golden_banked: _,
golden_call: _,
tide:
events::Tide {
enabled: _,
cooldown: _,
mania: _,
tempo: _,
claw_call: _,
last: _,
// Outside, with the others below.
queue: _,
spun_by: _,
},
wrap: _,
// Outside the fingerprint, each for a reason of its own: the
// construction seed is dead once the PRNG state (which *is*
// hashed) has been derived from it; the event queue is filled
// and drained inside a single tick, so it is always empty by
// the time anyone hashes; who spun the wheel is for the
// trophies and never read by the sim; and the swept-home record is written
// for the render layer and never read back by the sim, so
// hashing it would only make this build disagree with builds
// playing the same round.
seed: _,
swept_home: _,
// hash_round, at its tail
sweeping: _,
} = self;
let mut h = Fnv::new();
self.hash_terrain(&mut h);
self.hash_creatures(&mut h);
self.hash_round(&mut h);
h.finish()
}
/// The board itself: size, walls, tiles, signposts. Field order is part
/// of the contract: never reorder these, only append.
fn hash_terrain(&self, h: &mut Fnv) {
h.u8(self.grid.width);
h.u8(self.grid.height);
for &wall in &self.grid.h_walls {
h.bool(wall);
}
for &wall in &self.grid.v_walls {
h.bool(wall);
}
for tile in &self.grid.tiles {
match *tile {
TileKind::Empty => h.u8(0),
TileKind::Rock => h.u8(1),
TileKind::Castle(owner) => {
h.u8(2);
h.u8(owner);
}
TileKind::Spawner(s) => {
h.u8(3);
h.u8(s.dir.id());
h.u32(s.period);
}
TileKind::Turnstile { next_right } => {
h.u8(4);
h.bool(next_right);
}
TileKind::Kelp => h.u8(5),
TileKind::Pool => h.u8(6),
}
}
for slot in &self.signposts {
match slot {
None => h.u8(0),
Some(sp) => {
h.u8(1);
h.u8(sp.dir.id());
h.u8(sp.owner);
h.u8(match sp.health {
SignpostHealth::Full => 0,
SignpostHealth::Worn => 1,
});
h.u64(sp.seq);
h.u64(sp.placed);
}
}
}
}
/// Everything alive, the scores they are chasing, and the PRNG that
/// drives them.
fn hash_creatures(&self, h: &mut Fnv) {
for crab in &self.crabs {
h.u32(crab.id);
h.u16(crab.tile);
h.u8(crab.dir.id());
h.u16(crab.progress);
h.u16(crab.prev.tile);
h.u16(crab.prev.progress);
h.u8(crab.prev.dir.id());
h.u8(crab.handed.id());
h.u8(crab.kind.id());
}
for &score in &self.scores {
h.u32(score);
}
let (state, inc) = self.rng.hash_state();
h.u64(state);
h.u64(inc);
for gull in &self.gulls {
h.u32(gull.id);
h.u16(gull.tile);
h.u8(gull.dir.id());
h.u16(gull.progress);
h.u16(gull.prev.tile);
h.u16(gull.prev.progress);
h.u8(gull.prev.dir.id());
h.u8(gull.handed.id());
match gull.state {
GullState::Walking => h.u8(0),
GullState::Flying { remaining } => {
h.u8(1);
h.u8(remaining);
}
}
h.u32(gull.takeoff_in);
}
h.u32(self.next_gull_id);
}
/// The round's own state: the tide, the active tide effects, and the
/// counters that outlive a single creature.
fn hash_round(&self, h: &mut Fnv) {
h.u32(self.rules.gull_period);
h.u8(self.rules.gull_cap);
h.u8(u8::from(self.rules.gull_turnover));
match self.rules.round_length {
None => h.u8(0),
Some(len) => {
h.u8(1);
h.u32(len);
}
}
match self.lure {
None => h.u8(0),
Some((p, t)) => {
h.u8(1);
h.u8(p);
h.u32(t);
}
}
h.u32(self.golden_banked);
h.u32(self.rules.golden_every);
h.u8(u8::from(self.rules.timed_lock));
match self.golden_call {
None => h.u8(0),
Some((at, tile)) => {
h.u8(1);
h.u64(at);
h.u16(tile);
}
}
h.bool(self.rules.castle_raids);
h.bool(self.tide.enabled);
h.bool(self.wrap);
match self.tide.mania {
None => h.u8(0),
Some((Mania::Crab, t)) => {
h.u8(1);
h.u32(t);
}
Some((Mania::Gull, t)) => {
h.u8(2);
h.u32(t);
}
}
match self.tide.tempo {
None => h.u8(0),
Some((tempo, t)) => {
h.u8(match tempo {
Tempo::Fast => 1,
Tempo::Slow => 2,
});
h.u32(t);
}
}
h.u32(self.tide.claw_call);
match self.tide.last {
None => h.u8(0),
Some((event, tick)) => {
// ALL's position, not the declaration discriminant: every
// stable meaning of an event (roulette, snapshot, strings)
// reads off ALL, and the hash follows the same order.
h.u8(1 + event.index() as u8);
h.u64(tick);
}
}
h.u64(self.tick);
h.u64(self.signpost_seq);
h.u32(self.next_crab_id);
h.u32(self.crabs_banked);
h.u8(self.rules.signpost_cap);
h.u8(match self.rules.cap_policy {
CapPolicy::Evict => 0,
CapPolicy::Reject => 1,
});
// The quiet spell after a lure. Appended here rather than slotted
// in beside `lure`, where it belongs by meaning, because field
// order is the format and only the tail is safe to grow.
h.u32(self.lure_cooldown);
h.u32(self.tide.cooldown);
// Crab Monopoly's crabs in the air: live state that decides whose
// score moves on which tick.
h.u8(u8::from(self.rules.sweep_flight));
h.u32(self.sweeping.len() as u32);
for flight in &self.sweeping {
let crab = &flight.crab;
h.u32(crab.id);
h.u16(crab.tile);
h.u8(crab.dir.id());
h.u16(crab.progress);
h.u16(crab.prev.tile);
h.u16(crab.prev.progress);
h.u8(crab.prev.dir.id());
h.u8(crab.handed.id());
h.u8(crab.kind.id());
h.u8(flight.owner);
h.u64(flight.launch);
h.u64(flight.lands);
}
}
}
#[cfg(test)]
mod tests {
use crate::sim::{Board, CapPolicy, CrabKind, Direction, Handedness, Spawner, TileKind};
/// Every externally-reachable mutator must move the hash: a field that
/// escapes `state_hash` is a silent online-desync blind spot.
#[test]
fn every_mutator_changes_the_hash() {
let base = || Board::new(8, 6, 42);
type Mutation = (&'static str, Box<dyn Fn(&mut Board)>);
let mutations: Vec<Mutation> = vec![
("set_tile", Box::new(|b| b.set_tile(2, 2, TileKind::Rock))),
(
"set_spawner",
Box::new(|b| {
b.set_tile(
3,
3,
TileKind::Spawner(Spawner {
dir: Direction::Right,
period: 40,
}),
);
}),
),
(
"set_wall",
Box::new(|b| b.set_wall(1, 1, Direction::Up, true)),
),
("set_wrap", Box::new(|b| b.set_wrap(true))),
("set_score", Box::new(|b| b.set_score(0, 7))),
("set_gull_period", Box::new(|b| b.set_gull_period(99))),
("set_gull_cap", Box::new(|b| b.set_gull_cap(9))),
("set_gull_turnover", Box::new(|b| b.set_gull_turnover(true))),
("set_golden_every", Box::new(|b| b.set_golden_every(600))),
("set_timed_lock", Box::new(|b| b.set_timed_lock(true))),
("set_sweep_flight", Box::new(|b| b.set_sweep_flight(true))),
(
"set_round_length",
Box::new(|b| b.set_round_length(Some(500))),
),
(
"set_events_enabled",
Box::new(|b| b.set_events_enabled(true)),
),
("set_castle_raids", Box::new(|b| b.set_castle_raids(false))),
(
"set_signpost_rule",
Box::new(|b| b.set_signpost_rule(5, CapPolicy::Reject)),
),
(
"place_signpost",
Box::new(|b| {
b.place_signpost(0, 4, 4, Direction::Left);
}),
),
(
"spawn_crab",
Box::new(|b| {
b.spawn_crab(2, 3, Direction::Up, Handedness::Left, CrabKind::Common);
}),
),
(
"spawn_gull",
Box::new(|b| b.spawn_gull(5, 2, Direction::Down)),
),
("tick_idle", Box::new(Board::tick_idle)),
];
let clean = base().state_hash();
for (name, mutate) in mutations {
let mut board = base();
mutate(&mut board);
assert_ne!(board.state_hash(), clean, "{name} did not move state_hash");
}
}
/// State reachable only by ticking, which the mutator census above
/// cannot see. The lure cooldown decides whether banking a molt starts
/// a lure at all, so unhashed, two boards sit at the same fingerprint
/// and then play the round differently.
#[test]
fn the_lure_cooldown_is_part_of_the_fingerprint() {
use crate::sim::{MAX_PLAYERS, PlayerAction};
let armed = |cooldown: u32| {
let mut board = Board::new(6, 5, 1);
board.set_tile(3, 2, TileKind::Castle(0));
board.lure_cooldown = cooldown;
board.spawn_crab(2, 2, Direction::Right, Handedness::Right, CrabKind::Molting);
board
};
let (mut quiet, mut ready) = (armed(200), armed(0));
assert_ne!(
quiet.state_hash(),
ready.state_hash(),
"a cooldown that changes the round has to change the hash"
);
for board in [&mut quiet, &mut ready] {
for _ in 0..40 {
board.tick(&[PlayerAction::None; MAX_PLAYERS]);
}
}
assert!(quiet.lure().is_none(), "the quiet spell swallows the lure");
assert!(ready.lure().is_some(), "a clear board starts one");
}
/// The same trap, one field along. `event_cooldown` decides whether
/// banking a Sparkling crab spins the roulette at all, so two boards
/// holding different ones play the round apart, and the census above
/// only forces a new field to be *named*, not hashed. Removing the
/// `h.u32` for this field passes every other test in the suite.
#[test]
fn the_event_cooldown_is_part_of_the_fingerprint() {
use crate::sim::{MAX_PLAYERS, PlayerAction};
let armed = |cooldown: u32| {
let mut board = Board::new(6, 5, 1);
board.set_events_enabled(true);
board.set_tile(3, 2, TileKind::Castle(0));
board.tide.cooldown = cooldown;
board.spawn_crab(
2,
2,
Direction::Right,
Handedness::Right,
CrabKind::Sparkling,
);
board
};
let (mut quiet, mut ready) = (armed(200), armed(0));
assert_ne!(
quiet.state_hash(),
ready.state_hash(),
"a cooldown that changes the round has to change the hash"
);
for board in [&mut quiet, &mut ready] {
for _ in 0..40 {
board.tick(&[PlayerAction::None; MAX_PLAYERS]);
}
}
assert!(
quiet.last_event().is_none(),
"the cooldown swallows the spin"
);
assert!(
ready.last_event().is_some(),
"a clear board spins the wheel"
);
}
}