Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ Releases History

## Behavior changes
- **Open hands with no other fu won by tsumo.** They now always get the 2 tsumo fu, so they score 30 fu. Before, `fu_for_open_pinfu=False` scored them at 20 fu, and with the default `fu_for_open_pinfu=True` the 2 fu appeared in `fu_details` as `hand_without_fu` instead of `tsumo`. `fu_for_open_pinfu` now applies to ron only.

## Bug fixes
- A tenhou with kokushi, chuuren poutou or suuankou scored differently depending on `win_tile`. Now it always scores the thirteen-sided, nine-sided or tanki form.
Comment on lines +13 to +14

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This change should be treated as a behavioral change, not a bug fix.
It might even be considered a breaking change.

<!-- unreleased:end -->

<!-- release:2.2.0:start -->
Expand Down
46 changes: 35 additions & 11 deletions mahjong/hand_calculating/hand.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@
from mahjong.hand_calculating.hand_response import HandResponse
from mahjong.hand_calculating.scores import Aotenjou, ScoresCalculator, ScoresResult
from mahjong.hand_calculating.yaku import Yaku
from mahjong.hand_calculating.yaku_list.yakuman import (
DaburuChuurenPoutou,
DaburuKokushiMusou,
DaiSuushii,
SuuankouTanki,
)
from mahjong.meld import Meld
from mahjong.tile import TilesConverter
from mahjong.utils import build_dora_count_map, classify_hand_suits, count_dora_for_hand, plus_dora
Expand All @@ -22,16 +28,21 @@ class _CalculatedHand(TypedDict):
fu_details: list[FuDetail]


def _hand_priority(hand: _CalculatedHand) -> tuple[int, bool, int, int]:
_DOUBLE_YAKUMAN_FORMS = (DaburuKokushiMusou, SuuankouTanki, DaburuChuurenPoutou, DaiSuushii)


def _hand_priority(hand: _CalculatedHand) -> tuple[int, bool, int, int, int]:
"""
Rank a hand decomposition, the most expensive one is used.

The highest score wins, and on an equal score a real yakuman wins over counted (kazoe)
yakuman built from regular yaku, as on Tenhou.
yakuman built from regular yaku, as on Tenhou. Then the reading with more double yakuman
forms wins, so a tenhou names the double form even when it counts as one yakuman.
"""
total = hand["cost"]["total"] if hand["cost"] else -1
has_yakuman = any(yaku.is_yakuman for yaku in hand["hand_yaku"])
return total, has_yakuman, hand["han"], hand["fu"]
double_forms = sum(isinstance(yaku, _DOUBLE_YAKUMAN_FORMS) for yaku in hand["hand_yaku"]) if has_yakuman else 0
return total, has_yakuman, double_forms, hand["han"], hand["fu"]


