我的猜谜游戏出了什么问题

我的猜谜游戏出了什么问题
#!/bin/bash
# this programe random numbers between 1 and 100. 
clear
echo "Hello, "${USER}
date;
n1=$[($RANDOM % 100) +1]
guess=1
echo -n "I'm think of a number between 1 and 100. guess:"

while read n2; do
if   [[ $n2 -eq $n1 ]]; then
break;
else
echo

if [[ $n2 -gt $n1 ]]; then
echo -n "Sorry, your guess is too high. guess new:"
elif [[ $n2 -lt $n1 ]]; then
echo -n "Sorry, your guess is too low. guess new:"
fi
fi
guess=$((guess+1))
done
echo
echo "congratulation! you win."
echo

read -p "do you want to try again (y/n)?" choice 

答案1

您没有while loop针对“是/否”提问的脚本。我在底部添加了一个脚本,以便脚本可以循环,直到答案为Nn。我“猜测”您正在寻找类似这样的内容:

#!/bin/bash
# this program random numbers between 1 and 100. 
clear
echo "Hello, "${USER}
date;
guess=1
## Start loop of game here
while true; do
n1=$(( ( RANDOM % 100 ) +1 ))
echo -n "I'm think of a number between 1 and 100. Guess: "

while read n2; do
    if [[ $n2 -eq $n1 ]]; then
        break;
    else
        if [[ $n2 -gt $n1 ]]; then
            echo -n "Sorry, your guess is too high. Guess again: "
        elif [[ $n2 -lt $n1 ]]; then
            echo -n "Sorry, your guess is too low. Guess again: "
        fi
    fi
    guess=$(( $guess + 1 ))
done
echo
echo "Congratulations! You win!"
if [[ $guess == 1 ]]; then
    echo "It took you $guess guess to get $n1."
else
    echo "It took you $guess guesses to get $n1."
fi
echo

read -p "Do you want to try again (y/n)? " choice
case $choice in
    [Yy]* ) guess=1;;
    [Nn]* ) exit;;
    * ) echo "Please answer yes or no.";;
esac
## End loop of game here
done

例子:

$ ./guess.bsh 
Hello, terrance
Thu Jan 10 13:27:39 MST 2019
I'm think of a number between 1 and 100. Guess: 75
Sorry, your guess is too high. Guess again: 50
Sorry, your guess is too high. Guess again: 25
Sorry, your guess is too high. Guess again: 10

Congratulations! You win!
It took you 4 guesses to guess 10.

Do you want to try again (y/n)? n

相关内容