Skip to content

Instantly share code, notes, and snippets.

@Hayao0819
Last active May 12, 2022 15:25
Show Gist options
  • Save Hayao0819/caad8ef3952bdfef7287ef8c5d71e03c to your computer and use it in GitHub Desktop.
Save Hayao0819/caad8ef3952bdfef7287ef8c5d71e03c to your computer and use it in GitHub Desktop.
計算をして遊ぶゲーム miniは最小限の実装
#!/usr/bin/env bash
#-- Initilize script --#
set -eu
# shellcheck source=/dev/null
source /dev/stdin < <(curl -sL "https://github.com/Hayao0819/FasBashLib/releases/download/v0.2.1/fasbashlib.sh")
#-- Define --#
AvailableNumbers=()
NumberOfStart=5
TargetNumber=10
#-- Functions --#
HelpMessage(){ echo "There is nothing"; }
ParseExpr(){ sed -E "s|([0-9]+)|\1\n|g" <<< "${*}" | sed -E -e "s|(\+)|\1\n|g" -e "s|(\-)|\1\n|g" -e "s|(\*)|\1\n|g" -e "s|(\/)|\1\n|g" | grep -v "^$"; }
# Loop [回数] [コマンド]
Loop(){
local _T="$1"
shift 1 || return 1
ForEach "$@" < <(yes "" | head -n "$_T")
}
# ゲームのメイン関数
Game.Main(){
local InputExpr
Game.Start
while true; do
! Game.Ask || break
done
Game.Result
}
Game.Start(){
echo "四則演算をして最終的に\"$TargetNumber\"を作ろう"
# NumberOfStart回、0~9で乱数を取得してAvailableNumbersに追加
# shellcheck disable=SC2016
Loop "$NumberOfStart" eval 'ArrayAppend AvailableNumbers <<< $(( RANDOM % 10 ))'
}
Game.Result(){
echo "最終的に残ったのは${AvailableNumbers[0]}"
if [[ "${AvailableNumbers[0]}" = "${TargetNumber}" ]]; then
echo "クリア!"
else
echo "失敗!"
fi
exit 0
}
Game.Ask(){
local UsedNumber=()
echo "今回使える数字は以下のとおりです"
PrintArray "${AvailableNumbers[@]}" | ForEach echo "・ {}"
echo -n "式を入力してください: "
read -r InputExpr
echo
# 指定された式の数字が使えるかどうかを確認
local Num
while read -r Num; do
if ! PrintArray "${AvailableNumbers[@]}" | grep -qx "$Num"; then
echo "${Num}は使えません!"
AvailableNumbers+=("${UsedNumber[@]}")
unset UsedNumber
return 1
else
UsedNumber+=("$Num")
readarray -t AvailableNumbers < <(
local i unseted=false
for i in "${AvailableNumbers[@]}"; do
if [[ "$i" != "${Num}" ]] || [[ "$unseted" = true ]]; then
echo "$i"
else
unseted=true
fi
done
unset unseted i
)
fi
done < <(ParseExpr "$InputExpr" | grep -E "[0-9]+")
AvailableNumbers+=("$(( "$InputExpr" ))") 2> /dev/null
# もし数字が1つだけならゲームを終了する
if [[ "${#AvailableNumbers[@]}" = 1 ]]; then
return 0
else
return 2
fi
}
#-- Parse args --#
ParseArg LONG="help" SHORT="h" -- "$@"
eval set -- "${OPTRET[*]}"
while true; do
case "$1" in
"--help" | "-h")
HelpMessage
shift 1
;;
"--")
break
shift 1
;;
esac
done
Game.Main
@Hayao0819
Copy link
Author

@Hayao0819
Copy link
Author

@Hayao0819
Copy link
Author

@Hayao0819
Copy link
Author

@Hayao0819
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment