分类:
2005-12-22 12:05:44
#!/usr/bin/perl
use Getopt::Std;
@orig_num;
@guess_num;
sub show_usage() {
print "Usage: $0 ";
print " -h Show this help message ";
print " -r Show rules of the game ";
print " -p play game ";
exit 0;
}
sub show_rules() {
print "Welcome to This GUESS NUMBER GAME~! ";
print "There is a integer which contains four digits. And each digit of the integer is different from each other. ";
print "You have 8 chances to guess the integer. ";
print "I will show you how many right numbers having right digits with [0-9]A and how many numbers you guess are right but the digits you put are wrong with [0-9]B ";
}
sub generate_rand() {
my $i = 0;
my $j = 0;
my $seed=time();
srand($seed);
while($i<4) {
my $rand = int(rand(9));
if(($i == 0) && ($rand == 0)) {
next;
}
for($j = 0; $j < $i; $j++) {
if($rand == $orig_num[$j]) {
$rand = 11;
last;
}
}
if($rand < 10) {
$orig_num[$i] = $rand;
$i ++;
}
}
# print @orig_num," ";
}
sub get_guess_number() {
my $num_tmp;
print "Please input the number you guessed: ";
read(STDIN,$num_tmp,4);
chomp($num_tmp);
return $num_tmp;
print " ";
}
sub check_res() {
my $i, $j;
my $a = 0, $b = 0;
for($i = 0; $i < 4; $i ++) {
for($j = 0; $j < 4; $j ++) {
if($orig_num[$i] == $guess_num[$j]) {
if($i == $j) {
$a++;
}
else {
$b++;
}
}
}
}
if($a != 4) {
return "[$a]A[$b]B";
}
}
sub play_game() {
generate_rand();
my $i = 0;
my $num_guess_tmp;
while($i < 8) {
$num_guess_tmp = get_guess_number();
@guess_num = split(//,$num_guess_tmp);
$result=check_res();
if("$result" eq "") {
print "Congratulations! You win!~~~~~~~ ^_^ ";
exit 0;
}
else {
print "The result is: $result "
}
$i ++;
}
if($i == 8)
{
print "I am sorry you lose. The number is @orig_num. ";
exit 0;
}
}
sub get_opts() {
getopts(''hrp'');
if(defined($opt_p)) {
play_game();
}
elsif((not defined($opt_h))&&(not defined($opt_r))) {
show_usage();
}
elsif(defined($opt_r)) {
show_rules();
}
if(defined($opt_h)) {
show_usage();
}
}
get_opts();