riichienv-core 0.3.0

Japanese Mahjong (Riichi) game engine with MJAI protocol support
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
#[cfg(test)]
mod unit_tests {
    use crate::action::Phase;
    use crate::agari::{is_agari, is_chiitoitsu, is_kokushi};
    use crate::score::calculate_score;
    use crate::types::Hand;

    #[test]
    fn test_agari_standard() {
        // Pinfu Tsumo: 123 456 789 m 234 p 55 s
        let tiles = [
            0, 1, 2, // 123m
            3, 4, 5, // 456m
            6, 7, 8, // 789m
            9, 10, 11, // 123p (mapped to 9,10,11)
            18, 18, // 1s pair (mapped to 18)
        ];
        let mut hand = Hand::new(Some(tiles.to_vec()));
        assert!(is_agari(&mut hand), "Should be agari");
    }

    #[test]
    fn test_basic_pinfu() {
        // 123m 456m 789m 123p 11s
        // m: 0-8, p: 9-17, s: 18-26_
        // 123p -> 9, 10, 11
        // 11s -> 18, 18
        let mut hand = Hand::new(None);
        // 123m
        hand.add(0);
        hand.add(1);
        hand.add(2);
        // 456m
        hand.add(3);
        hand.add(4);
        hand.add(5);
        // 789m
        hand.add(6);
        hand.add(7);
        hand.add(8);
        // 123p
        hand.add(9);
        hand.add(10);
        hand.add(11);
        // 11s (pair)
        hand.add(18);
        hand.add(18);

        assert!(is_agari(&mut hand));
    }

    #[test]
    fn test_chiitoitsu() {
        let mut hand = Hand::new(None);
        let pairs = [0, 2, 4, 6, 8, 10, 12];
        for &t in &pairs {
            hand.add(t);
            hand.add(t);
        }
        assert!(is_chiitoitsu(&hand));
        assert!(is_agari(&mut hand));
    }

    #[test]
    fn test_kokushi() {
        let mut hand = Hand::new(None);
        // 1m,9m, 1p,9p, 1s,9s, 1z-7z
        let terminals = [0, 8, 9, 17, 18, 26, 27, 28, 29, 30, 31, 32, 33];
        for &t in &terminals {
            hand.add(t);
        }
        hand.add(0); // Double 1m
        assert!(is_kokushi(&hand));
        assert!(is_agari(&mut hand));
    }

    #[test]
    fn test_score_calculation() {
        // Current implementation does NOT do Kiriage Mangan (rounding 1920->2000).
        // So base is 1920.
        // Oya pays: ceil(1920*2/100)*100 = 3900.
        // Ko pays: ceil(1920/100)*100 = 2000.
        // Total: 3900 + 2000*2 = 7900.

        let score = calculate_score(4, 30, false, true, 0); // Ko Tsumo

        assert_eq!(score.pay_tsumo_oya, 3900);
        assert_eq!(score.pay_tsumo_ko, 2000);
        assert_eq!(score.total, 7900); // 3900 + 2000 + 2000
    }

    #[test]
    fn test_tsuu_iisou() {
        use crate::yaku::{calculate_yaku, YakuContext};
        let mut hand = Hand::new(None);
        // 111z, 222z, 333z, 444z, 55z
        for &t in &[27, 28, 29, 30] {
            hand.add(t);
            hand.add(t);
            hand.add(t);
        }
        hand.add(31);
        hand.add(31);

        let res = calculate_yaku(&hand, &[], &YakuContext::default(), 31);
        assert!(res.han >= 13);
        assert!(res.yaku_ids.contains(&39));
    }

    #[test]
    fn test_ryuu_iisou() {
        use crate::yaku::{calculate_yaku, YakuContext};
        let mut hand = Hand::new(None);
        // 234s, 666s, 888s, 6s6s6s (Wait, 6s6s6s is already there)
        // Correct 234s, 666s, 888s, Hatsuz, 6s6s (pair)
        let tiles = [
            19, 20, 21, // 234s
            23, 23, 23, // 666s
            25, 25, 25, // 888s
            32, 32, 32, // Hatsuz
            19, 19, // 2s pair
        ];
        for &t in &tiles {
            hand.add(t);
        }

        let res = calculate_yaku(&hand, &[], &YakuContext::default(), 19);
        assert!(res.han >= 13);
        assert!(res.yaku_ids.contains(&40));
    }