# suit bitmask: sou=1, pin=2, man=4
Expand Down Expand Up @@ -142,6 +153,9 @@ def estimate_hand_value(
block combinations, evaluate yaku and fu for each decomposition, and return
the highest-scoring result as a :class:`~mahjong.hand_calculating.hand_response.HandResponse`.

A tenhou has no winning tile, so each tile kind in it is tried as one, and ``win_tile``
does not change the result.
Comment on lines +156 to +157

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I’d suggest revising the sentence “A tenhou has no winning tile.” There are two separate rule questions here. Does the game distinguish the dealer’s first draw from the initial deal?
And when the dealer wins with tenhou, does a qualifying hand receive the double-yakuman form regardless of which tile was drawn?

In Mahjong Soul, the game log records all 14 tiles as the dealer’s initial hand. The client displays the last tile in the sorted hand as the drawn tile, but the log does not identify a separate first draw.
Tenhou and Riichi City, on the other hand, both record a 13-tile initial hand followed by a distinct first draw.
Example Tenhou replay

Mahjong Soul and Riichi City both explicitly award the double-yakuman form on tenhou regardless of the drawn tile. I’d describe that scoring rule directly in the docstring. It explains the change and covers both ways of recording the deal.

Tenhou’s rules do not specify how it handles this case. Since Tenhou does not award double yakuman, the score would be the same either way, but the yaku name shown in the result could still differ. Do you have a Tenhou replay where the dealer wins with tenhou and the actual first draw would ordinarily give the single-yakuman form? That would let us check which yaku name Tenhou reports.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I have missed these key details. I will close PR for now and will investigate later how tenhou handles it vs other servers

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I support this change, as it improves compatibility with Mahjong Soul and Riichi City. However, I'm concerned about the compatibility of this library with Tenhou, which it's been testing.


Basic closed ron with tanyao:

>>> from mahjong.hand_calculating.hand import HandCalculator
Expand Down Expand Up @@ -365,6 +379,8 @@ def estimate_hand_value(
config.yaku.round_wind_north,
)

win_tiles = list({tile // 4: tile for tile in tiles}.values()) if config.is_tenhou else [win_tile]

calculated_hands: list[_CalculatedHand] = []
meld_blocks = [meld._sorted_tiles_34 for meld in melds] # noqa: SLF001
for hand in hand_options:
Expand All @@ -390,14 +406,20 @@ def estimate_hand_value(
suit_mask, honor_count = classify_hand_suits(hand)
has_honors = honor_count > 0

win_groups = HandCalculator._find_win_groups(win_tile, hand, meld_blocks)
for win_group in win_groups:
win_groups = [
(candidate_win_tile, win_group)
for candidate_win_tile in win_tiles
for win_group in HandCalculator._find_win_groups(candidate_win_tile, hand, meld_blocks)
]
for candidate_win_tile, win_group in win_groups:
cost = None
error = None
hand_yaku = []
han = 0

fu_details, fu = FuCalculator.calculate_fu(hand, win_tile, win_group, config, valued_tiles, melds)
fu_details, fu = FuCalculator.calculate_fu(
hand, candidate_win_tile, win_group, config, valued_tiles, melds
)

is_pinfu = len(fu_details) == 1 and not is_chiitoitsu and not is_open_hand

Expand Down Expand Up @@ -525,7 +547,7 @@ def estimate_hand_value(
if config.yaku.toitoi.is_condition_met(hand):
hand_yaku.append(config.yaku.toitoi)

if config.yaku.sanankou.is_condition_met(hand, win_tile, melds, config.is_tsumo):
if config.yaku.sanankou.is_condition_met(hand, candidate_win_tile, melds, config.is_tsumo):
hand_yaku.append(config.yaku.sanankou)

# sanshoku douko requires same triplet in all 3 suits
Expand Down Expand Up @@ -565,13 +587,15 @@ def estimate_hand_value(

# closed kan can't be used in chuuren_poutou; requires terminals
if not melds and not is_tanyao_hand and config.yaku.chuuren_poutou.is_condition_met(hand):
if tiles_34[win_tile // 4] == 2 or tiles_34[win_tile // 4] == 4:
if tiles_34[candidate_win_tile // 4] == 2 or tiles_34[candidate_win_tile // 4] == 4:
hand_yaku.append(config.yaku.daburu_chuuren_poutou)
else:
hand_yaku.append(config.yaku.chuuren_poutou)

if not is_open_hand and config.yaku.suuankou.is_condition_met(hand, win_tile, config.is_tsumo):
if tiles_34[win_tile // 4] == 2:
if not is_open_hand and config.yaku.suuankou.is_condition_met(
hand, candidate_win_tile, config.is_tsumo
):
if tiles_34[candidate_win_tile // 4] == 2:
hand_yaku.append(config.yaku.suuankou_tanki)
else:
hand_yaku.append(config.yaku.suuankou)
Expand Down Expand Up @@ -645,7 +669,7 @@ def estimate_hand_value(

# exception hand
if not melds and config.yaku.kokushi.is_condition_met(None, tiles_34):
if tiles_34[win_tile // 4] == 2:
if any(tiles_34[candidate_win_tile // 4] == 2 for candidate_win_tile in win_tiles):
hand_yaku.append(config.yaku.daburu_kokushi)
else:
hand_yaku.append(config.yaku.kokushi)
Expand Down
73 changes: 70 additions & 3 deletions tests/hand_calculating/tests_yakuman_calculation.py
Original file line number Diff line number Diff line change
Expand Up @@ -449,11 +449,11 @@ def test_kokushi_musou_multiple_yakuman() -> None:

assert hand_calculation.error is None
assert len(hand_calculation.yaku) == 2
assert hand_config.yaku.kokushi in hand_calculation.yaku
assert hand_config.yaku.daburu_kokushi not in hand_calculation.yaku
assert hand_config.yaku.kokushi not in hand_calculation.yaku
assert hand_config.yaku.daburu_kokushi in hand_calculation.yaku
assert hand_config.yaku.tenhou in hand_calculation.yaku
assert hand_config.yaku.chiihou not in hand_calculation.yaku
assert hand_calculation.han == 26
assert hand_calculation.han == 39

hand_config = HandConfig(is_tsumo=True, is_tenhou=False, is_chiihou=True)

Expand Down Expand Up @@ -858,3 +858,70 @@ def test_suuankou_wins_over_kazoe_capped_at_sanbaiman() -> None:
assert result.han == 13
assert [yaku.name for yaku in result.yaku] == ["Suu Ankou"]
assert result.cost["total"] == 32000


_TENHOU_HANDS = [
pytest.param(TilesConverter.string_to_136_array(man="11123345678999"), "daburu_chuuren_poutou", id="chuuren"),
pytest.param(
TilesConverter.string_to_136_array(sou="19", pin="19", man="19", honors="12345677"),
"daburu_kokushi",
id="kokushi",
),
pytest.param(
TilesConverter.string_to_136_array(man="111", pin="222", sou="333444", honors="55"),
"suuankou_tanki",
id="suuankou",
),
]


def _tenhou_config(has_double_yakuman: bool) -> HandConfig:
return HandConfig(
is_tsumo=True,
is_tenhou=True,
player_wind=EAST,
options=OptionalRules(has_double_yakuman=has_double_yakuman),
)


@pytest.mark.parametrize(("has_double_yakuman", "yakuman_count"), [(True, 3), (False, 2)])
@pytest.mark.parametrize(("tiles", "double_form"), _TENHOU_HANDS)
def test_tenhou_names_the_double_form_whichever_tile_is_the_win_tile(
tiles: list[int], double_form: str, has_double_yakuman: bool, yakuman_count: int
) -> None:
config = _tenhou_config(has_double_yakuman)
expected_yaku = sorted([getattr(config.yaku, double_form), config.yaku.tenhou], key=str)

for win_tile in tiles:
result = HandCalculator.estimate_hand_value(tiles, win_tile, config=config)
assert result.error is None
assert sorted(result.yaku, key=str) == expected_yaku
assert result.han == 13 * yakuman_count
assert result.cost["main"] == 16000 * yakuman_count
assert result.cost["additional"] == 16000 * yakuman_count


@pytest.mark.parametrize("has_double_yakuman", [True, False])
@pytest.mark.parametrize(("tiles", "double_form"), _TENHOU_HANDS)
def test_tenhou_scores_the_same_whichever_tile_is_the_win_tile(
tiles: list[int], double_form: str, has_double_yakuman: bool
) -> None:
config = _tenhou_config(has_double_yakuman)

results = set()
for win_tile in tiles:
result = HandCalculator.estimate_hand_value(tiles, win_tile, config=config)
results.add((result.han, result.fu, tuple(str(yaku) for yaku in result.yaku), result.cost["total"]))

assert len(results) == 1, double_form


def test_chiihou_keeps_the_wait_of_its_drawn_tile() -> None:
tiles = TilesConverter.string_to_136_array(man="11123345678999")
win_tile = _string_to_136_tile(man="1")
config = HandConfig(is_tsumo=True, is_chiihou=True)

result = HandCalculator.estimate_hand_value(tiles, win_tile, config=config)
assert result.error is None
assert sorted(result.yaku, key=str) == sorted([config.yaku.chuuren_poutou, config.yaku.chiihou], key=str)
assert result.han == 26
Loading