您的位置:首页 > 运维架构 > Linux

Linux:猜数游戏脚本

2020-08-06 09:03 162 查看

猜数游戏

执行脚本会随机生成一个1-100之间的数字,由执行者猜,一共有6次机会: 如果在6次内猜对了,程序提示赢了并退出;
如果6次都没猜对则提示输了,并给出答案。 在猜的过程中程序会给出提示,如果猜的数字大于答案则提示大了; 如果所猜数字小于答案则提示小了。
如果输入为空或不是数字则会浪费一次机会。 所有的提示信息可自定义

猜数游戏也是初级编程的一个很经典的练习,下面用shell写一下:

num=$[ $RANDOM%100+1 ]
for ((i=5;i>=0;i--))
do
read -p "Please tell me your number:" user_num
if [[ $user_num =~ ^[0-9]+$ ]]
then
[ $user_num -eq $num ] && echo -e "\033[5mBingo!\033[0m" && break
[ $user_num -lt $num ] && echo -e "The answer is \033[31mgreater\033[0m than yours."
[ $user_num -gt $num ] && echo -e "The answer is \033[31mless\033[0m than yours."
fi
[[ $i -ne 0 ]] && echo -e "You still have \033[41;37m$i\033[0m chances"  || echo -e "\033[31mGame over!\033[0m The answer is \033[32m$num\033[0m. Be smarter next time!"
done

结果如下:

[root@Li~]# bash guess.sh
Please tell me your number:56
The answer is greater than yours.
You still have 5 chances
Please tell me your number:66
The answer is greater than yours.
You still have 4 chances
Please tell me your number:76
The answer is greater than yours.
You still have 3 chances
Please tell me your number:86
The answer is greater than yours.
You still have 2 chances
Please tell me your number:99
The answer is less than yours.
You still have 1 chances
Please tell me your number:90
Bingo!

(部分字体是有样式的。)

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: