#!/bin/bash
clear
echo
echo "###################################################################"
echo "# this is a bash-shell game write by lee #"
echo "# this game is infinite frequency 猜数字 #"
echo "# version 2.1.1.20200421 #"
echo "###################################################################"
echo -e "\n\n"
declare INPUT
declare PASSWORD
declare LEN_PWD
declare A
declare B
declare LOOP
#this function is create random number
random_number()
{
PASSWORD=$RANDOM
LEN_PWD=`echo $PASSWORD | wc -L`
if [[ $LEN_PWD -ne 4 ]]
then
random_number
else
#输出标准值,测试需要,开发完成注释掉
echo $PASSWORD
input
fi
}
#this function is accept the input from user's keyboard
input()
{
read -n4 -p "please input a number between 0000-9999:" input
# 10#${input} 进制转换
if [[ 10#${input} -eq 10#${PASSWORD} ]]
then
echo -e "\n"
echo "#############################################"
echo "#congratulations!You have tried $LOOP times!#"
echo "# The password is $PASSWORD ! #"
echo "#############################################"
exit
elif [[ $LOOP -eq 6 ]]
then
echo -e "\n"
echo "You have tried $LOOP times!Game over!"
exit
else
A=0
B=0
count_a
count_b
echo -e "\n"
echo "****************************"
echo "* "$A"A"$B"B *"
echo "****************************"
echo "You have tried $LOOP times! You left `expr 6 - $LOOP` times!"
LOOP=`expr $LOOP + 1`
input
fi
}
#this function is count the variable A's value
count_a()
{
for i in `seq 4`
do
VAR_INPUT=`expr substr $input $i 1`
for j in `seq 4`
do
VAR_PASSWORD=`expr substr $PASSWORD $j 1`
if [[ $VAR_INPUT -eq $VAR_PASSWORD ]] && [[ $i -eq $j ]]
then A=`expr $A + 1`
fi
done
done
}
#this function is count the variable B's value
count_b()
{
for i in `seq 4`
do
VAR_INPUT=`expr substr $input $i 1`
for j in `seq 4`
do
VAR_PASSWORD=`expr substr $PASSWORD $j 1`
if [[ $VAR_INPUT -eq $VAR_PASSWORD ]] && [[ $i -ne $j ]]
then B=`expr $B + 1`
fi
done
done
}
LOOP=1
random_number