Twitter で見かけた以下の投稿を関数ぽく書きなおしてみました。
.bat(バッチファイル)でダイスを振るだけ
http://qiita.com/sawa_tsuka/items/5787d969aed9e3440289
dice.bat
@echo off
set SELF=%~n0
set TEST=0
setlocal enabledelayedexpansion
if %TEST% equ 1 (
:BOL-#0
call :dice "%~1" e || exit /b -1
echo.
echo 合計は !e! です。
call :Q "継続しますか? (Y/N) " || exit /b !e!
goto BOL-#0
) else (
call :dice "%~1" e || exit /b -1
echo.
echo 合計は !e! です。
exit /b !e!
)
endlocal
goto :EOF
:usage
setlocal
>&2 echo Usage: %SELF% [#_OF_DICE]
endlocal
goto :EOF
:error
setlocal
set s=%~1
if "%s%" == "" set s=one or more error^(s^) has been occurred
>&2 echo %SELF%: %s%
endlocal
goto :EOF
:isnumeric
setlocal
(echo %~1) | findstr /r "[0-9]" > NUL
endlocal
goto :EOF
:Q
setlocal
:BOL-#1
echo.
set /p A=%~1
if /i "%A%" == "Y" exit /b 0
if /i "%A%" == "N" exit /b 1
goto BOL-#1
endlocal
goto :EOF
:randomize
setlocal
set /a r=%RANDOM%%%6+1
endlocal & set %~1=%r%
goto :EOF
:dice
setlocal enabledelayedexpansion
:: argument #1
if "%~1" == "" (set n=2) else (set n=%~1)
call :isnumeric "%n%" || (call :usage & exit /b -1)
if %n% lss 1 (call :error "illegal value: use 1-" & exit /b -1)
:: argument #2
if "%~2" == "" (call :error "insufficient arguments: #2" & exit /b -1)
set /a i=1,s=0
:BOL-#2
call :randomize r
call :dice-#%r% %i% || exit /b -1
set /a s+=r,i+=1
if %i% leq %n% goto BOL-#2
if %TEST% equ 1 cls
for /l %%i in (0,1,4) do (
for /l %%j in (1,1,%n%) do (
< NUL set /p t=!d[%%j][%%i]!
)
echo.
)
endlocal & (set %~2=%s%) & exit /b 0
goto :EOF
:dice-#1
call :isnumeric "%~1" || exit /b 1
set d[%~1][0]=┌―――┐
set d[%~1][1]=| |
set d[%~1][2]=| ● |
set d[%~1][3]=| |
set d[%~1][4]=└―――┘
exit /b 0
goto :EOF
:dice-#2
call :isnumeric "%~1" || exit /b 1
set d[%~1][0]=┌―――┐
set d[%~1][1]=|● |
set d[%~1][2]=| |
set d[%~1][3]=| ●|
set d[%~1][4]=└―――┘
exit /b 0
goto :EOF
:dice-#3
call :isnumeric "%~1" || exit /b 1
set d[%~1][0]=┌―――┐
set d[%~1][1]=|● |
set d[%~1][2]=| ● |
set d[%~1][3]=| ●|
set d[%~1][4]=└―――┘
exit /b 0
goto :EOF
:dice-#4
call :isnumeric "%~1" || exit /b 1
set d[%~1][0]=┌―――┐
set d[%~1][1]=|● ●|
set d[%~1][2]=| |
set d[%~1][3]=|● ●|
set d[%~1][4]=└―――┘
exit /b 0
goto :EOF
:dice-#5
call :isnumeric "%~1" || exit /b 1
set d[%~1][0]=┌―――┐
set d[%~1][1]=|● ●|
set d[%~1][2]=| ● |
set d[%~1][3]=|● ●|
set d[%~1][4]=└―――┘
exit /b 0
goto :EOF
:dice-#6
call :isnumeric "%~1" || exit /b 1
set d[%~1][0]=┌―――┐
set d[%~1][1]=|● ●|
set d[%~1][2]=|● ●|
set d[%~1][3]=|● ●|
set d[%~1][4]=└―――┘
exit /b 0
goto :EOF
位置パラメーターの指定や実行結果は以下をご覧ください。
おもな変更点は以下のとおりです。
- ラベル,setlocal ... endlocal,goto :EOF などを利用して関数的な表現に変更
- 位置パラメーターを指定することでサイコロの数を変更可能
- 終了ステータス(環境変数 ERRORLEVEL の値)からも合計値を参照可能
- 擬似乱数の取得方法を変更(変更前と後とで精度に変化なし)
- エラー処理を追加
- 対話モードを実装(バッチ変数 TEST の値を 1 に変更して実行)