    #[test]
    fn test_daisushii() {
        use crate::yaku::{calculate_yaku, YakuContext};
        let mut hand = Hand::new(None);
        // EEEz, SSSz, WWWz, NNNz, 11m
        for &t in &[27, 28, 29, 30] {
            hand.add(t);
            hand.add(t);
            hand.add(t);
        }
        hand.add(0);
        hand.add(0);

        let res = calculate_yaku(&hand, &[], &YakuContext::default(), 0);
        assert!(res.han >= 26);
        assert!(res.yaku_ids.contains(&50));
    }

    fn create_test_state(game_type: u8) -> crate::state::GameState {
        crate::state::GameState::new(game_type, false, None, 0, crate::rule::GameRule::default())
    }

    #[test]
    fn test_seeded_shuffle_changes_between_rounds() {
        let mut state = create_test_state(2);
        state.seed = Some(42);

        state._initialize_next_round(true, false);
        let digest1 = state.wall.wall_digest.clone();

        state._initialize_next_round(true, false);
        let digest2 = state.wall.wall_digest.clone();

        assert_ne!(
            digest1, digest2,
            "Wall digest should differ between rounds when seed is fixed"
        );
    }

    #[test]
    fn test_sudden_death_hanchan_logic() {
        use serde_json::Value;

        let mut state = create_test_state(2);
        state.round_wind = 1;
        state.kyoku_idx = 3;
        state.oya = 3;
        for i in 0..4 {
            state.players[i].score = 25000;
            state.players[i].nagashi_eligible = false;
        }
        state.needs_initialize_next_round = false;

        state._trigger_ryukyoku("exhaustive_draw");

        if state.needs_initialize_next_round {
            state._initialize_next_round(state.pending_oya_won, state.pending_is_draw);
            state.needs_initialize_next_round = false;
        }

        assert!(
            !state.is_done,
            "Game should not be done (Sudden Death should trigger)"
        );
        assert_eq!(state.round_wind, 2, "Should enter West round");
        assert_eq!(state.kyoku_idx, 0, "Should be West 1 (Kyoku 0)");
        assert_eq!(state.oya, 0, "Oya should rotate to player 0");

        let new_scores = [31000, 25000, 24000, 20000];
        for (player, &score) in state.players.iter_mut().zip(new_scores.iter()) {
            player.score = score;
        }

        state._trigger_ryukyoku("exhaustive_draw");
        if state.needs_initialize_next_round {
            state._initialize_next_round(state.pending_oya_won, state.pending_is_draw);
            state.needs_initialize_next_round = false;
        }

        assert!(
            state.is_done,
            "Game should be done (Score >= 30000 in West)"
        );

        let logs = &state.mjai_log;
        let event_types: Vec<String> = logs
            .iter()
            .filter_map(|s| {
                let v: Value = serde_json::from_str(s).ok()?;
                v.get("type")
                    .and_then(|t| t.as_str())
                    .map(|t| t.to_string())
            })
            .collect();

        let last_event = event_types.last().expect("Should have events");
        assert_eq!(last_event, "end_game");

        assert!(event_types.contains(&"ryukyoku".to_string()));
    }

    #[test]
    fn test_is_tenpai() {
        use crate::hand_evaluator::HandEvaluator;
        // 111,222,333m, 444p, 11s (Tenpai on 1s)
        let hand = vec![0, 1, 2, 4, 5, 6, 8, 9, 10, 12, 13, 14, 72];
        let calc = HandEvaluator::new(hand, Vec::new());
        assert!(calc.is_tenpai());
        let waits = calc.get_waits_u8();
        assert!(waits.contains(&18)); // 1s
    }

