socha 0.2.2

Communication layer for the software challenge germany 2025
Documentation
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
use std::{fmt, str::FromStr};

use crate::{
    incoming::{ReceivedBoard, ReceivedData, ReceivedRoom, ReceivedState},
    neutral::{Direction, Move, PiranhaField, Team},
};

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Joined {
    pub room_id: String,
}

#[derive(Debug, PartialEq, Eq, Clone)]
/// opposite of joined
pub struct Left {
    pub room_id: String,
}

#[derive(Debug, Default, PartialEq, Eq, Clone)]
pub struct Row {
    /// from left to right
    pub fields: [PiranhaField; 10],
}

#[derive(Debug, PartialEq, Eq, Clone, Default)]
pub struct Board {
    /// from bottom to top
    pub rows: [Row; 10],
}

impl fmt::Display for Board {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for row in self.rows.iter().rev() {
            for field in row.fields.iter() {
                write!(f, "{:<12}", field)?;
                write!(f, " ")?;
            }
            writeln!(f)?;
        }
        Ok(())
    }
}

impl TryFrom<ReceivedBoard> for Board {
    type Error = String;
    fn try_from(recv_board: ReceivedBoard) -> Result<Self, Self::Error> {
        if recv_board.rows.len() != 10 {
            return Err(format!(
                "board should contain exactly 10 rows, but has {}",
                recv_board.rows.len()
            ));
        }
        let mut rows: [Row; 10] = Default::default();
        for (i, recv_row) in recv_board.rows.into_iter().enumerate() {
            if recv_row.fields.len() != 10 {
                return Err(format!(
                    "row {} should contain exactly 10 fields, but has {}",
                    i,
                    recv_row.fields.len()
                ));
            }
            let mut fields: [PiranhaField; 10] = Default::default();
            for (j, recv_field) in recv_row.fields.into_iter().enumerate() {
                let field = PiranhaField::from_str(recv_field.raw.as_ref())?;
                fields[j] = field;
            }
            rows[i] = Row { fields };
        }
        Ok(Board { rows })
    }
}

impl Board {
    pub fn in_bounds(x: i32, y: i32) -> bool {
        (0..10).contains(&x) && (0..10).contains(&y)
    }

    pub fn get(&self, x: usize, y: usize) -> &PiranhaField {
        &self.rows[y].fields[x]
    }

    pub fn get_mut(&mut self, x: usize, y: usize) -> &mut PiranhaField {
        &mut self.rows[y].fields[x]
    }

    pub fn count_fishes_on_axis(&self, x: usize, y: usize, dir: Direction) -> u8 {
        let (dx, dy) = dir.to_delta();

        let mut cnt: u8 = 0;

        if matches!(self.get(x, y), PiranhaField::Fish { .. }) {
            cnt += 1;
        }
        let mut cx = x as i32 + dx;
        let mut cy = y as i32 + dy;

        while Board::in_bounds(cx, cy) {
            if let PiranhaField::Fish { .. } = self.get(cx as usize, cy as usize) {
                cnt += 1;
            }
            cx += dx;
            cy += dy;
        }

        let (bdx, bdy) = (-dx, -dy);
        let mut cx = x as i32 + bdx;
        let mut cy = y as i32 + bdy;

        while Board::in_bounds(cx, cy) {
            if let PiranhaField::Fish { .. } = self.get(cx as usize, cy as usize) {
                cnt += 1;
            }
            cx += bdx;
            cy += bdy;
        }

        cnt
    }

