;================================================================
; mahjong/mahjong_utils 麻将游戏 工具函数
; mahjong_agari.erb 和牌判定
;================================================================


;;;判断是否达成和牌牌型
;;;- str hand_code 目标手牌代码
;;;- (option)int agari_method 判定方式 0回轨法 1查表法
;;;@return 1能 0不能
@mj_agari(hand_code, agari_method=0)
#FUNCTION
    #DIMS hand_code
    #DIM agari_method
    #DIMS DYNAMIC jantou, 7
    #DIMS DYNAMIC count_map_str
    #DIMS DYNAMIC count_map_copy
    #DIMS DYNAMIC count_map_copy_without_jantou
    #DIM DYNAMIC i
    SIF STRLENSU(hand_code) % 6 != 4
        RETURNF 0
    SIF mj_count_toitsu(hand_code) == 7  ; 七对子
        RETURNF 1
    SIF mj_count_yaochuu(hand_code) == 13 && mj_count_toitsu(hand_code) == 1  ; 国士无双
        RETURNF 1
    SELECTCASE agari_method
        CASE 0  ; 回轨法 详情参见 http://hp.vector.co.jp/authors/VA046927/mjscore/mjalgorism.html
            count_map_str '= mj_map_hand_to_count(hand_code)
            SPLIT mj_get_jantou(count_map_str), ",", jantou
            SIF jantou:0 == ""
                RETURNF 0
            FOR i, 0, RESULT
                count_map_copy '= count_map_str  ; 深拷贝原映射数组
                SIF !mj_remove_toitsu(count_map_copy, TOINT(jantou:i))
                    THROW 取出雀头失败 %count_map_copy%的第%jantou:i%位(%SUBSTRINGU(count_map_copy, TOINT(jantou:i), 1)%)

                count_map_copy_without_jantou '= count_map_copy  ; 深拷贝去掉雀头后的映射数组
                RESULTS:0 '= mj_clear_shuntsu(count_map_copy_without_jantou)  ; 先取出顺子
                RESULTS:1 '= mj_clear_koutsu(count_map_copy_without_jantou)   ; 再取出刻子
                SIF count_map_copy_without_jantou == "0" * 34
                    RETURNF 1

                count_map_copy_without_jantou '= count_map_copy  ; 重新深拷贝去掉雀头后的映射数组
                RESULTS:1 '= mj_clear_koutsu(count_map_copy_without_jantou)   ; 先取出刻子
                RESULTS:0 '= mj_clear_shuntsu(count_map_copy_without_jantou)  ; 再取出顺子
                SIF count_map_copy_without_jantou == "0" * 34
                    RETURNF 1
            NEXT
        CASEELSE
            PRINTSL get_log("TODO 查表法尚未完成。", "error")
    ENDSELECT
    RETURNF 0
