如何使用函数做出决策

时间:2015-04-25 23:25:21

标签: bash

我正在向Linux移植一个“选择你自己的冒险”游戏。游戏接受了用户输入并用它来确定“路径”。

我如何在Windows上执行此操作:

echo Do you turn left or right?
set /p a=
if %a%==left goto left
if %a%==right goto right
:left
echo You go left.
echo Now, do you continue down the cave or...

:right
echo You go right.
echo Now, do you... ect.

我如何在Linux中执行此操作?

2 个答案:

答案 0 :(得分:0)

bash中没有goto。您可以使用case代替游戏:

#!/bin/bash

pos=start

while [[ $pos != quit ]] ; do
    case $pos in
        (start) echo You are in a room. You can go left or right.
            until [[ $pos == @(left|right) ]] ; do
                read pos
            done
            ;;

        (left) echo You go left.
            # ...
            ;;

        (right) echo You go right.
            pos=quit
            ;;
    esac
done

答案 1 :(得分:0)

将代码翻译成bash的几乎1:1可以用这样的函数编写

#!/bin/bash

left() {
  echo You go left.
  echo Now, do you continue down the cave or...
}

right() {
  echo You go right.
  echo Now, do you... ect.
}


echo -n "Do you turn left or right? "
read a
[ $a = "left" ]  && left
[ $a = "right" ] && right