Shell脚本实现的猜数字小游戏
(编辑:jimmy 日期: 2024/11/15 浏览:3 次 )
生成的密码和用户输入可以接受重复数字。
所以相对一般规则的猜数字可能难度要大不少。
本版本规则:
A--数字对,位置也对
B--排除A的结果后,数字对,但位置不对
开始后,系统化初始化一个4位可重复数字,如“1223”。假设用户第一次输入“1234”,那么系统将提示“2A1B”,前两位数字“12”相同并且位置也相同,为“2A”。后两位数字中,用户输入的“3”与密文中“3”相同,但两者位置不同,则为“1B”,最终结果为“2A1B”。
再假设用户此时输入“1232”,那么结果则为“2A2B”,计算方法与前次一样。
代码如下:
#!/bin/bash clear echo echo "###################################################################" echo "# this is a bash-shell game write by Email:breeze7086@gmail.com #" echo "# the game called *digits*,and this version have repeated numbers #" echo "# version 1.0 #" echo "###################################################################" echo -e "\n\n" declare INPUT declare PASSWORD declare A declare B declare X declare Y declare LOOP #This funtion init the variable PASSWORD that user need to guess init_password() { PASSWORD=`echo $(($RANDOM%10000))` echo $PASSWORD | grep '^[0-9]\{4\}$' >/dev/null 2>&1 if [ $"please input a number between 0000-9999:" read INPUT echo $INPUT | grep '^[0-9]\{4\}$' >/dev/null 2>&1 if [ $"retry a number between 0000-9999 and do not input a char" input else judge fi } #This funtion is the main funtion judge() { X=$INPUT Y=$PASSWORD while [ $INPUT != $PASSWORD ] do A=0 B=0 judge_a judge_b LOOP=`expr $LOOP + 1` echo "****************************" echo "* "$A"A"$B"B *" echo "****************************" input done } #This funtion count the variable A's value judge_a() { for i in `seq 4` do VAR_INPUT=`expr substr "$X" $i 1` for j in `seq 4` do VAR_PASSWORD=`expr substr "$Y" $j 1` if [[ $VAR_INPUT = $VAR_PASSWORD && $VAR_INPUT != "" && $VAR_PASSWORD != "" && $i = $j ]] then A=`expr $A + 1` X=`expr substr $X 1 "$[$i-1]"``expr substr $X "$[$i+1]" 4` Y=`expr substr $Y 1 "$[$i-1]"``expr substr $Y "$[$i+1]" 4` judge_a fi done done } #This funtion count the variable B's value judge_b() { for i in `seq 4` do VAR_INPUT=`expr substr "$X" $i 1` for j in `seq 4` do VAR_PASSWORD=`expr substr "$Y" $j 1` if [[ $VAR_INPUT = $VAR_PASSWORD && $VAR_INPUT != "" && $VAR_PASSWORD != "" ]] then B=`expr $B + 1` X=`expr substr "$X" 1 "$[$i-1]"``expr substr "$X" "$[$i+1]" 4` Y=`expr substr "$Y" 1 "$[$j-1]"``expr substr "$Y" "$[$j+1]" 4` judge_b fi done done } #This is the begin of script LOOP=1 init_password echo "#############################################" echo "#congratulations!You have tried $LOOP times! #" echo "# The password is $PASSWORD ! #" echo "#############################################"
下一篇:linux进程监控shell脚本代码