Linux:猜数游戏脚本

猜数游戏

执行脚本会随机生成一个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!

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

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值