我正在做的石头剪刀布游戏中的 elif 语句有什么问题吗?

我正在做的石头剪刀布游戏中的 elif 语句有什么问题吗?

制作剪刀石头布游戏来更好地学习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

您可以对随机选择的计算机玩家的移动进行类似的操作并确定结果。

相关内容