原本想写点shell脚本练练手,突发奇想试试做个猜数字游戏吧.于是就有了后续的事情.最先写了个最最原始的猜数字脚本.无论功能还是美观度都不尽如人意,于是一个一个版本迭代更新,后续版本每次都比前一次功能更完善.
通过这次的脚本练习我明白一个道理,"心急吃不了热豆腐" 亘古不变的真理啊,无论创业也好,做实事打工也罢,还的从头一步一步做起,凡是心高气傲一次性想做出完美产品的都不切实际.好的产品需要从用户需求出发,精雕细琢,层层迭代,才能经受更严峻的考验.
猜数字游戏原版V1
#给定一个不可变更的两位数,用户输入数字,程序提示大小,根据提示继续输入,直到正确输入数字为止,游戏结束.
#!/bin/bash num="32" while true do read -p "Please input a "double-digit": " input if [ $input -gt $num ] ; then echo "Try smaller!" elif [ $input -lt $num ];then echo "Try bigger!" else echo "Good! You are right!" break; fi done
猜数字游戏改进版V2
增加非法输入判断功能.
增加了随机数功能.
#!/bin/bash NUM=`echo $RANDOM$RANDOM |cut -c 2-3` while true do read -p "Please input a "double-digit": " input case $input in [0-9][0-9] ) if [ $input -gt $NUM ] ;then echo "Try smaller!" elif [ $input -lt $NUM ];then echo "Try bigger!" else echo "Good! You are right!" break; fi ;; *) read -p "Please input a "double-digit": " input ;; esac done
猜数字游戏改进版V3
增加了次数统计功能.
增加历史最好成绩前十排名功能.
增加时间显示功能.
优化结果显示.
#!/bin/bash NUM=`echo $RANDOM$RANDOM |cut -c 2-3` DATE=`date +%y%m%d-%H:%M` read -p "Please input your name: " USER while true do read -p "Please input a "double-digit": " input i=$((i+1)) case $input in [0-9][0-9] ) if [ $input -gt $NUM ] ;then echo "Try smaller!" elif [ $input -lt $NUM ];then echo "Try bigger!" else echo "Good! You are right!" break; fi ;; *) read -p "Please input a "double-digit": " input ;; esac done printf "%-12s %s\n" "<$USER>" "your record is $i! Try better next time! $DATE" |tee -a ./record.record printf "\n\n" printf "%15s %6s %-8s\n" "-----" "HISTORY RECORD" "-----" cat ./record.record |sort -k5 -g|awk -F! ‘{print $1,"!",$3}‘|head -10 printf "%15s %6s %-8s\n" "-----" "HISTORY RECORD" "-----"
本文出自 “statby的博客” 博客,请务必保留此出处http://statby.blog.51cto.com/7588140/1554538
原文地址:http://statby.blog.51cto.com/7588140/1554538