    pub fn check_allowed(
        board: &Self,
        x: usize,
        y: usize,
        dir: Direction,
        dis: u8,
        us_team: Team,
    ) -> bool {
        if dis == 0 {
            return false;
        }

        let opp_team = match us_team {
            Team::One => Team::Two,
            Team::Two => Team::One,
        };

        let mut cx = x as i32;
        let mut cy = y as i32;
        let (dx, dy) = dir.to_delta();
        let steps = dis as i32;

        for _step in 1..steps {
            cx += dx;
            cy += dy;

            if !Board::in_bounds(cx, cy) {
                return false;
            }

            let p_field = Board::get(board, cx as usize, cy as usize);

            // opp fish in the way
            if matches!(p_field, PiranhaField::Fish { team, .. } if *team == opp_team) {
                return false;
            }
        }

        // check goal field
        cx += dx;
        cy += dy;

        if !Board::in_bounds(cx, cy) {
            return false;
        }

        let goal_field = Board::get(board, cx as usize, cy as usize);

        match goal_field {
            PiranhaField::Squid => false,
            PiranhaField::Fish { team, .. } if *team == us_team => false,
            PiranhaField::Empty | PiranhaField::Fish { .. } => true,
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Default)]
pub struct GameState {
    // todo handle class
    pub class: Option<String>,
    pub start_team: Team,
    pub turn: u32,
    pub board: Board,
    pub last_move: Option<Move>,
}

impl TryFrom<ReceivedState> for GameState {
    type Error = String;
    fn try_from(recv_state: ReceivedState) -> Result<Self, Self::Error> {
        let start_team = if let Some(start_team_str) = recv_state.start_team {
            Team::try_from(start_team_str.as_ref())?
        } else {
            return Err(
                "ReceivedState should contain a 'start team' when converting to GameState"
                    .to_string(),
            );
        };

        let turn = if let Some(t) = recv_state.turn {
            t
        } else {
            return Err(
                "ReceivedState should contain 'turn' when converting to GameState".to_string(),
            );
        };

        let last_move = if let Some(recv_last_move) = recv_state.last_move {
            Some(Move::try_from(&recv_last_move)?)
        } else {
            None
        };

        let board = if let Some(recv_board) = recv_state.board {
            Board::try_from(recv_board)?
        } else {
            return Err(
                "ReceivedState should contain \"board\" when converting to GameState".to_string(),
            );
        };

        Ok(GameState {
            // todo: stop pushing class directly
            class: recv_state.class,
            start_team,
            turn,
            board,
            last_move,
        })
    }
}

#[derive(Debug, Clone, Copy)]
pub struct MoveChange {
    initial_square: (u8, u8),
    final_square: (u8, u8),
    // some if a fish was eaten
    fish_at_final: Option<PiranhaField>,
}

impl GameState {
    pub fn new_with_board(board: Board, start_team: Team) -> Self {
        GameState {
            class: None,
            start_team,
            turn: 0,
            board,
            last_move: None,
        }
    }
    pub fn current_team(&self) -> Team {
        if self.turn % 2 == 0 {
            match self.start_team {
                Team::One => Team::One,
                Team::Two => Team::Two,
            }
        } else {
            match self.start_team {
                Team::One => Team::Two,
                Team::Two => Team::One,
            }
        }
    }

    pub fn possible_moves(&self) -> Vec<Move> {
        let mut moves = Vec::new();
        let team = self.current_team();

        for y in 0..10 {
            for x in 0..10 {
                let cell = self.board.get(x, y);

                if let PiranhaField::Fish { team: t, .. } = cell {
                    if *t != team {
                        continue;
                    }
                } else {
                    continue;
                }
                for dir in [
                    Direction::Left,
                    Direction::Right,
                    Direction::UP,
                    Direction::Down,
                    Direction::UpLeft,
                    Direction::UpRight,
                    Direction::DownLeft,
                    Direction::DownRight,
                ] {
                    let dis = self.board.count_fishes_on_axis(x, y, dir);
                    if Board::check_allowed(&self.board, x, y, dir, dis, team) {
                        moves.push(Move {
                            from: (x as u8, y as u8),
                            dir,
                        });
                    }
                }
            }
        }

        moves
    }

