Created
May 22, 2012 16:21
-
-
Save riywo/2770060 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use strict; | |
use warnings; | |
use Time::HiRes qw/time/; | |
use Term::ANSIColor; | |
$SIG{INT} = 'print_score'; | |
my $from = defined $ARGV[0] ? $ARGV[0] : 100; | |
my $to = defined $ARGV[1] ? $ARGV[1] : 999; | |
die "Need from <= to ($from > $to)" if($from > $to); | |
my $say = 'say'; | |
my @scores = (); | |
while (1) { | |
my $num = int(rand $to - $from + 1) + $from; | |
$num =~ s/(\d{1,3})(?=(?:\d{3})+(?!\d))/$1,/g; | |
my $t1 = time; | |
my $ans; | |
do { | |
print 'What is the number?[NUM|r|e] : '; | |
system("$say $num"); | |
$ans = <STDIN>; chomp $ans; | |
} while ($ans =~ /r$/); | |
last if($ans eq 'e'); | |
my $time = time - $t1; | |
$ans =~ s/(\d{1,3})(?=(?:\d{3})+(?!\d))/$1,/g; | |
my $msg; | |
my $score = { | |
num => $num, | |
time => $time, | |
}; | |
if ($ans eq $num) { | |
print color 'bold green'; | |
$msg = "Right! ($num)"; | |
$score->{right} = 1; | |
} else { | |
print color 'bold red'; | |
$msg = "Wrong! (expect:$num got:$ans)"; | |
$score->{right} = 0; | |
} | |
push @scores, $score; | |
printf "[%.3f sec] %s\n", $time, $msg; | |
print color 'reset'; | |
} | |
print_score(); | |
sub print_score { | |
my $right_num = 0; | |
my $time_sum = 0; | |
exit if(scalar @scores == 0); | |
for (@scores) { | |
$right_num += 1 if($_->{right} == 1); | |
$time_sum += $_->{time}; | |
} | |
print "\n---------------------------------------\n"; | |
printf "rate: %d%% (%d/%d)\n", $right_num / scalar(@scores) * 100, $right_num, scalar(@scores); | |
printf "time: %.3f sec\n", $time_sum / scalar(@scores); | |
exit; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment