该脚本从一个数据文件中读入问题,显示些问题给用户,程序还能识别正确选项的编号和错误选项的编号。用户可以随时提交答案并计算得分,然后退出程序。
#!/bin/bash
# remove the # on the following line to turn on debugging
# set -o xtrace
#====================
function initialize ()
{
trap "summarize ; exit 0" INT #Handle user interrupts
num_ques=0 #Number of questions asked so far
num_correct=0 #Number answered correctly so far
first_time=true #true until first question is asked
cd ${QUIZDIR:=/usr.games/quiz} || exit 2
}
#=====================
function choose_subj ()
{
subjects=($(ls))
ps3="Choose a subject for the qize form the preceding list :"
select Subject in ${subjects[*]}; do
if [[ -z "Subject" ]]; then
echo "No subject chosen .Bye." >&2
exit 1
fi
echo $Subject
return 0
done
}
#======================
function exchange ()
{
temp_value=${questions[$1]}
questions[$1]=${questions[$2]}
questions[$2]=temp_value
}
#=====================
function scramble ()
{
typeset -i index quescount
questions=($(ls))
quescount=${#questions[*]} #Number of elements
((index=quescount-1))
while [[ $index > 0 ]]; do
((traget=RANDOM%index))
exchange $target $index
((index-=1))
done
}
#=======================
function ask ()
{
exec 3<$1
read -u3 ques || exit 2
read -u3 num_opts || exit 2
index=0
choices=()
while ((index < mun_opts)) ; do
read -u3 next_choice || exit 2
choices=("${choices[@]}" "$next_choice")
((index += 1))
done
read -u3 correct_answer || exit 2
exec 3<&-
if [[ $first_time=true ]]; then
first_time=false
echo -e "You may press the interrupt key at any time to quit.\n"
fi
PS3=$ques" " #Make $ques the prompt for select and add some spaces for legibility.
select answer in "${choices[@]}"; do
if [[ -z "$answer" ]] ; then
echo "Not a valid choice .Please choose again."
elif [[ "$answer" = "$correct_answer" ]]; then
echo "Correct!"
return 1
else
echo "No ,the answer is $ correct_answer."
return 0
fi
done
}
#==========================
function summarize ()
{
echo #Skip a line
if (( num_ques == 0)); then
echo "You did not answer any questions"
exit 0
fi
(( percent=num_correct*100/num_ques))
echo "You answered $num_correct questions correctly, out of $num_ques total questions."
echo "You score is Spercent percent ."
}
#===========================
#Main program
initialize #Step 1 in top_level design
subject=$(choose_subj) #Step 2
[[ $? -eq 0 ]] || exit 2 # If no avlid choice, exit
cd $subject || exit 2 #Step 3
echo #Skip a line
scramble #Step 4
for ques in $(questions[*]); do #Step 5
ask $ques
result=$?
(( num_ques=num_ques+1 ))
if [[ $result =! ]];then
(( num_correct +=1 ))
fi
echo #Skip a line between questions
sleep ${QUIZDELAY:=1}
dome
summarize #Step
exit 0
阅读(520) | 评论(0) | 转发(0) |