#!/bin/zsh initialize() { num_ques=0 num_correct=0 cd ${QUIZDIR:=/usr/games/lib/quiz} || exit 2 } choose_subj() { set -A subjects $(command ls) PS3="Choose a subject for the quiz: " select Subject in $subjects; do if [[ -z "$Subject" ]]; then print -u2 "No subject chosen. Bye." exit 0 fi print $Subject return 0 done } scramble() { typeset -i index quescount set -A questions $(command ls) quescount=${#questions} ((index = quescount)) while ((index > 1)); do ((target = $RANDOM % index + 1)) exchange $target $index ((index -= 1)) done } exchange() { local temp_value temp_value=$questions[$1] questions[$1]=$questions[$2] questions[$2]=$temp_value } ask() { set -A choices exec 3<$1 read -u3 ques || exit 2 read -u3 num_opts || exit 2 index=0 while (( index < num_opts )); do read -u3 next_choice || exit 2 choices=($choices $next_choice) (( index += 1 )) done read -u3 correct_answer || exit 2 exec 3<&- print "You may press the Interrupt key at any time to quit.\n" PS3=$ques" " # Make $ques the prompt for select, but add some spaces for legibility. select answer in $choices; do if [[ -z "$answer" ]]; then print "Not a valid choice. Please try again." elif [[ "$answer" = "$correct_answer" ]]; then print "Correct!" return 0 else print "No, the answer is $correct_answer" return 1 fi done } summarize() { if (( num_ques == 0 )); then print "You did not answer any questions." exit 0 fi (( percent = num_correct*100/num_ques )) print "You answered $num_correct questions correctly," print "out of $num_ques total questions." print "Your score is $percent percent" } # Main program initialize trap 'summarize; exit 0' INT subject=$(choose_subj) [[ $? -eq 0 ]] || exit 2 print cd $subject || exit 2 scramble for ques in ${questions}; do ask $ques result=$? (( num_ques += 1 )) if (( result == 0 )); then (( num_correct += 1 )) fi print sleep ${QUIZDELAY:=1} done summarize exit 0