猜数游戏
执行脚本会随机生成一个1-100之间的数字,由执行者猜,一共有6次机会: 如果在6次内猜对了,程序提示赢了并退出;
如果6次都没猜对则提示输了,并给出答案。 在猜的过程中程序会给出提示,如果猜的数字大于答案则提示大了; 如果所猜数字小于答案则提示小了。
如果输入为空或不是数字则会浪费一次机会。 所有的提示信息可自定义
猜数游戏也是初级编程的一个很经典的练习,下面用shell写一下:
num=$[ $RANDOM%100+1 ]for ((i=5;i>=0;i--))doread -p \"Please tell me your number:\" user_numif [[ $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.shPlease tell me your number:56The answer is greater than yours.You still have 5 chancesPlease tell me your number:66The answer is greater than yours.You still have 4 chancesPlease tell me your number:76The answer is greater than yours.You still have 3 chancesPlease tell me your number:86The answer is greater than yours.You still have 2 chancesPlease tell me your number:99The answer is less than yours.You still have 1 chancesPlease tell me your number:90Bingo!
(部分字体是有样式的。)