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
431
432
433
434
435
436
//! What one tick did, read off the board before and after it: which crabs
//! banked and for whom, which were eaten, which castles were raided, which
//! signposts wore or went. The standings count it and `simulate` reports it.
//!
//! Read from the outside rather than recorded by the sim, which keeps no
//! such log: the sim's state is exactly what its hash covers, and a record
//! nothing in the sim reads would be a field for nothing.
use crate::sim::{
Board, CrabKind, Direction, Handedness, MAX_PLAYERS, PlayerId, SignpostHealth, TileKind,
};
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Happened {
Banked {
crab: u32,
owner: PlayerId,
x: u8,
y: u8,
},
Eaten {
crab: u32,
x: u8,
y: u8,
},
Raided {
owner: PlayerId,
lost: u32,
},
PostWorn {
x: u8,
y: u8,
owner: PlayerId,
},
PostGone {
x: u8,
y: u8,
owner: PlayerId,
},
}
/// A crab as a diff needs it.
#[derive(Clone, Copy)]
struct Seen {
id: u32,
tile: u16,
dir: Direction,
progress: u16,
handed: Handedness,
kind: CrabKind,
}
/// The parts of a board a diff needs, taken before a tick.
pub struct Before {
/// In the board's own order, which is the order the tick moves them.
crabs: Vec<Seen>,
posts: Vec<(u8, u8, PlayerId, SignpostHealth, u64)>,
scores: [u32; MAX_PLAYERS],
banked: u32,
claw_call: bool,
/// Every castle and its owner, as the tick found them. A crab banks
/// for the owner of the moment it walks in, and a Castle Swap its
/// sparkling crab spins later in the same tick hands that castle on:
/// read after, the bank went to the wrong seat and the seat it did go
/// to showed a raid nobody made.
castles: Vec<((u8, u8), PlayerId)>,
}
impl Before {
pub fn of(board: &Board) -> Before {
Before {
// A crab Crab Monopoly is carrying home is still in play: it
// is gone, banked, on the tick it lands.
crabs: board
.crabs()
.iter()
.chain(board.sweeping().iter().map(|flight| &flight.crab))
.map(|c| Seen {
id: c.id,
tile: c.tile,
dir: c.dir,
progress: c.progress,
handed: c.handed,
kind: c.kind,
})
.collect(),
posts: board
.signposts()
.map(|(x, y, p)| (x, y, p.owner, p.health, p.placed))
.collect(),
scores: *board.scores(),
banked: board.crabs_banked(),
claw_call: board.in_claw_call(),
castles: board
.tiles()
.filter_map(|(x, y, kind)| match kind {
TileKind::Castle(owner) => Some(((x, y), owner)),
TileKind::Empty
| TileKind::Rock
| TileKind::Spawner(_)
| TileKind::Turnstile { .. }
| TileKind::Kelp
| TileKind::Pool => None,
})
.collect(),
}
}
/// What happened between this reading and `after`.
///
/// A crab that is gone banked if the tide swept it home, or if the
/// castle is the tile it stood on or the one it was walking into: a
/// crab moves at most a tile a tick, and banks by stepping into a
/// castle. Being next to a castle whose score went up is not that, and
/// a score is no witness anyway (Right Claws can bank a crab for
/// nothing). If more crabs were walking in than the board says banked,
/// the ones furthest along made it and the rest were eaten short of
/// the door.
pub fn diff(&self, after: &Board, out: &mut Vec<Happened>) {
let alive: std::collections::HashSet<u32> = after
.crabs()
.iter()
.chain(after.sweeping().iter().map(|flight| &flight.crab))
.map(|c| c.id)
.collect();
let gone: Vec<&Seen> = self
.crabs
.iter()
.filter(|c| !alive.contains(&c.id))
.collect();
let swept = gone
.iter()
.filter(|c| after.swept_home(c.id).is_some())
.count() as u32;
let walked_in = after
.crabs_banked()
.saturating_sub(self.banked)
.saturating_sub(swept) as usize;
let mut walking: Vec<(&Seen, PlayerId, (u8, u8))> = gone
.iter()
.filter(|c| after.swept_home(c.id).is_none())
.filter_map(|c| {
self.castle_entered(after, c)
.map(|(owner, at)| (*c, owner, at))
})
.collect();
if walking.len() > walked_in {
walking.sort_by_key(|(c, ..)| std::cmp::Reverse(c.progress));
walking.truncate(walked_in);
}
// What the banks alone would leave each score at, credited in the
// order the tick credits them: the walkers as they arrive, then
// the tide's sweep.
let mut expected = self.scores;
let mut credit = |owner: PlayerId, points: i32| {
if let Some(score) = expected.get_mut(usize::from(owner)) {
*score = score.saturating_add_signed(points);
}
};
let walked_points = |crab: &Seen| worth(crab, after.crab_value(crab.kind), self.claw_call);
let mut reports: Vec<(u32, Happened)> = Vec::new();
for crab in &gone {
let (x, y) = after.coords_u8(crab.tile);
if let Some(&(_, owner, (x, y))) = walking.iter().find(|(c, ..)| c.id == crab.id) {
credit(owner, walked_points(crab));
reports.push((
crab.id,
Happened::Banked {
crab: crab.id,
owner,
x,
y,
},
));
} else if after.swept_home(crab.id).is_none() {
reports.push((
crab.id,
Happened::Eaten {
crab: crab.id,
x,
y,
},
));
}
}
for crab in &gone {
if let Some(owner) = after.swept_home(crab.id) {
// Priced by the sim, which paid it under the claw call it
// was swept under rather than the one running now.
let points = after
.swept_paid(crab.id)
.unwrap_or_else(|| walked_points(crab));
credit(owner, points);
let (x, y) = after
.castle_of(owner)
.unwrap_or_else(|| after.coords_u8(crab.tile));
reports.push((
crab.id,
Happened::Banked {
crab: crab.id,
owner,
x,
y,
},
));
}
}
reports.sort_by_key(|(id, _)| *id);
out.extend(reports.into_iter().map(|(_, what)| what));
// Whatever the banks do not account for, a gull carried off.
for (seat, (&was, &now)) in expected.iter().zip(after.scores()).enumerate() {
if now < was {
out.push(Happened::Raided {
owner: seat as PlayerId,
lost: was - now,
});
}
}
for &(x, y, owner, health, placed) in &self.posts {
match after.signpost_at(x, y) {
Some(post) if post.owner == owner && post.placed == placed => {
if health == SignpostHealth::Full && post.health == SignpostHealth::Worn {
out.push(Happened::PostWorn { x, y, owner });
}
}
// Re-pointed by its owner: still standing, freshly.
Some(post) if post.owner == owner => {}
_ => out.push(Happened::PostGone { x, y, owner }),
}
}
}
}
impl Before {
/// The castle a crab that vanished walked into, and whose it was when
/// it did: the tile it stood on, or the one it was heading into (across
/// the seam on a wrapping beach).
fn castle_entered(&self, after: &Board, crab: &Seen) -> Option<(PlayerId, (u8, u8))> {
[Some(crab.tile), after.step(crab.tile, crab.dir)]
.into_iter()
.flatten()
.find_map(|tile| {
let at = after.coords_u8(tile);
self.castles
.iter()
.find(|(castle, _)| *castle == at)
.map(|&(_, owner)| (owner, at))
})
}
}
/// What banking `crab`, worth `value` on this board, pays, by the sim's
/// own rule (`Crab::bank_points`): Right Claws doubles a right-clawed crab
/// and charges for a left-clawed one. The floor at nothing is the
/// caller's, as it is the sim's.
fn worth(crab: &Seen, value: u32, claw_call: bool) -> i32 {
let value = value as i32;
match (claw_call, crab.handed) {
(false, _) => value,
(true, Handedness::Right) => value * 2,
(true, Handedness::Left) => -value,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_crab_walking_home_is_a_bank_for_that_castle() {
let mut board = Board::new(5, 1, 1);
board.set_tile(4, 0, TileKind::Castle(1));
board.spawn_crab(2, 0, Direction::Right, Handedness::Left, CrabKind::Common);
let mut seen = Vec::new();
for _ in 0..200 {
let before = Before::of(&board);
board.tick_idle();
before.diff(&board, &mut seen);
}
assert!(
matches!(
seen.as_slice(),
[Happened::Banked {
owner: 1,
x: 4,
y: 0,
..
}]
),
"{seen:?}"
);
}
fn run(board: &mut Board, ticks: u32, seen: &mut Vec<Happened>) {
for _ in 0..ticks {
let before = Before::of(board);
board.tick_idle();
before.diff(board, seen);
}
}
/// A crab eaten beside a castle on the tick another walks into it is
/// eaten, not banked: standing next to a castle whose score went up is
/// not walking into it.
#[test]
fn a_crab_eaten_beside_a_castle_that_banked_is_eaten() {
let mut board = Board::new(6, 4, 1);
board.set_tile(4, 0, TileKind::Castle(1));
board.spawn_crab(3, 0, Direction::Right, Handedness::Left, CrabKind::Common);
let mut seen = Vec::new();
run(&mut board, 11, &mut seen);
board.spawn_crab(4, 1, Direction::Down, Handedness::Left, CrabKind::Common);
board.spawn_gull(4, 2, Direction::Up);
run(&mut board, 40, &mut seen);
let banked = seen
.iter()
.filter(|h| matches!(h, Happened::Banked { .. }))
.count();
let eaten = seen
.iter()
.filter(|h| matches!(h, Happened::Eaten { .. }))
.count();
assert_eq!((banked, eaten), (1, 1), "{seen:?}");
}
/// Right Claws turns a left-clawed bank into a cost, which is no raid;
/// but a gull raiding a castle while it runs is still a raid.
#[test]
fn a_raid_during_right_claws_is_still_a_raid() {
let mut board = Board::new(6, 1, 1);
board.set_tile(0, 0, TileKind::Castle(0));
board.set_tile(5, 0, TileKind::Castle(1));
board.set_score(1, 20);
board.spawn_gull(3, 0, Direction::Right);
let text = format!("{}claw_call: 200\n", board.to_snapshot());
let mut board = Board::parse_snapshot(&text).expect("a board with Right Claws running");
assert!(board.in_claw_call());
let mut seen = Vec::new();
run(&mut board, 100, &mut seen);
assert!(
seen.iter()
.any(|h| matches!(h, Happened::Raided { owner: 1, .. })),
"{seen:?}"
);
}
/// A crab Crab Monopoly flies home banks for what it was worth when
/// the sweep fired. A Right Claws spun while it is in the air changes
/// nothing it pays, so pricing it off the clock at landing reported
/// the difference as a raid nobody made.
#[test]
fn a_crab_swept_before_right_claws_lands_as_a_bank_not_a_raid() {
let mut board = Board::new(9, 7, 5);
board.rules_mut().sweep_flight = true;
board.rules_mut().timed_lock = true;
board.rules_mut().sweep_keeps_worth = true;
board.set_tile(7, 5, TileKind::Castle(1));
board.set_score(1, 10);
for x in 1..5 {
board.spawn_crab(x, 1, Direction::Down, Handedness::Right, CrabKind::Common);
}
board.tick_idle();
board.force_tide_event(crate::sim::TideEvent::Monopoly, 1);
let mut seen = Vec::new();
run(&mut board, 5, &mut seen);
board.force_tide_event(crate::sim::TideEvent::RightClaws, 0);
while !board.sweeping().is_empty() {
run(&mut board, 1, &mut seen);
}
assert!(
!seen.iter().any(|h| matches!(h, Happened::Raided { .. })),
"{seen:?}"
);
let banked = seen
.iter()
.filter(|h| matches!(h, Happened::Banked { owner: 1, .. }))
.count();
assert_eq!(banked, 2, "{seen:?}");
}
/// A crab that banks on the tick a Castle Swap hands its castle on
/// banked for the owner it walked in on: no bank for the new owner,
/// and no raid on the old one.
#[test]
fn a_bank_on_a_castle_swap_tick_is_the_old_owners() {
let mut board = Board::new(5, 1, 1);
board.set_tile(0, 0, TileKind::Castle(0));
board.set_tile(4, 0, TileKind::Castle(1));
board.spawn_crab(2, 0, Direction::Right, Handedness::Left, CrabKind::Common);
let mut seen = Vec::new();
loop {
let before = Before::of(&board);
board.tick_idle();
if board.crabs().is_empty() {
// The swap a sparkling crab spins comes after the banks in
// the same tick: done here by hand, in that order.
board.force_spun_tide_event(crate::sim::TideEvent::CastleSwap, 1);
assert_eq!(board.tile_at(4, 0), TileKind::Castle(0));
before.diff(&board, &mut seen);
break;
}
before.diff(&board, &mut seen);
}
assert_eq!(board.scores()[1], 1);
assert!(
matches!(
seen.as_slice(),
[Happened::Banked {
owner: 1,
x: 4,
y: 0,
..
}]
),
"{seen:?}"
);
}
/// A left-clawed crab banked at nothing during Right Claws leaves the
/// score where it was, and is still a bank.
#[test]
fn a_bank_that_scores_nothing_is_still_a_bank() {
let mut board = Board::new(5, 1, 1);
board.set_tile(4, 0, TileKind::Castle(1));
board.spawn_crab(2, 0, Direction::Right, Handedness::Left, CrabKind::Common);
let text = format!("{}claw_call: 200\n", board.to_snapshot());
let mut board = Board::parse_snapshot(&text).expect("a board with Right Claws running");
let mut seen = Vec::new();
run(&mut board, 100, &mut seen);
assert_eq!(board.scores()[1], 0);
assert!(
matches!(seen.as_slice(), [Happened::Banked { owner: 1, .. }]),
"{seen:?}"
);
}
}