#!/usr/bin/perl
# Created:06-11-01
# By Jeff Connelly

# Quiz Whiz Trivia generator for All-Connected custom Card

# All-Connected card pre-calculated answers
@answers = map { ord($_)-ord('A') }
           map { $_ eq " " || $_ eq "\n" ? () : $_ }
           split //, <<___;
BCDBDBBDBDDABBABDBDB
CACAAAADDACDBACDBBBB
CAACCACACABCDCDBDBDC
A
___


print "Loading DB...";
open(DB, "<trivia.db") || die "cannot open trivia.db: $!";
while(<DB>)
{
    chomp;
    my ($q, $a, $c, $d, $e, $f) = split /:/;
    $questions{$q} = [ $a, $c, $d, $e, $f ];        # Answer, choices
}
close(DB);
print scalar keys %questions, "\n";

print <<BLURB;
Welcome to Jeff's Quiz Whiz All-Connected Card Trivia Generator

Before you begin, make sure that your custom All-Connected card
is securely inserted into Quiz Whiz's book slot. If it is not,
you'll get wrong answers.

BLURB

while()
{
    my ($q, $a, @ch, $quizwhiz_a);

    $q = (keys %questions)[rand scalar keys %questions];
    if (exists $completed{$q})
    {
        next;       # User already did this. Don't bore them.
    }
    $completed{$q} = undef;
    $a = shift @{$questions{$q}};     # First element is answer index
    @ch = @{$questions{$q}};

    # Quiz Whiz's All-Connected card has fixed answers, so we have to choose
    # a random question ID and use that, making sure the right answer is in
    # the right place 
    $qid = int rand @answers;

    print "$qid: $q\n";

    #print "CH: @ch\n";
    #print "A: $a\n";
    #print "CH[A]: $ch[$a]\n";
    #print "CH[ANSWERS[QID]]: $ch[$answers[$qid]]\n";

    # The correct answer has to be choice $answers[$qid]. Swap $answer[$qid]
    # with $a, so that they're in the right places.

    $quizwhiz_a = $answers[$qid];       # Correct Quiz Whiz answer

    #my $last_a = $ch[$a];               # Takes place of given answer
    #$ch[$quizwhiz_a] = $ch[$a];         # Must be right answer (given)
    #$ch[$a] = $last_a;

    ($ch[$a], $ch[$quizwhiz_a]) = ($ch[$quizwhiz_a], $ch[$a]);

    foreach my $ch (0..$#ch)    # display choices
    {
        print chr($ch+ord('A')).". $ch[$ch]\n";
    }
    print ">";
    <>;
}