    #[test]
    fn test_kuikae_deadlock_repro() {
        use crate::action::{Action, ActionType};
        use std::collections::HashMap;

        let mut state = create_test_state(4);
        let pid = 0;

        // Hand: 4m, 5m, 6m, 6m. (12, 16, 20, 21)
        // 3m is 8.
        state.players[pid as usize].hand = vec![12, 16, 20, 21];

        // Setup P3 (Kamicha of P0)
        state.current_player = 3;
        state.phase = Phase::WaitAct;
        state.active_players = vec![3];
        state.players[3].hand.push(8); // Give 3m

        // Action: P3 discards 3m
        let mut actions = HashMap::new();
        actions.insert(3, Action::new(ActionType::Discard, Some(8), vec![]));

        state.step(&actions);

        state.step(&actions);

        assert_eq!(
            state.phase,
            Phase::WaitAct,
            "Should proceed to WaitAct as deadlock Chi is filtered out"
        );
        assert_eq!(state.current_player, 0, "Should be P0's turn");

        // Verify current_claims is empty or does not contain 0
        if let Some(claims) = state.current_claims.get(&0) {
            assert!(claims.is_empty(), "P0 should have no legal claims");
        }
    }
    #[test]
    fn test_match_84_agari_check() {
        use crate::hand_evaluator::HandEvaluator;
        use crate::types::{Conditions, Wind};

        // Hand: 111m, 78p, 11123s, 789s
        // 1m: 0
        // 7p: 15. 8p: 16.
        // 1s: 18. 2s: 19. 3s: 20.
        // 7s: 24. 8s: 25. 9s: 26.

        let mut tiles = vec![
            0, 1, 2,  // 1m x3
            60, // 7p (15*4)
            64, // 8p (16*4)
            72, 73, 74,  // 1s x3
            76,  // 2s (19*4)
            80,  // 3s (20*4)
            96,  // 7s (24*4)
            100, // 8s (25*4)
            104, // 9s (26*4)
        ];
        tiles.sort();

        let calc = HandEvaluator::new(tiles, Vec::new());

        let cond = Conditions {
            tsumo: false,
            riichi: false,
            double_riichi: false,
            ippatsu: false,
            haitei: false,
            houtei: false,
            rinshan: false,
            chankan: false,
            tsumo_first_turn: false,
            player_wind: Wind::West,
            round_wind: Wind::East,
            riichi_sticks: 0,
            honba: 0,
        };

        // 1. Check 6p (14 -> 56)
        let res6p = calc.calc(56, vec![], vec![], Some(cond.clone()));
        println!(
            "6p Result: is_win={}, Shape={}, Han={}, Yaku={:?}",
            res6p.is_win, res6p.has_win_shape, res6p.han, res6p.yaku
        );
        assert!(!res6p.is_win, "6p should NOT be a win (No Yaku)");
        assert!(res6p.has_win_shape, "6p should have win shape");
        assert_eq!(res6p.han, 0, "6p should have 0 Han");

        // 2. Check 9p (17 -> 68)
        let res9p = calc.calc(68, vec![], vec![], Some(cond));
        println!(
            "9p Result: is_win={}, Han={}, Yaku={:?}",
            res9p.is_win, res9p.han, res9p.yaku
        );
        assert!(res9p.is_win, "9p should be a win");
        assert!(res9p.han >= 3, "9p should be Junchan (>= 3 Han)"); // Junchan (3)
    }

    #[test]
    fn test_tobi_ends_game() {
        let mut state = create_test_state(4);
        state.game_mode = 2; // 4p-red-half (Hanchan)

        // Set scores with one player having negative score
        state.players[0].score = 30000;
        state.players[1].score = 40000;
        state.players[2].score = 35000;
        state.players[3].score = -5000; // Negative score - should trigger tobi

        state.needs_initialize_next_round = false;

        // Try to initialize next round - should end game due to tobi
        state._initialize_next_round(false, false);

        assert!(
            state.is_done,
            "Game should be done due to tobi (player with negative score)"
        );
    }

