Shell脚本实现的猜数字小游戏
生成的密码和用户输入可以接受重复数字。
所以相对一般规则的猜数字可能难度要大不少。
本版本规则:
A--数字对,位置也对
B--排除A的结果后,数字对,但位置不对
开始后,系统化初始化一个4位可重复数字,如“1223”。假设用户第一次输入“1234”,那么系统将提示“2A1B”,前两位数字“12”相同并且位置也相同,为“2A”。后两位数字中,用户输入的“3”与密文中“3”相同,但两者位置不同,则为“1B”,最终结果为“2A1B”。
再假设用户此时输入“1232”,那么结果则为“2A2B”,计算方法与前次一样。
代码如下:
#!/bin/bash
clear
echo
echo"###################################################################"
echo"#thisisabash-shellgamewritebyEmail:breeze7086@gmail.com#"
echo"#thegamecalled*digits*,andthisversionhaverepeatednumbers#"
echo"#version1.0#"
echo"###################################################################"
echo-e"\n\n"
declareINPUT
declarePASSWORD
declareA
declareB
declareX
declareY
declareLOOP
#ThisfuntioninitthevariablePASSWORDthatuserneedtoguess
init_password()
{
PASSWORD=`echo$(($RANDOM%10000))`
echo$PASSWORD|grep'^[0-9]\{4\}$'>/dev/null2>&1
if[$?!=0]
then
init_password
else
input
fi
}
#Thisfuntionaccepttheinputfromuser'skeyboard
input()
{
echo-n"pleaseinputanumberbetween0000-9999:"
readINPUT
echo$INPUT|grep'^[0-9]\{4\}$'>/dev/null2>&1
if[$?!=0]
then
echo"retryanumberbetween0000-9999anddonotinputachar"
input
else
judge
fi
}
#Thisfuntionisthemainfuntion
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
}
#ThisfuntioncountthevariableA'svalue
judge_a()
{
foriin`seq4`
do
VAR_INPUT=`exprsubstr"$X"$i1`
forjin`seq4`
do
VAR_PASSWORD=`exprsubstr"$Y"$j1`
if[[$VAR_INPUT=$VAR_PASSWORD&&$VAR_INPUT!=""&&$VAR_PASSWORD!=""&&$i=$j]]
then
A=`expr$A+1`
X=`exprsubstr$X1"$[$i-1]"``exprsubstr$X"$[$i+1]"4`
Y=`exprsubstr$Y1"$[$i-1]"``exprsubstr$Y"$[$i+1]"4`
judge_a
fi
done
done
}
#ThisfuntioncountthevariableB'svalue
judge_b()
{
foriin`seq4`
do
VAR_INPUT=`exprsubstr"$X"$i1`
forjin`seq4`
do
VAR_PASSWORD=`exprsubstr"$Y"$j1`
if[[$VAR_INPUT=$VAR_PASSWORD&&$VAR_INPUT!=""&&$VAR_PASSWORD!=""]]
then
B=`expr$B+1`
X=`exprsubstr"$X"1"$[$i-1]"``exprsubstr"$X""$[$i+1]"4`
Y=`exprsubstr"$Y"1"$[$j-1]"``exprsubstr"$Y""$[$j+1]"4`
judge_b
fi
done
done
}
#Thisisthebeginofscript
LOOP=1
init_password
echo"#############################################"
echo"#congratulations!Youhavetried$LOOPtimes!#"
echo"#Thepasswordis$PASSWORD!#"
echo"#############################################"