%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Released under the MIT License.

% Copyright (c) 2025 Kosei Kawaguchi

% Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

% The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{KKran}[2025/12/23, Version 1.1.0]
\RequirePackage{calc}
\RequirePackage{tikz}
\RequirePackage{xcolor}
\RequirePackage{KKsymbols}%%%
\usetikzlibrary{shapes}
\usetikzlibrary{calc}
\RequirePackage{kvoptions}
\RequirePackage{luacode} 
\RequirePackage{etoolbox} 

\SetupKeyvalOptions{%
  family=kkran,%
  prefix=kkran@%
}
\DeclareStringOption[1]{kaitouhyouji}
\DeclareStringOption[red]{kaitoucolor}
\DeclareStringOption[20]{gridmax}
\DeclareStringOption[20]{nongridmax}
\DeclareStringOption[2\zw]{unit}
\DeclareStringOption[.7pt]{wakuwidth}
\DeclareStringOption[.35pt]{tensenwakuwidth}
\DeclareStringOption[.5pt]{tensenon}
\DeclareStringOption[.7pt]{tensenoff}
\DeclareStringOption[0]{clsadjust}
\ProcessKeyvalOptions*

\ifnum\number\kkran@clsadjust=1
  \RequirePackage[scale=1]{luatexja-fontspec}
  \RequirePackage[deluxe,expert]{luatexja-preset}
\else
  \ifnum\number\kkran@clsadjust=0
  \else
    \errmessage{Error: clsadjust option requires to be 0 or 1.}%
  \fi
\fi