    pub fn get_field_type(&self, pos: (u8, u8)) -> Option<PiranhaField> {
        match self.board.rows.get(pos.1 as usize) {
            None => None,
            Some(r) => r.fields.get(pos.0 as usize).copied(),
        }
    }

    pub fn get_fields_type(&self, field_type: PiranhaField) -> Vec<(u8, u8)> {
        let mut fields = Vec::new();
        for (i, row) in self.board.rows.iter().enumerate() {
            for (j, f) in row.fields.iter().enumerate() {
                if f == &field_type {
                    fields.push((i as u8, j as u8));
                }
            }
        }
        fields
    }

    /// assumes legal move
    pub fn make_move(&mut self, mv: Move) -> MoveChange {
        let dis = Board::count_fishes_on_axis(
            &self.board,
            mv.from.0 as usize,
            mv.from.1 as usize,
            mv.dir,
        );
        let goal_field = mv.to_goal_pos(dis);

        let (fx, fy) = (mv.from.0 as usize, mv.from.1 as usize);
        let (gx, gy) = (goal_field.0 as usize, goal_field.1 as usize);

        let field_at_goal = *self.board.get(gx, gy);
        let field_at_initial = *self.board.get(fx, fy);
        let fish_at_final = if !matches!(field_at_goal, PiranhaField::Empty) {
            Some(field_at_goal)
        } else {
            None
        };

        let removed = self.board.get_mut(fx, fy);
        *removed = PiranhaField::Empty;

        let goal = self.board.get_mut(gx, gy);
        *goal = field_at_initial;

        MoveChange {
            initial_square: mv.from,
            final_square: goal_field,
            fish_at_final,
        }
    }

