while 循环可以在两个玩家之间切换?

while 循环可以在两个玩家之间切换?

我可以使用 while 循环在游戏中的两个玩家之间切换吗?我有这个 bash while 循环,但它不起作用。我使用“U:代表用户”,“C”代表计算机。

U=0; c=0;
while [[ c -eq 0 ]] && [[ u -eq 0 ]]
 echo who goes first c or u 
read -n 1 input 
if [[ input == c ]]
then 
  c=1
else 
   if [[ input == u ]]
   then 
      u=1
    else 
    echo your input is not valid
   fi
fi
done

答案1

是的你可以。

但首先,测试应该使用变量值,而不是名称。而不是while [[ c -eq 0 ]]你应该使用:

while [[ "$c" -eq 0 ]]

这也适用于以后的几个测试,例如 [[ input == c ]] 应该是:

if [[ "$input" == c ]]

另外,开头的变量声明应该是(小写)

u=0; c=0;

不是U=0; c=0;

第三,do过了一段时间你就错过了:

u=0; c=0;
while [[ $c -eq 0 ]] && [[ $u -eq 0 ]]
do
    echo who goes first c or u 
    read -n 1 input 
    if [[ $input == c ]]
    then 
        c=1
    else 
        if [[ $input == u ]]
        then 
            u=1
        else 
            echo your input is not valid
        fi
    fi


done
echo "The var u is $u"
echo "The var c is $c"

这样可行。但使用 case 语句应该更容易:

while
    echo "Who goes first c or u? : "
    read -n1 input
do
    echo
    case $input in
        c)  c=1; u=0; break;;
        u)  c=0; u=1; break;;
        *)  echo "your input is not valid";;
    esac
done
echo "The var u is $u"
echo "The var c is $c"

或者,因为您使用的是普通 bash:

#!/bin/bash
while read -p "Who goes first c or u? : " -t10 -n1 input
do
    echo
    [[ $input == c ]] && { c=1; u=0; break; }
    [[ $input == u ]] && { c=0; u=1; break; }
    printf '%30s\n' "Your input is not valid"
done
echo "The var u is $u"
echo "The var c is $c"

或者可能:

#!/bin/bash
u=0; c=0
echo "Who goes first user or computer ? "
select input in user computer; do
    case $input in
        computer )  c=1; break;;
        user )      u=1; break;;
        *)          printf '%50s\n' "Your input \"$REPLY\" is not valid";;
    esac
done
echo "The var u is $u"
echo "The var c is $c"
echo "The selection was $input"

或者(正弦选择在 中input)更短:

echo "Who goes first ? "
select input in user computer; do
    [[ $input =~ user|computer ]] && break
    printf '%50s\n' "Your input \"$REPLY\" is not valid"
done
echo "The selection was $input"

相关内容