\NewDocumentCommand{\KaitouInput}{m}{%
  \ifnum\number\kkran@kaitouhyouji=1
    {\color{\kkran@kaitoucolor}#1}%
  \else
    \ifnum\number\kkran@kaitouhyouji=0
      {\color{white}#1}%
    \else
      \errmessage{Error: kaitouhyouji option requires to be 0 or 1.}%
    \fi%
  \fi%
}

\newdimen\width@KKran
\width@KKran=\kkran@unit

\newdimen\waku@KKran \waku@KKran=\kkran@wakuwidth
\newdimen\tensenwaku@KKran \tensenwaku@KKran =\kkran@tensenwakuwidth


\def\modai@bangou@wd{0.5}
\def\mondai@position@tmp{0}
\def\mondai@position@y@tmp{0}

\def\mondai@dash@pat@on{\kkran@tensenon}
\def\mondai@dash@pat@off{\kkran@tensenoff}

\newcount\NUM@mondai
\newcount\NUM@shoumon


% 縦書きの時のみ仕様\kakko{\RevBangou{あ}}みたいに
% KKsymbolsがv2.0.0から\RotTateを使って中身だけ回転させるか否かを決めるようにするので、それに対応。
\NewDocumentCommand{\RevBangou}{m}{%
  \ifnum\ltjgetparameter{direction}=3%
    \rotatebox[origin=c]{-90}{#1}%
  \else%
    #1%
  \fi%
} 

% カウンタを設定するため
\NewDocumentCommand{\SetDaimon}{m}{\NUM@mondai=#1}
\NewDocumentCommand{\SetShoumon}{m}{\NUM@shoumon=#1}

\NewDocumentCommand{\daimon@bangou@yokotate}{}{%
  \ifnum\ltjgetparameter{direction}=3%
    \def\rotate@or@not@daimon{0}
  \else
    \def\rotate@or@not@daimon{0}%
  \fi%
} 
\NewDocumentCommand{\how@to@count@daimon@bangou}{}{%
  \kakko{\number\NUM@mondai}%
} 
\NewDocumentCommand{\Daimon@Box@A@N}{ O{.5} m o }{% 大問番号
  \daimon@bangou@yokotate%
  \IfNoValueTF{#3}{\global\advance\NUM@mondai by 1}{}%
  \global\def\modai@bangou@wd{#1}%
  \draw[line width=\waku@KKran] (0,0) rectangle (#1\width@KKran,- #2\width@KKran);%
  \node[anchor=center,overlay
    ,rotate=\rotate@or@not@daimon
  ]
   at (.5*#1\width@KKran,- .5*#2\width@KKran) {\scalebox{.8}{\IfNoValueTF{#3}{\how@to@count@daimon@bangou}{#3}}};
  \pgfmathparse{\mondai@position@tmp + \modai@bangou@wd}%
  \edef\mondai@position@tmp{\pgfmathresult}%
}

\NewDocumentCommand{\shoumon@bangou@yokotate}{}{%
  \ifnum\ltjgetparameter{direction}=3%
    \def\rotate@or@not@shoumon{0}
  \else
    \def\rotate@or@not@shoumon{0}%
  \fi%
} 
\NewDocumentCommand{\how@to@count@shoumon@bangou}{}{%
  \kakko{\number\NUM@shoumon}%
} 
\NewDocumentCommand{\Shoumon@Box@A@N}{ O{.5} m o }{% 小問番号
  \shoumon@bangou@yokotate
  \IfNoValueTF{#3}{\advance\NUM@shoumon by 1}{}%

  \draw[line width=\waku@KKran] (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran) -- ++ (0,- #2\width@KKran);
  \draw[line width=\waku@KKran] (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran) -- ++ (#1\width@KKran,0);
  \draw[line width=\tensenwaku@KKran, dash pattern=on \mondai@dash@pat@on off \mondai@dash@pat@off] (\mondai@position@tmp\width@KKran+#1\width@KKran,-\mondai@position@y@tmp\width@KKran) -- ++ (0,- #2\width@KKran);
  \draw[line width=\waku@KKran] (\mondai@position@tmp\width@KKran+#1\width@KKran,-\mondai@position@y@tmp\width@KKran- #2\width@KKran) -- ++ (-#1\width@KKran,0);

  \node[anchor=center,overlay
    ,rotate=\rotate@or@not@shoumon
  ]
  at (\mondai@position@tmp\width@KKran+.5*#1\width@KKran,-\mondai@position@y@tmp\width@KKran- .5*#2\width@KKran) {\scalebox{.8}{\IfNoValueTF{#3}{\how@to@count@shoumon@bangou}{#3}}};

  \pgfmathparse{\mondai@position@tmp + #1}%
  \edef\mondai@position@tmp{\pgfmathresult}%
}


\define@key{Shoumon@Box@A}{west}{%
  \def\westtext@Shoumon@Box@A{#1}%
}
\define@key{Shoumon@Box@A}{center}{%
  \def\centertext@Shoumon@Box@A{#1}%
}
\define@key{Shoumon@Box@A}{east}{%
  \def\easttext@Shoumon@Box@A{#1}%
}
\define@key{Shoumon@Box@A}{north west}{%
  \def\nwtext@Shoumon@Box@A{#1}%
}
\define@key{Shoumon@Box@A}{north east}{%
  \def\netext@Shoumon@Box@A{#1}%
}
\define@key{Shoumon@Box@A}{south west}{%
  \def\swtext@Shoumon@Box@A{#1}%
}
\define@key{Shoumon@Box@A}{south east}{%
  \def\setext@Shoumon@Box@A{#1}%
}
\NewDocumentCommand{\reset@Shoumon@Box@A}{}{%
  \def\westtext@Shoumon@Box@A{}%
  \def\centertext@Shoumon@Box@A{}%
  \def\easttext@Shoumon@Box@A{}%
  \def\nwtext@Shoumon@Box@A{}%
  \def\netext@Shoumon@Box@A{}%
  \def\swtext@Shoumon@Box@A{}%
  \def\setext@Shoumon@Box@A{}%
}
\NewDocumentCommand{\Shoumon@Box@A}{ m m O{} }{% 小問
  \reset@Shoumon@Box@A\setkeys{Shoumon@Box@A}{#3}%

  % 左上から反時計回りに A, B, C, D を定義
  \path (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran) coordinate (A@Shoumon@Box@A)
        -- ++(0,-#2\width@KKran) coordinate (B@Shoumon@Box@A)
        -- ++(#1\width@KKran,0)  coordinate (C@Shoumon@Box@A)
        -- ++(0,#2\width@KKran)  coordinate (D@Shoumon@Box@A);

  % 箱の描画
  \draw[line width=\tensenwaku@KKran, dash pattern=on \mondai@dash@pat@on off \mondai@dash@pat@off] (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran) -- ++ (0,- #2\width@KKran);
  \draw[line width=\waku@KKran] (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran) -- ++ (#1\width@KKran,0) -- ++ (0,- #2\width@KKran) -- ++ (-#1\width@KKran,0);

  % 文字列などの挿入用
  \node[overlay,anchor=center] at ($(A@Shoumon@Box@A)!0.5!(C@Shoumon@Box@A)$) {\centertext@Shoumon@Box@A};
  \node[overlay,anchor=west] at ($(A@Shoumon@Box@A)!0.5!(B@Shoumon@Box@A)$) {\westtext@Shoumon@Box@A};
  \node[overlay,anchor=east] at ($(C@Shoumon@Box@A)!0.5!(D@Shoumon@Box@A)$) {\easttext@Shoumon@Box@A};
  \node[overlay,anchor=north west] at (A@Shoumon@Box@A) {\nwtext@Shoumon@Box@A};
  \node[overlay,anchor=north east] at (D@Shoumon@Box@A) {\netext@Shoumon@Box@A};
  \node[overlay,anchor=south west] at (B@Shoumon@Box@A) {\swtext@Shoumon@Box@A};
  \node[overlay,anchor=south east] at (C@Shoumon@Box@A) {\setext@Shoumon@Box@A};

  % 座標の更新
  \pgfmathparse{\mondai@position@tmp + #1}%
  \edef\mondai@position@tmp{\pgfmathresult}%
}



\define@key{Shoumon@Box@B}{west}{%
  \def\westtext@Shoumon@Box@B{#1}%
}
\define@key{Shoumon@Box@B}{center}{%
  \def\centertext@Shoumon@Box@B{#1}%
}
\define@key{Shoumon@Box@B}{east}{%
  \def\easttext@Shoumon@Box@B{#1}%
}
\define@key{Shoumon@Box@B}{north west}{%
  \def\nwtext@Shoumon@Box@B{#1}%
}
\define@key{Shoumon@Box@B}{north east}{%
  \def\netext@Shoumon@Box@B{#1}%
}
\define@key{Shoumon@Box@B}{south west}{%
  \def\swtext@Shoumon@Box@B{#1}%
}
\define@key{Shoumon@Box@B}{south east}{%
  \def\setext@Shoumon@Box@B{#1}%
}
\NewDocumentCommand{\reset@Shoumon@Box@B}{}{%
  \def\westtext@Shoumon@Box@B{}%
  \def\centertext@Shoumon@Box@B{}%
  \def\easttext@Shoumon@Box@B{}%
  \def\nwtext@Shoumon@Box@B{}%
  \def\netext@Shoumon@Box@B{}%
  \def\swtext@Shoumon@Box@B{}%
  \def\setext@Shoumon@Box@B{}%
}
\NewDocumentCommand{\Shoumon@Box@B}{ m m O{} }{% 小問（右が点線に）
  \reset@Shoumon@Box@B\setkeys{Shoumon@Box@B}{#3}%

  % 左上から反時計回りに A, B, C, D を定義
  \path (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran) coordinate (A@Shoumon@Box@B)
        -- ++(0,-#2\width@KKran) coordinate (B@Shoumon@Box@B)
        -- ++(#1\width@KKran,0)  coordinate (C@Shoumon@Box@B)
        -- ++(0,#2\width@KKran)  coordinate (D@Shoumon@Box@B);

  % 箱の描画
  \draw[line width=\tensenwaku@KKran, dash pattern=on \mondai@dash@pat@on off \mondai@dash@pat@off] (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran) -- ++ (0,- #2\width@KKran);
  \draw[line width=\waku@KKran] (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran) -- ++ (#1\width@KKran,0);
  \draw[line width=\tensenwaku@KKran, dash pattern=on \mondai@dash@pat@on off \mondai@dash@pat@off] (\mondai@position@tmp\width@KKran+#1\width@KKran,-\mondai@position@y@tmp\width@KKran) -- ++ (0,- #2\width@KKran);
  \draw[line width=\waku@KKran] (\mondai@position@tmp\width@KKran+#1\width@KKran,-\mondai@position@y@tmp\width@KKran- #2\width@KKran) -- ++ (-#1\width@KKran,0);

  % 文字列などの挿入用
  \node[overlay,anchor=center] at ($(A@Shoumon@Box@B)!0.5!(C@Shoumon@Box@B)$) {\centertext@Shoumon@Box@B};
  \node[overlay,anchor=west] at ($(A@Shoumon@Box@B)!0.5!(B@Shoumon@Box@B)$) {\westtext@Shoumon@Box@B};
  \node[overlay,anchor=east] at ($(C@Shoumon@Box@B)!0.5!(D@Shoumon@Box@B)$) {\easttext@Shoumon@Box@B};
  \node[overlay,anchor=north west] at (A@Shoumon@Box@B) {\nwtext@Shoumon@Box@B};
  \node[overlay,anchor=north east] at (D@Shoumon@Box@B) {\netext@Shoumon@Box@B};
  \node[overlay,anchor=south west] at (B@Shoumon@Box@B) {\swtext@Shoumon@Box@B};
  \node[overlay,anchor=south east] at (C@Shoumon@Box@B) {\setext@Shoumon@Box@B};

  % 座標の更新
  \pgfmathparse{\mondai@position@tmp + #1}%
  \edef\mondai@position@tmp{\pgfmathresult}%
}


\newcommand{\masume@text@KKran}[1]{%
  \begingroup%
    \ltjsetparameter{kanjiskip=0pt}% 
    \ltjsetparameter{xkanjiskip=0pt}% 
    \setlength{\baselineskip}{\dimexpr\unit@KKran\relax}% 
    \fontsize{\unit@KKran}{\baselineskip}\selectfont%
    {#1}% 
    \setlength{\lineskiplimit}{-99mm}%
    \par%
  \endgroup%
}
\newdimen\unit@KKran
\unit@KKran=\kkran@unit
\NewDocumentCommand{\Shoumon@Grid@A}{ O{#2} m  O{} }{% 
    \def\grid@max@A{#2}\def\grid@min@A{#1}%
    \ifnum\grid@max@A<\grid@min@A% 大小がおかしい時はerror
      \errmessage{Error: \grid@max@A (\the\grid@max@A) must be greater than or equal to \grid@min@A (\the\grid@min@A).}%
    \fi%
    \def\grid@x@A{\kkran@gridmax}% 可変にしてもいい
    \pgfmathtruncatemacro{\shou@grid@max@A}{\grid@max@A / \grid@x@A}%
    \pgfmathtruncatemacro{\amari@grid@max@A}{mod(\grid@max@A,\grid@x@A)}%
    \pgfmathtruncatemacro{\max@minus@amari@grid@max@A}{\grid@x@A-\amari@grid@max@A}%
    \pgfmathtruncatemacro{\shou@grid@min@A}{\grid@min@A / \grid@x@A}%
    \pgfmathtruncatemacro{\amari@grid@min@A}{mod(\grid@min@A,\grid@x@A)}%
    \pgfmathtruncatemacro{\min@minus@amari@grid@min@A}{\grid@x@A-\amari@grid@min@A}%

    \ifnum\grid@min@A<\grid@x@A% minの方の描画
      \draw[overlay,line width=\waku@KKran] (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran-\unit@KKran) -- (\mondai@position@tmp\width@KKran+\amari@grid@min@A\unit@KKran,-\mondai@position@y@tmp\width@KKran-\unit@KKran);
      \draw[overlay,line width=\waku@KKran] (\mondai@position@tmp\width@KKran+\amari@grid@min@A\unit@KKran,-\mondai@position@y@tmp\width@KKran-\unit@KKran) -- (\mondai@position@tmp\width@KKran+\amari@grid@min@A\unit@KKran,-\mondai@position@y@tmp\width@KKran+\shou@grid@min@A\unit@KKran);
      \draw[overlay,line width=\waku@KKran] (\mondai@position@tmp\width@KKran+\amari@grid@min@A\unit@KKran,-\mondai@position@y@tmp\width@KKran+\shou@grid@min@A\unit@KKran) -- (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran);
    \else
      \ifnum\amari@grid@min@A=0% 余り0の方
        \draw[overlay,line width=\waku@KKran] (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran-\shou@grid@min@A\unit@KKran) -- (\mondai@position@tmp\width@KKran+\grid@x@A\unit@KKran,-\mondai@position@y@tmp\width@KKran-\shou@grid@min@A\unit@KKran);
        \draw[overlay,line width=\waku@KKran] (\mondai@position@tmp\width@KKran+\grid@x@A\unit@KKran,-\mondai@position@y@tmp\width@KKran-\shou@grid@min@A\unit@KKran) -- (\mondai@position@tmp\width@KKran+\grid@x@A\unit@KKran,-\mondai@position@y@tmp\width@KKran);
        \draw[overlay,line width=\waku@KKran] (\mondai@position@tmp\width@KKran+\grid@x@A\unit@KKran,-\mondai@position@y@tmp\width@KKran) -- (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran);

      \else% 余り\neq0の方
        \coordinate (A@amari@non@zero) at (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran);%
        \coordinate (B@amari@non@zero) at (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran-\shou@grid@min@A\unit@KKran-\unit@KKran);%
        \coordinate (C@amari@non@zero) at (\mondai@position@tmp\width@KKran+\amari@grid@min@A\unit@KKran,-\mondai@position@y@tmp\width@KKran-\shou@grid@min@A\unit@KKran-\unit@KKran);%
        \coordinate (D@amari@non@zero) at (\mondai@position@tmp\width@KKran+\amari@grid@min@A\unit@KKran,-\mondai@position@y@tmp\width@KKran-\shou@grid@min@A\unit@KKran);%
        \coordinate (E@amari@non@zero) at (\mondai@position@tmp\width@KKran+\grid@x@A\unit@KKran,-\mondai@position@y@tmp\width@KKran-\shou@grid@min@A\unit@KKran);%
        \coordinate (F@amari@non@zero) at (\mondai@position@tmp\width@KKran+\grid@x@A\unit@KKran,-\mondai@position@y@tmp\width@KKran);%

        \draw[overlay,line width=\waku@KKran] (B@amari@non@zero) -- (C@amari@non@zero);
        \draw[overlay,line width=\waku@KKran] (C@amari@non@zero) -- (D@amari@non@zero);
        \draw[overlay,line width=\waku@KKran] (D@amari@non@zero) -- (E@amari@non@zero);
        \draw[overlay,line width=\waku@KKran] (E@amari@non@zero) -- (F@amari@non@zero);
        \draw[overlay,line width=\waku@KKran] (F@amari@non@zero) -- (A@amari@non@zero);
      \fi
    \fi
    
    \ifnum\grid@max@A<\grid@x@A% maxの方の描画
      % 垂直線（左端除去）
        \foreach \x in {1,2,...,\amari@grid@max@A} {
          \draw[dashed,line width=\tensenwaku@KKran]
            ($(\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran) + (\x\unit@KKran,0)$)
            -- ++(0,-\unit@KKran);
        }

      \draw[line width=\tensenwaku@KKran, dash pattern=on \mondai@dash@pat@on off \mondai@dash@pat@off]  (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran) -- (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran-\unit@KKran);
      \draw[line width=\waku@KKran]
        (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran-\unit@KKran) -- % 1. 底辺の始点 (左下の角)
        (\mondai@position@tmp\width@KKran+\amari@grid@max@A\unit@KKran,-\mondai@position@y@tmp\width@KKran-\unit@KKran) -- % 2. 底辺の終点 (右下の角)
        (\mondai@position@tmp\width@KKran+\amari@grid@max@A\unit@KKran,-\mondai@position@y@tmp\width@KKran+\shou@grid@max@A\unit@KKran) -- % 3. 右の縦の辺 (右上の角)
        (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran+\shou@grid@max@A\unit@KKran); % 4. 上辺の終点 (左上の角)

      \node[anchor=north west,inner sep=0pt] at (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran+\shou@grid@max@A\unit@KKran) {\masume@text@KKran{#3}};% 最後に文字

      \pgfmathparse{\mondai@position@tmp + \grid@max@A}%
      \edef\mondai@position@tmp{\pgfmathresult}%
    \else
      \ifnum\amari@grid@max@A=0% 余り0の方
        % 座標の短縮
        \coordinate (P@amarizero) at (\mondai@position@tmp\width@KKran, -\mondai@position@y@tmp\width@KKran);
        \def\H{\shou@grid@max@A\unit@KKran}

        % 垂直線（左端除去）
        \foreach \x in {1,2,...,\grid@x@A} {
          \draw[dashed,line width=\tensenwaku@KKran]
            ($(P@amarizero) + (\x\unit@KKran,0)$)
            -- ++(0,-\shou@grid@max@A\unit@KKran);
        }

        % 水平線
        \foreach \y in {0,1,...,\shou@grid@max@A} {
          \draw[dashed,line width=\tensenwaku@KKran]
            ($(P@amarizero) + (0,-\y\unit@KKran)$)
            -- ++(\grid@x@A\unit@KKran,0);
        }

        \draw[line width=\tensenwaku@KKran, dash pattern=on \mondai@dash@pat@on off \mondai@dash@pat@off] (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran) -- (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran-\shou@grid@max@A\unit@KKran);
        \draw[line width=\waku@KKran]
          (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran-\shou@grid@max@A\unit@KKran) -- % 始点 A
          (\mondai@position@tmp\width@KKran+\grid@x@A\unit@KKran,-\mondai@position@y@tmp\width@KKran-\shou@grid@max@A\unit@KKran) -- % 終点 B
          (\mondai@position@tmp\width@KKran+\grid@x@A\unit@KKran,-\mondai@position@y@tmp\width@KKran) -- % 終点 C
          (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran); % 終点 D
        
        \node[anchor=north west,inner sep=0pt] at (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran) {\parbox{\grid@x@A\unit@KKran}{\masume@text@KKran{#3}}};% 最後に文字

      \else% 余り\neq0の方
        \coordinate (A@amari@non@zero) at (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran);%
        \coordinate (B@amari@non@zero) at (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran-\shou@grid@max@A\unit@KKran-\unit@KKran);%
        \coordinate (C@amari@non@zero) at (\mondai@position@tmp\width@KKran+\amari@grid@max@A\unit@KKran,-\mondai@position@y@tmp\width@KKran-\shou@grid@max@A\unit@KKran-\unit@KKran);%
        \coordinate (D@amari@non@zero) at (\mondai@position@tmp\width@KKran+\amari@grid@max@A\unit@KKran,-\mondai@position@y@tmp\width@KKran-\shou@grid@max@A\unit@KKran);%
        \coordinate (E@amari@non@zero) at (\mondai@position@tmp\width@KKran+\grid@x@A\unit@KKran,-\mondai@position@y@tmp\width@KKran-\shou@grid@max@A\unit@KKran);%
        \coordinate (F@amari@non@zero) at (\mondai@position@tmp\width@KKran+\grid@x@A\unit@KKran,-\mondai@position@y@tmp\width@KKran);%

        % 垂直線（左端除去）
        \foreach \x in {1,2,...,\amari@grid@max@A} {% 左ブロック
          \draw[dashed,line width=\tensenwaku@KKran]
            ($(A@amari@non@zero) + (\x\unit@KKran,0)$)
            -- ++(0,-\shou@grid@max@A\unit@KKran-\unit@KKran);
        }
        \foreach \x in {1,2,...,\max@minus@amari@grid@max@A} {% 右ブロック
          \draw[dashed,line width=\tensenwaku@KKran]
            ($(D@amari@non@zero) + (\x\unit@KKran,0)$)
            -- ++(0,\shou@grid@max@A\unit@KKran);
        }

        % 水平線
        \foreach \y in {0,1,...,\shou@grid@max@A} {% 左ブロック
          \draw[dashed,line width=\tensenwaku@KKran]
            ($(A@amari@non@zero) + (0,-\y\unit@KKran)$)
            -- ++(\amari@grid@max@A\unit@KKran,0);
        }
        \foreach \y in {0,1,...,\shou@grid@max@A} {% 右ブロック
          \draw[dashed,line width=\tensenwaku@KKran]
            ($(D@amari@non@zero) + (0,\y\unit@KKran)$)
            -- ++(\max@minus@amari@grid@max@A\unit@KKran,0);
        }

        \draw[line width=\tensenwaku@KKran, dash pattern=on \mondai@dash@pat@on off \mondai@dash@pat@off] (A@amari@non@zero) -- (B@amari@non@zero);
        \draw[line width=\waku@KKran] (B@amari@non@zero) -- (C@amari@non@zero)
        -- (D@amari@non@zero) -- (E@amari@non@zero) -- (F@amari@non@zero) -- (A@amari@non@zero);

        \node[anchor=north west,inner sep=0pt] at (A@amari@non@zero) {\parbox{\grid@x@A\unit@KKran}{\masume@text@KKran{#3}}};% 最後に文字
      \fi
      \pgfmathparse{\mondai@position@tmp + \grid@x@A}%
      \edef\mondai@position@tmp{\pgfmathresult}%
    \fi
}

\NewDocumentCommand{\Shoumon@NonGrid@A}{ m O{} }{%
    \def\nongrid@max@A{#1}%
    \def\nongrid@x@A{20}% 可変にしてもいい
    \pgfmathtruncatemacro{\shou@nongrid@max@A}{\nongrid@max@A / \nongrid@x@A}%
    \pgfmathtruncatemacro{\amari@nongrid@max@A}{mod(\nongrid@max@A,\nongrid@x@A)}%
    \pgfmathtruncatemacro{\max@minus@amari@nongrid@max@A}{\nongrid@x@A-\amari@nongrid@max@A}%

    \ifnum\nongrid@max@A<\nongrid@x@A% maxの方の描画のみ
      \draw[line width=\tensenwaku@KKran, dash pattern=on \mondai@dash@pat@on off \mondai@dash@pat@off]  (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran) -- (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran-\unit@KKran);
      \draw[line width=\waku@KKran]
        (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran-\unit@KKran) -- % 1. 底辺の始点 (左下の角)
        (\mondai@position@tmp\width@KKran+\amari@nongrid@max@A\unit@KKran,-\mondai@position@y@tmp\width@KKran-\unit@KKran) -- % 2. 底辺の終点 (右下の角)
        (\mondai@position@tmp\width@KKran+\amari@nongrid@max@A\unit@KKran,-\mondai@position@y@tmp\width@KKran+\shou@nongrid@max@A\unit@KKran) -- % 3. 右の縦の辺 (右上の角)
        (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran+\shou@nongrid@max@A\unit@KKran); % 4. 上辺の終点 (左上の角)

      \node[anchor=north west,inner sep=0pt] at (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran+\shou@nongrid@max@A\unit@KKran) {\masume@text@KKran{#2}};% 最後に文字

      \pgfmathparse{\mondai@position@tmp + \nongrid@max@A}%
      \edef\mondai@position@tmp{\pgfmathresult}%
    \else
      \ifnum\amari@nongrid@max@A=0% 余り0の方
        % 座標の短縮
        \coordinate (P@amarizero) at (\mondai@position@tmp\width@KKran, -\mondai@position@y@tmp\width@KKran);
        \def\H{\shou@nongrid@max@A\unit@KKran}

        % 水平線
        \foreach \y in {0,1,...,\amari@nongrid@max@A} {
          \draw[dashed,line width=\tensenwaku@KKran]
            ($(P@amarizero) + (0,-\y\unit@KKran)$)
            -- ++(\nongrid@x@A\unit@KKran,0);
        }

        \draw[line width=\tensenwaku@KKran, dash pattern=on \mondai@dash@pat@on off \mondai@dash@pat@off] (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran) -- (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran-\shou@nongrid@max@A\unit@KKran);
        \draw[line width=\waku@KKran]
          (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran-\shou@nongrid@max@A\unit@KKran) -- % 始点 A
          (\mondai@position@tmp\width@KKran+\nongrid@x@A\unit@KKran,-\mondai@position@y@tmp\width@KKran-\shou@nongrid@max@A\unit@KKran) -- % 終点 B
          (\mondai@position@tmp\width@KKran+\nongrid@x@A\unit@KKran,-\mondai@position@y@tmp\width@KKran) -- % 終点 C
          (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran); % 終点 D
        
        \node[anchor=north west,inner sep=0pt] at (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran) {\parbox{\nongrid@x@A\unit@KKran}{\masume@text@KKran{#2}}};% 最後に文字

      \else% 余り\neq0の方
        \coordinate (A@amari@non@zero) at (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran);%
        \coordinate (B@amari@non@zero) at (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran-\shou@nongrid@max@A\unit@KKran-\unit@KKran);%
        \coordinate (C@amari@non@zero) at (\mondai@position@tmp\width@KKran+\amari@nongrid@max@A\unit@KKran,-\mondai@position@y@tmp\width@KKran-\shou@nongrid@max@A\unit@KKran-\unit@KKran);%
        \coordinate (D@amari@non@zero) at (\mondai@position@tmp\width@KKran+\amari@nongrid@max@A\unit@KKran,-\mondai@position@y@tmp\width@KKran-\shou@nongrid@max@A\unit@KKran);%
        \coordinate (E@amari@non@zero) at (\mondai@position@tmp\width@KKran+\nongrid@x@A\unit@KKran,-\mondai@position@y@tmp\width@KKran-\shou@nongrid@max@A\unit@KKran);%
        \coordinate (F@amari@non@zero) at (\mondai@position@tmp\width@KKran+\nongrid@x@A\unit@KKran,-\mondai@position@y@tmp\width@KKran);%

        % 水平線
        \foreach \y in {0,1,...,\shou@nongrid@max@A} {% 上ブロック
          \draw[dashed,line width=\tensenwaku@KKran]
            ($(A@amari@non@zero) + (0,-\y\unit@KKran)$)
            -- ++(\nongrid@x@A\unit@KKran,0);
        }
        \draw[dashed,line width=\tensenwaku@KKran]% 下ブロック
          ($(D@amari@non@zero) + (0,\shou@nongrid@max@A\unit@KKran)$)
          -- ++(\max@minus@amari@nongrid@max@A\unit@KKran,0);

        \draw[line width=\tensenwaku@KKran, dash pattern=on \mondai@dash@pat@on off \mondai@dash@pat@off] (A@amari@non@zero) -- (B@amari@non@zero);
        \draw[line width=\waku@KKran] (B@amari@non@zero) -- (C@amari@non@zero)
        -- (D@amari@non@zero) -- (E@amari@non@zero) -- (F@amari@non@zero) -- (A@amari@non@zero);

        \node[anchor=north west,inner sep=0pt] at (A@amari@non@zero) {\parbox{\nongrid@x@A\unit@KKran}{\masume@text@KKran{#2}}};% 最後に文字
      \fi
      \pgfmathparse{\mondai@position@tmp + \nongrid@x@A}%
      \edef\mondai@position@tmp{\pgfmathresult}%
    \fi
}

\NewDocumentCommand{\GoDown}{m}{% 下へ行く
  \pgfmathparse{\mondai@position@y@tmp + #1}%
  \edef\mondai@position@y@tmp{\pgfmathresult}%
  \def\mondai@position@tmp{0}%
  \pgfmathparse{\mondai@position@tmp + \modai@bangou@wd}%
  \edef\mondai@position@tmp{\pgfmathresult}%
}

% 1.外枠と中身を黒塗り 2.中身を白抜き 3.本体の描画
\newcommand{\BlockFillMode@KKran}{%
  % 1. カウンターが進まないようにローカル化（または無効化）
  
  % 2. 各ボックス描画コマンドを「矩形塗りつぶし(\fill)」に再定義
  
  % \Daimon@Box@A@N のパッチ
  \RenewDocumentCommand{\Daimon@Box@A@N}{ O{.5} m O{} }{%
    \global\def\modai@bangou@wd{##1}%
    \fill (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran) 
          rectangle ++(##1\width@KKran, -##2\width@KKran);%
    \pgfmathparse{\mondai@position@tmp + \modai@bangou@wd}%
    \edef\mondai@position@tmp{\pgfmathresult}%
  }%
  
  % Shoumon@Box@A@N のパッチ
  \RenewDocumentCommand{\Shoumon@Box@A@N}{ O{.5} m O{} }{%
    \fill (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran) 
          rectangle ++(##1\width@KKran, -##2\width@KKran);%
    \pgfmathparse{\mondai@position@tmp + ##1}%
    \edef\mondai@position@tmp{\pgfmathresult}%
  }%
  
  % Shoumon@Box@A のパッチ
  \RenewDocumentCommand{\Shoumon@Box@A}{ m m O{} }{%
      \fill (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran) 
            rectangle ++(##1\width@KKran, -##2\width@KKran);%
      \pgfmathparse{\mondai@position@tmp + ##1}%
      \edef\mondai@position@tmp{\pgfmathresult}%
    }%
    \RenewDocumentCommand{\Shoumon@Box@B}{ m m O{} }{%
      \fill (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran) 
            rectangle ++(##1\width@KKran, -##2\width@KKran);%
      \pgfmathparse{\mondai@position@tmp + ##1}%
      \edef\mondai@position@tmp{\pgfmathresult}%
    }%

  % Shoumon@Grid@A/NonGrid@A
  \RenewDocumentCommand{\Shoumon@Grid@A}{ O{##2} m O{}}{%
    \def\grid@max@A{##2}\def\grid@min@A{##1}%
    \def\grid@x@A{\kkran@gridmax}% 可変にしてもいい
    \pgfmathtruncatemacro{\shou@grid@max@A}{\grid@max@A / \grid@x@A}%
    \pgfmathtruncatemacro{\amari@grid@max@A}{mod(\grid@max@A,\grid@x@A)}%
    \pgfmathtruncatemacro{\max@minus@amari@grid@max@A}{\grid@x@A-\amari@grid@max@A}%
    \pgfmathtruncatemacro{\shou@grid@min@A}{\grid@min@A / \grid@x@A}%
    \pgfmathtruncatemacro{\amari@grid@min@A}{mod(\grid@min@A,\grid@x@A)}%
    \pgfmathtruncatemacro{\min@minus@amari@grid@min@A}{\grid@x@A-\amari@grid@min@A}%
    
    \ifnum\grid@max@A<\grid@x@A
      \fill
      (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran-\unit@KKran) -- % 1. 底辺の始点 (左下の角)
      (\mondai@position@tmp\width@KKran+\amari@grid@max@A\unit@KKran,-\mondai@position@y@tmp\width@KKran-\unit@KKran) -- % 2. 底辺の終点 (右下の角)
      (\mondai@position@tmp\width@KKran+\amari@grid@max@A\unit@KKran,-\mondai@position@y@tmp\width@KKran+\shou@grid@max@A\unit@KKran) -- % 3. 右の縦の辺 (右上の角)
      (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran+\shou@grid@max@A\unit@KKran) -- cycle; % 4. 上辺の終点 (左上の角)
    \else
      \ifnum\amari@grid@max@A=0
        \fill
          (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran-\shou@grid@max@A\unit@KKran) -- % 始点 A
          (\mondai@position@tmp\width@KKran+\grid@x@A\unit@KKran,-\mondai@position@y@tmp\width@KKran-\shou@grid@max@A\unit@KKran) -- % 終点 B
          (\mondai@position@tmp\width@KKran+\grid@x@A\unit@KKran,-\mondai@position@y@tmp\width@KKran) -- % 終点 C
          (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran) -- cycle; % 終点 D
      \else
        \coordinate (A@amari@non@zero) at (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran);%
        \coordinate (B@amari@non@zero) at (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran-\shou@grid@max@A\unit@KKran-\unit@KKran);%
        \coordinate (C@amari@non@zero) at (\mondai@position@tmp\width@KKran+\amari@grid@max@A\unit@KKran,-\mondai@position@y@tmp\width@KKran-\shou@grid@max@A\unit@KKran-\unit@KKran);%
        \coordinate (D@amari@non@zero) at (\mondai@position@tmp\width@KKran+\amari@grid@max@A\unit@KKran,-\mondai@position@y@tmp\width@KKran-\shou@grid@max@A\unit@KKran);%
        \coordinate (E@amari@non@zero) at (\mondai@position@tmp\width@KKran+\grid@x@A\unit@KKran,-\mondai@position@y@tmp\width@KKran-\shou@grid@max@A\unit@KKran);%
        \coordinate (F@amari@non@zero) at (\mondai@position@tmp\width@KKran+\grid@x@A\unit@KKran,-\mondai@position@y@tmp\width@KKran);%
        \fill (B@amari@non@zero) -- (C@amari@non@zero)
        -- (D@amari@non@zero) -- (E@amari@non@zero) -- (F@amari@non@zero) -- (A@amari@non@zero) -- cycle;
      \fi
    \fi
  }
  \RenewDocumentCommand{\Shoumon@NonGrid@A}{ m O{}}{%
    \def\nongrid@max@A{##1}
    \def\nongrid@x@A{20}% 可変にしてもいい
    \pgfmathtruncatemacro{\shou@nongrid@max@A}{\nongrid@max@A / \nongrid@x@A}% 
    \pgfmathtruncatemacro{\amari@nongrid@max@A}{mod(\nongrid@max@A,\nongrid@x@A)}% <-- grid を nongrid に変更
    \pgfmathtruncatemacro{\max@minus@amari@nongrid@max@A}{\nongrid@x@A-\amari@nongrid@max@A}% 
    
    \ifnum\nongrid@max@A<\nongrid@x@A
      \fill
      (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran-\unit@KKran) -- % 1. 底辺の始点 (左下の角)
      (\mondai@position@tmp\width@KKran+\amari@nongrid@max@A\unit@KKran,-\mondai@position@y@tmp\width@KKran-\unit@KKran) -- % 2. 底辺の終点 (右下の角)
      (\mondai@position@tmp\width@KKran+\amari@nongrid@max@A\unit@KKran,-\mondai@position@y@tmp\width@KKran+\shou@nongrid@max@A\unit@KKran) -- % 3. 右の縦の辺 (右上の角)
      (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran+\shou@nongrid@max@A\unit@KKran) -- cycle; % 4. 上辺の終点 (左上の角)
      
      \pgfmathparse{\mondai@position@tmp + \nongrid@max@A}%
      \edef\mondai@position@tmp{\pgfmathresult}%
    \else
      \ifnum\amari@nongrid@max@A=0
        \fill
          (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran-\shou@nongrid@max@A\unit@KKran) -- % 始点 A
          (\mondai@position@tmp\width@KKran+\nongrid@x@A\unit@KKran,-\mondai@position@y@tmp\width@KKran-\shou@nongrid@max@A\unit@KKran) -- % 終点 B
          (\mondai@position@tmp\width@KKran+\nongrid@x@A\unit@KKran,-\mondai@position@y@tmp\width@KKran) -- % 終点 C
          (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran) -- cycle; % 終点 D

        \pgfmathparse{\mondai@position@tmp + \nongrid@x@A}%
        \edef\mondai@position@tmp{\pgfmathresult}%
      \else
        \coordinate (A@amari@non@zero) at (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran);%
        \coordinate (B@amari@non@zero) at (\mondai@position@tmp\width@KKran,-\mondai@position@y@tmp\width@KKran-\shou@nongrid@max@A\unit@KKran-\unit@KKran);%
        \coordinate (C@amari@non@zero) at (\mondai@position@tmp\width@KKran+\amari@nongrid@max@A\unit@KKran,-\mondai@position@y@tmp\width@KKran-\shou@nongrid@max@A\unit@KKran-\unit@KKran);%
        \coordinate (D@amari@non@zero) at (\mondai@position@tmp\width@KKran+\amari@nongrid@max@A\unit@KKran,-\mondai@position@y@tmp\width@KKran-\shou@nongrid@max@A\unit@KKran);%
        \coordinate (E@amari@non@zero) at (\mondai@position@tmp\width@KKran+\nongrid@x@A\unit@KKran,-\mondai@position@y@tmp\width@KKran-\shou@nongrid@max@A\unit@KKran);%
        \coordinate (F@amari@non@zero) at (\mondai@position@tmp\width@KKran+\nongrid@x@A\unit@KKran,-\mondai@position@y@tmp\width@KKran);%
        \fill (B@amari@non@zero) -- (C@amari@non@zero)
        -- (D@amari@non@zero) -- (E@amari@non@zero) -- (F@amari@non@zero) -- (A@amari@non@zero) -- cycle;

        \pgfmathparse{\mondai@position@tmp + \nongrid@x@A}%
        \edef\mondai@position@tmp{\pgfmathresult}%
      \fi
    \fi
  }
}

\ExplSyntaxOn
% アルファベット
\seq_set_split:Nnn \g_alphabet_lower_seq {} {abcdefghijklmnopqrstuvwxyz}
\seq_set_split:Nnn \g_alphabet_upper_seq {} {ABCDEFGHIJKLMNOPQRSTUVWXYZ}
\NewDocumentCommand{\alphabetarray}{ s m }{%
  \IfBooleanTF{#1}
    {\seq_item:Nn \g_alphabet_upper_seq {#2}} % *あり：大文字
    {\seq_item:Nn \g_alphabet_lower_seq {#2}} % *なし：小文字
}
% ローマ数字
\NewDocumentCommand{\Rrnum}{ s m }{%
  \IfBooleanTF{#1}{\uppercase\expandafter{\romannumeral#2}}{\romannumeral#2}%
}
% 50音 
\seq_set_split:Nnn \g_gojyuon_hira_seq {} {あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわをん}
\seq_set_split:Nnn \g_gojyuon_kata_seq {} {アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲン}
\NewDocumentCommand{\gojyuon}{ s m }{%
  \IfBooleanTF{#1}{\seq_item:Nn \g_gojyuon_kata_seq {#2}} {\seq_item:Nn \g_gojyuon_hira_seq {#2}}
}
% いろはうた
\seq_set_split:Nnn \g_iroha_seq {}{いろはにほへとちりぬるをわかよたれそつねならむうゐのおくやまけふこえてあさきゆめみしゑひもせす}
\seq_set_split:Nnn \g_irohakata_seq {}{イロハニホヘトチリヌルヲワカヨタレソツネナラムウヰノオクヤマケフコエテアサキユメミシヱヒモセス
}
\NewDocumentCommand{\iroha}{ s m }{%
  \IfBooleanTF{#1}{\seq_item:Nn \g_irohakata_seq {#2}}{\seq_item:Nn \g_iroha_seq {#2}}
}
% 漢数字
\int_new:N \wabunkansuji_tmpa_int
\int_new:N \wabunkansuji_tmpb_int
\int_new:N \wabunkansuji_tmpc_int

\cs_new:Npn \wabunkansuji_one:n #1
 {
   \int_case:nnF {#1}
    { {1}{一}{2}{二}{3}{三}{4}{四}{5}{五}{6}{六}{7}{七}{8}{八}{9}{九} }{}
 }

\cs_new:Npn \wabunkansuji_main:n #1
 {
   \int_compare:nNnTF {#1} = {0} {零}
   {
     \int_compare:nNnTF {#1} = {10000} {一万}
     {
       % 万の位
       \int_set:Nn \wabunkansuji_tmpa_int { \int_div_truncate:nn {#1} {10000} }
       \int_set:Nn \wabunkansuji_tmpb_int { #1 - \wabunkansuji_tmpa_int * 10000 }

       \int_compare:nNnTF \wabunkansuji_tmpa_int > 0
         { \wabunkansuji_one:n{\wabunkansuji_tmpa_int}万 }{}

       % 千の位
       \int_set:Nn \wabunkansuji_tmpa_int { \int_div_truncate:nn \wabunkansuji_tmpb_int {1000} }
       \int_set:Nn \wabunkansuji_tmpc_int { \wabunkansuji_tmpb_int - \wabunkansuji_tmpa_int * 1000 }
       \int_compare:nNnTF \wabunkansuji_tmpa_int = 0 {} 
         { \int_compare:nNnTF \wabunkansuji_tmpa_int = 1 {千}{\wabunkansuji_one:n{\wabunkansuji_tmpa_int}千} }

       % 百の位
       \int_set:Nn \wabunkansuji_tmpa_int { \int_div_truncate:nn \wabunkansuji_tmpc_int {100} }
       \int_set:Nn \wabunkansuji_tmpb_int { \wabunkansuji_tmpc_int - \wabunkansuji_tmpa_int * 100 }
       \int_compare:nNnTF \wabunkansuji_tmpa_int = 0 {} 
         { \int_compare:nNnTF \wabunkansuji_tmpa_int = 1 {百}{\wabunkansuji_one:n{\wabunkansuji_tmpa_int}百} }

       % 十の位
       \int_set:Nn \wabunkansuji_tmpa_int { \int_div_truncate:nn \wabunkansuji_tmpb_int {10} }
       \int_set:Nn \wabunkansuji_tmpc_int { \wabunkansuji_tmpb_int - \wabunkansuji_tmpa_int * 10 }
       \int_compare:nNnTF \wabunkansuji_tmpa_int = 0 {} 
         { \int_compare:nNnTF \wabunkansuji_tmpa_int = 1 {十}{\wabunkansuji_one:n{\wabunkansuji_tmpa_int}十} }

       % 一の位
       \int_compare:nNnTF \wabunkansuji_tmpc_int = 0 {} {\wabunkansuji_one:n{\wabunkansuji_tmpc_int}}
     }
   }
 }
\NewDocumentCommand{\wabunkansuji}{ m }{\wabunkansuji_main:n{#1}}
\ExplSyntaxOff

\pgfkeys{
  /KKran/.is family, /KKran/.cd,
  daimon/.is choice, 
  daimon/a/.code={%
    \def\how@to@count@daimon@bangou{\kakko*{\alphabetarray{\number\NUM@mondai}}}%
  },
  daimon/A/.code={%
    \def\how@to@count@daimon@bangou{\kakko{\alphabetarray*{\number\NUM@mondai}}}%
  },
  daimon/あ/.code={%
    \def\how@to@count@daimon@bangou{\kakko{\RevBangou{\gojyuon{\number\NUM@mondai}}}}%
  },
  daimon/ア/.code={%
    \def\how@to@count@daimon@bangou{\kakko{\RevBangou{\gojyuon*{\number\NUM@mondai}}}}%
  },
  daimon/いろは/.code={%
    \def\how@to@count@daimon@bangou{\kakko{\RevBangou{\iroha{\number\NUM@mondai}}}}%
  },
  daimon/イロハ/.code={%
    \def\how@to@count@daimon@bangou{\kakko{\RevBangou{\iroha*{\number\NUM@mondai}}}}%
  },
  daimon/一/.code={%
    \def\how@to@count@daimon@bangou{\kakko{\RevBangou{\wabunkansuji{\number\NUM@mondai}}}}%
  },
  daimon/ロ小/.code={%
    \def\how@to@count@daimon@bangou{\kakko{\Rrnum{\number\NUM@mondai}}}%
  },
  daimon/ロ大/.code={%
    \def\how@to@count@daimon@bangou{\kakko{\Rrnum*{\number\NUM@mondai}}}%
  },
  shoumon/.is choice, 
  shoumon/a/.code={%
    \def\how@to@count@shoumon@bangou{\kakko*{\alphabetarray{\number\NUM@shoumon}}}%
  },
  shoumon/A/.code={%
    \def\how@to@count@shoumon@bangou{\kakko{\alphabetarray*{\number\NUM@shoumon}}}%
  },
  shoumon/あ/.code={%
    \def\how@to@count@shoumon@bangou{\kakko{\RevBangou{\gojyuon{\number\NUM@shoumon}}}}%
  },
  shoumon/ア/.code={%
    \def\how@to@count@shoumon@bangou{\kakko{\RevBangou{\gojyuon*{\number\NUM@shoumon}}}}%
  },
  shoumon/いろは/.code={%
    \def\how@to@count@shoumon@bangou{\kakko{\RevBangou{\iroha{\number\NUM@shoumon}}}}%
  },
  shoumon/イロハ/.code={%
    \def\how@to@count@shoumon@bangou{\kakko{\RevBangou{\iroha*{\number\NUM@shoumon}}}}%
  },
  shoumon/一/.code={%
    \def\how@to@count@shoumon@bangou{\kakko{\RevBangou{\wabunkansuji{\number\NUM@shoumon}}}}%
  },
  shoumon/ロ小/.code={%
    \def\how@to@count@shoumon@bangou{\kakko{\Rrnum{\number\NUM@shoumon}}}%
  },
  shoumon/ロ大/.code={%
    \def\how@to@count@shoumon@bangou{\kakko{\Rrnum*{\number\NUM@shoumon}}}%
  },
}
\NewDocumentCommand{\KKran}{ O{2pt} m O{} }{%
\begingroup%
  % 第3引数(#3)のキー設定を適用
    \pgfkeys{/KKran/.cd, #3}%

  % 描画内容をマクロとして定義（３回使い回す）
  \def\byouga@KKran{%
    #2%
  }
  \begin{tikzpicture}
    % 1. 黒の太線シルエット（背景）
    %    BlockFillModeでコマンドを「塗りつぶし」に変え、カウンターをリセットしてから描画
    \begin{scope}[line width=#1, line join=round] 
      \BlockFillMode@KKran
      % fillだけでなくdrawも行うことで外側に太らせる
      \tikzset{every path/.style={draw=black, fill=black}} 
      \byouga@KKran
    \end{scope}

    % 2. 白のシルエット（中抜き用）
    %    線の太さを0にして、純粋な形状だけで黒い塊の内側をくり抜く
    \begin{scope}
      \BlockFillMode@KKran
      \tikzset{every path/.style={fill=white, draw=none}}
      \byouga@KKran
    \end{scope}

    % 3. 本番の描画（前面）
    \begin{scope}
      \byouga@KKran
    \end{scope}
  \end{tikzpicture}
\endgroup%
  \def\how@to@count@shoumon@bangou{\kakko{\number\NUM@shoumon}}%
  \def\how@to@count@daimon@bangou{\kakko{\number\NUM@mondai}}%
}


% 名前をユーザー用に切り替え
\let\大問番号\Daimon@Box@A@N
\let\小問番号\Shoumon@Box@A@N
\let\小問欄\Shoumon@Box@A
\let\小問中欄\Shoumon@Box@B
\let\小問マス目\Shoumon@Grid@A
\let\小問記述\Shoumon@NonGrid@A


% マークシート

\ifnum\number\kkran@kaitouhyouji=1 %
  \let\kyouteovalblackUSEINTERNAL\jegg@new@black%
\else%
  \let\kyouteovalblackUSEINTERNAL\jegg@new%
\fi%

\begin{luacode*}
-- 配列データを保存するグローバルテーブル
stored_arrays = {}

function register_mark_array(name, input_str)
    local items = {}
    -- パイプ区切りで要素を取得してLuaテーブルに保存
    for s in string.gmatch(input_str, "[^|]+") do
        table.insert(items, s)
    end
    stored_arrays[name] = items
    
    -- TeXマクロを定義
    -- \解答マーク配列[n] の形式で呼び出せるようにする (デフォルトは0)
    -- 内部で render_mark_array を呼び出す
    tex.print("\\expandafter\\newcommand\\csname " .. name .. "マーク配列\\endcsname[1][0]{" .. 
              "\\directlua{render_mark_array('" .. name .. "', #1)}}")
end

function render_mark_array(name, active_index)
    local items = stored_arrays[name]
    local output = {}
    local target = tonumber(active_index)

    for i, val in ipairs(items) do
        if i == target then
            -- 指定されたインデックスなら黒丸
            table.insert(output, "\\kyouteovalblackUSEINTERNAL{" .. val .. "}")
        else
            -- それ以外は白丸
            table.insert(output, "\\jegg{" .. val .. "}")
        end
    end
    
    -- \hfill で結合してTeXに出力
    tex.print(table.concat(output, "\\hfill "))
end
\end{luacode*}

% 配列作成マクロ
\newcommand{\MarkArrayMake}[2]{%
    \directlua{register_mark_array("\luaescapestring{#1}", "\luaescapestring{#2}")}%
}

% マークシート表示マクロ
% 第3引数(オプション)があれば、内部のマクロ(#2)にその引数を渡す
% \MarkArrayMake{解答}{|ア|イ|ウ|エ|オ|}で配列作成
% \小問欄{6}{1}[center={\マークシート{5}{\解答マーク配列}}]で使う
\NewDocumentCommand{\マークシート}{ m m o }{%
  \makebox[#1\unit@KKran]{%
    \usefont{T1}{phv}{m}{n}\gtfamily%
    \IfNoValueTF{#3}{%
      #2% 引数なし（すべて白）
    }{%
      #2[#3]% 引数あり（指定箇所を黒く）
    }%
  }%
}

% （特に縦書きでマークに）$\pm$ みたいなのを入れる時など
% boxの寸法が想定と異なる場合に固定する
\newcommand{\MarkFixKK}[3]{%
  \ifnum\ltjgetparameter{direction}=3\relax%
    \lower.25\zw\vbox to #2{\vss\hbox to #1{\hss#3\hss}\vss}%
  \else%
    \vbox to #2{\vss\hbox to #1{\hss#3\hss}\vss}%
  \fi%
}
\endinput