    pub fn unmake_move(&mut self, change: MoveChange) {
        let (fx, fy) = (
            change.initial_square.0 as usize,
            change.initial_square.1 as usize,
        );
        let (gx, gy) = (
            change.final_square.0 as usize,
            change.final_square.1 as usize,
        );

        let moved_fish = *self.board.get(gx, gy);
        *self.board.get_mut(fx, fy) = moved_fish;

        match change.fish_at_final {
            Some(fish) => {
                *self.board.get_mut(gx, gy) = fish;
            }
            None => {
                *self.board.get_mut(gx, gy) = PiranhaField::Empty;
            }
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScoreTypes {
    Siegpunkte,
    Schwarmgröße,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AggregationTypes {
    Sum,
    Average,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Scores {
    pub score_type: ScoreTypes,
    pub value: u32,
    pub aggregation_type: AggregationTypes,
    pub relevant_for_ranking: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Winner {
    pub team: Team,
    pub regular: bool,
    pub reason: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GameResult {
    pub player1_result: Vec<Scores>,
    pub player2_result: Vec<Scores>,
    pub winner: Option<Winner>,
}

impl TryFrom<ReceivedData> for GameResult {
    type Error = String;
    fn try_from(recv_data: ReceivedData) -> Result<Self, Self::Error> {
        let winner = if let Some(scores) = recv_data.winner {
            let team = if let Some(team) = scores.team.as_ref() {
                Team::try_from(team.as_ref())?
            } else {
                return Err("missing winner team".to_string());
            };
            let regular = if let Some(regular) = scores.regular.as_ref() {
                regular.parse::<bool>().map_err(|e| e.to_string())?
            } else {
                return Err("missing winner regular".to_string());
            };
            let reason = scores.reason;
            Some(Winner {
                team,
                regular,
                reason,
            })
        } else {
            None
        };
        let mut definitions = Vec::new();
        if let Some(def) = &recv_data.definition {
            for frag in &def.fragments {
                let score_type = if let Some(name) = frag.frag_name.as_ref() {
                    match name.as_ref() {
                        "Siegpunkte" => ScoreTypes::Siegpunkte,
                        // todo: check if it is written as "Schwarmgr..e"
                        "Schwarmgröße" => ScoreTypes::Schwarmgröße,
                        other => {
                            return Err(format!("unknown score type '{}'", other));
                        }
                    }
                } else {
                    return Err("missing fragment name".to_string());
                };
                let aggregation_type = if let Some(agr) = frag.aggregation.as_ref() {
                    match agr.agr_content.as_ref() {
                        "SUM" => AggregationTypes::Sum,
                        "AVERAGE" => AggregationTypes::Average,
                        other => {
                            return Err(format!("unknown aggregation type '{}'", other));
                        }
                    }
                } else {
                    return Err("missing aggregation type".to_string());
                };
                let relevant_for_ranking = if let Some(rfr) = frag.relevant_for_ranking.as_ref() {
                    rfr.rfr_content.parse::<bool>().map_err(|e| e.to_string())?
                } else {
                    return Err("missing relevantForRanking".to_string());
                };
                definitions.push((score_type, aggregation_type, relevant_for_ranking));
            }
        }

        let mut player1_result = Vec::new();
        let mut player2_result = Vec::new();
        for entry in recv_data.scores.ok_or("missing scores")?.entries {
            let team = if let Some(player) = entry.player.team.as_ref() {
                Team::try_from(player.as_ref())?
            } else {
                return Err("missing player team".to_string());
            };
            let score = if let Some(score) = entry.score {
                score
            } else {
                return Err("missing player score".to_string());
            };
            if score.parts.len() != definitions.len() {
                return Err(format!(
                    "score parts length {} does not match definitions length {}",
                    score.parts.len(),
                    definitions.len()
                ));
            }
            let mut scores = Vec::new();
            for (part, def) in score.parts.into_iter().zip(definitions.iter()) {
                let value = part
                    .part_content
                    .parse::<u32>()
                    .map_err(|e| e.to_string())?;
                let score = Scores {
                    score_type: def.0,
                    value,
                    aggregation_type: def.1,
                    relevant_for_ranking: def.2,
                };
                scores.push(score);
            }
            match team {
                Team::One => player1_result = scores,
                Team::Two => player2_result = scores,
            }
        }

        Ok(GameResult {
            player1_result,
            player2_result,
            winner,
        })
    }
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub enum RoomMessage {
    Memento(Box<GameState>),
    Result(Box<GameResult>),
    WelcomeMessage,
    MoveRequest,
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct PreparedRoom {
    pub reservations: (String, String),
    pub room_id: String,
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum AdminMessage {
    /// (reservation, reservation)
    Prepared(PreparedRoom),
}

impl TryFrom<ReceivedRoom> for RoomMessage {
    type Error = String;
    fn try_from(recv_room: ReceivedRoom) -> Result<Self, Self::Error> {
        if let Some(data) = recv_room.data {
            if let Some(class) = &data.class {
                match class.as_str() {
                    "memento" => {
                        if let Some(state) = data.state {
                            if state.class.as_ref() != Some(&"state".to_string()) {
                                return Err("Received data with a class of memento should contain the a <state> element".to_string());
                            }
                            let state = GameState::try_from(state)?;
                            Ok(RoomMessage::Memento(Box::new(state)))
                        } else {
                            Err("Received data with a class of memento should contain the ReceivedState".to_string())
                        }
                    }
                    "result" => {
                        if let Ok(result) = GameResult::try_from(data) {
                            Ok(RoomMessage::Result(Box::new(result)))
                        } else {
                            Err("Received data with a class of result should contain the ReceivedResult".to_string())
                        }
                    }
                    "welcomeMessage" => Ok(RoomMessage::WelcomeMessage),
                    "moveRequest" => Ok(RoomMessage::MoveRequest),
                    other => Err(format!("unknown room message class '{}'", other)),
                }
            } else {
                Err("missing room message class".to_string())
            }
        } else {
            Err("missing room message data".to_string())
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub enum ComMessage {
    Joined(Joined),
    Left(Left),
    Room(Box<RoomMessage>),
    Admin(AdminMessage),
}