Bashをもっと学ぶためにはさみロックゲームを作ってください。何らかの理由で、私のelifステートメントが好きではなく、その理由を理解していません。そしてもっと良い方法があれば教えてくれてありがとう!
#!/bin/bash
#rock beats scissors, scissors beats paper, paper beats rock,
printf "Welcome to rock paper scissors. Type 'r', 'p', or 's' to start: "
#get users selection
read user
#detect input and assign it to a num that will be used to check against computer.
if [[ $user == [rR] || $user == "Rock" || $user == "rock" ]]
then
user="r"
elif [[ $user == [sS] || $user == "scissors" || $user == "Scissors" ]]
then
user="s"
elif [[ $user == [pP] || $user == "paper" || $user == "Paper" ]]
then
user="p"
else
printf "Not a valid submission, you entered: $user\n"
fi
#get random number between 1 and 9
comp=$(shuf -i 1-9 -n 1)
#detect what number it was and assign either r p s to it.
if ((1<=$comp && $comp<=3))
then
comp="r"
printf "Rock\n"
elif ((4<=$comp && $comp<=6))
then
comp="s"
printf "Scissors\n"
elif ((6<=$comp && $comp<=9))
then
comp="p"
printf "Paper\n"
else
echo "not in range?"
fi
#find out who won
if [[ $user == $comp ]]
then
echo "same!"
elif [[ $user == "r" && $comp == "p" ]]
echo "user rock comp paper COMP WINS"
elif [[ $user == "p" && $comp == "r" ]]
echo "comp rock user paper USER WINS"
elif [[ $user == "s" && $comp == "r" ]]
echo "user scissors comp rock COMP WINS"
elif [[ $user == "r" && $comp == "s" ]]
echo "user rock comp scissors USER WINS"
elif [[ $user == "p" && $comp == "s" ]]
echo "user paper comp scissors COMP WINS"
elif [[ $user == "s" && $comp == "p" ]]
echo "user scissors comp paper USER WINS"
else
echo "something is borked"
fi
次のエラーが発生します。
./rps.sh: line 49: syntax error near unexpected token `elif'
./rps.sh: line 49: `elif [[ $user == "p" && $comp == "r" ]]'
答え1
このようなタスクを実行するより読みやすい方法は、case
ステートメントを使用することです。
move=''
while [[ -z "$move" ]]; do
echo "Please specify paper, scissors, or rock. >"
read userinput
case "$userinput" in
[Rr]*)
move="rock"
;;
[Pp]*)
move="paper"
;;
[Ss]*)
move="scissors"
;;
*)
echo "Invalid input."
;;
esac
done
ランダムに選択されたコンピュータプレーヤーの動きで同様のタスクを実行し、結果を決定できます。