    #[test]
    fn test_apply_mjai_event_honor_and_red_tiles() {
        use crate::replay::MjaiEvent;

        let mut state =
            crate::state::GameState::new(4, true, None, 0, crate::rule::GameRule::default());

        // start_kyoku with mjai-format tiles: honors (E, S, W, N, P, F, C) and red fives (5pr, 5sr)
        let start = MjaiEvent::StartKyoku {
            bakaze: "E".to_string(),
            kyoku: 1,
            honba: 0,
            kyoutaku: 0,
            oya: 0,
            scores: vec![25000, 25000, 25000, 25000],
            dora_marker: "P".to_string(), // White dragon (tid 124)
            tehais: vec![
                // Player 0: E, S, W, N, P, F, C, 1m, 2m, 3m, 4m, 5m, 6m
                vec![
                    "E", "S", "W", "N", "P", "F", "C", "1m", "2m", "3m", "4m", "5m", "6m",
                ]
                .into_iter()
                .map(String::from)
                .collect(),
                // Player 1: 1s, 2s, 3s, 4s, 5sr, 6s, 7s, 8s, 9s, 1p, 2p, 3p, 4p
                vec![
                    "1s", "2s", "3s", "4s", "5sr", "6s", "7s", "8s", "9s", "1p", "2p", "3p", "4p",
                ]
                .into_iter()
                .map(String::from)
                .collect(),
                // Player 2: 5pr, 1m, 2m, 3m, 4m, 6m, 7m, 8m, 9m, 1p, 2p, 3p, 4p
                vec![
                    "5pr", "1m", "2m", "3m", "4m", "6m", "7m", "8m", "9m", "1p", "2p", "3p", "4p",
                ]
                .into_iter()
                .map(String::from)
                .collect(),
                // Player 3: all number tiles
                vec![
                    "1s", "2s", "3s", "4s", "5s", "6s", "7s", "8s", "9s", "1m", "2m", "3m", "4m",
                ]
                .into_iter()
                .map(String::from)
                .collect(),
            ],
        };
        state.apply_mjai_event(start);

        // Player 0: verify honor tiles are parsed correctly
        let hand0 = &state.players[0].hand;
        // E=108, S=112, W=116, N=120, P=124, F=128, C=132
        assert!(
            hand0.contains(&108),
            "E should be tid 108, hand: {:?}",
            hand0
        );
        assert!(
            hand0.contains(&112),
            "S should be tid 112, hand: {:?}",
            hand0
        );
        assert!(
            hand0.contains(&116),
            "W should be tid 116, hand: {:?}",
            hand0
        );
        assert!(
            hand0.contains(&120),
            "N should be tid 120, hand: {:?}",
            hand0
        );
        assert!(
            hand0.contains(&124),
            "P should be tid 124, hand: {:?}",
            hand0
        );
        assert!(
            hand0.contains(&128),
            "F should be tid 128, hand: {:?}",
            hand0
        );
        assert!(
            hand0.contains(&132),
            "C should be tid 132, hand: {:?}",
            hand0
        );

        // Player 1: verify red 5s (5sr = tid 88)
        let hand1 = &state.players[1].hand;
        assert!(
            hand1.contains(&88),
            "5sr should be tid 88, hand: {:?}",
            hand1
        );

        // Player 2: verify red 5p (5pr = tid 52)
        let hand2 = &state.players[2].hand;
        assert!(
            hand2.contains(&52),
            "5pr should be tid 52, hand: {:?}",
            hand2
        );

        // Dora marker "P" should be tid 124
        assert_eq!(
            state.wall.dora_indicators[0], 124,
            "dora_marker P should be tid 124, got: {}",
            state.wall.dora_indicators[0]
        );

        // Test tsumo with honor tile
        let tsumo = MjaiEvent::Tsumo {
            actor: 0,
            pai: "C".to_string(), // Red dragon (tid 132)
        };
        state.apply_mjai_event(tsumo);
        assert!(
            state.players[0].hand.contains(&132),
            "Tsumo C should add tid 132 to hand, hand: {:?}",
            state.players[0].hand
        );

        // Test dahai with honor tile
        let dahai = MjaiEvent::Dahai {
            actor: 0,
            pai: "E".to_string(), // East (tid 108)
            tsumogiri: false,
        };
        state.apply_mjai_event(dahai);
        assert!(
            state.players[0].discards.contains(&108),
            "Dahai E should discard tid 108, discards: {:?}",
            state.players[0].discards
        );

        // Test dora event with mjai honor
        let dora = MjaiEvent::Dora {
            dora_marker: "F".to_string(), // Green dragon (tid 128)
        };
        state.apply_mjai_event(dora);
        assert_eq!(
            state.wall.dora_indicators[1], 128,
            "dora F should be tid 128, got: {}",
            state.wall.dora_indicators[1]
        );
    }

    #[test]
    fn test_no_tobi_with_positive_scores() {
        let mut state = create_test_state(4);
        state.game_mode = 2; // 4p-red-half (Hanchan)
        state.round_wind = 0; // East round

        // Set scores with all players having positive scores
        state.players[0].score = 25000;
        state.players[1].score = 25000;
        state.players[2].score = 25000;
        state.players[3].score = 25000;

        state.needs_initialize_next_round = false;

        // Try to initialize next round - should NOT end game
        state._initialize_next_round(false, false);

        assert!(
            !state.is_done,
            "Game should NOT be done (all players have positive scores)"
        );
    }
}