如何在随机数猜游戏中将猜数限制为3

时间:2018-11-10 23:20:56

标签: bash

#!/bin/bash
echo "Pick a number between 1 and 10"       
read ANS
echo "You guessed $ANS"
VALUE=$[( $RANDOM % 10 ) +1]
if [ "$VALUE" -eq "$ANS" ]; then
    echo "You win!"
elif [ "$VALUE" -gt "$ANS" ]; then
    echo "Higher!"
elif [ "$VALUE" -lt "$ANS" ]; then    
    echo "Lower!"
fi

1 个答案:

答案 0 :(得分:0)

尝试一下:

#! /bin/bash

MAXTRIES=3
VALUE=$[( $RANDOM % 10 ) +1]

for (( i=1 ; i <= $MAXTRIES ; i++ )) ; do

    read -p "Pick a number between 1 and 10  " ANS

    echo "You guessed $ANS"

    if [ "$VALUE" -eq "$ANS" ]; then
        echo "You win!"
        break
    fi

    if [ $i -ge $MAXTRIES ] ; then
        echo "You have exceeded $MAXTRIES tries!"
        break

    elif [ "$VALUE" -gt "$ANS" ]; then
        echo "Higher!"

    elif [ "$VALUE" -lt "$ANS" ]; then
        echo "Lower!"
    fi

done