두 플레이어 간에 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"

관련 정보