![我正在做的石头剪刀布游戏中的 elif 语句有什么问题吗?](https://linux22.com/image/9129/%E6%88%91%E6%AD%A3%E5%9C%A8%E5%81%9A%E7%9A%84%E7%9F%B3%E5%A4%B4%E5%89%AA%E5%88%80%E5%B8%83%E6%B8%B8%E6%88%8F%E4%B8%AD%E7%9A%84%20elif%20%E8%AF%AD%E5%8F%A5%E6%9C%89%E4%BB%80%E4%B9%88%E9%97%AE%E9%A2%98%E5%90%97%EF%BC%9F.png)
制作剪刀石头布游戏来更好地学习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
您可以对随机选择的计算机玩家的移动进行类似的操作并确定结果。