Skip to content

Instantly share code, notes, and snippets.

@masak

masak/animal.p6 Secret

Created December 14, 2014 10:32
Show Gist options
  • Save masak/732867afd82801004c19 to your computer and use it in GitHub Desktop.
Save masak/732867afd82801004c19 to your computer and use it in GitHub Desktop.
class Guess {
has Str $.question;
has Guess $.yes;
has Guess $.no;
has Str $.animal;
method is-a-question { ?$.question }
method insert-question(
:$!question,
:$!yes = Guess.new(:$.animal),
:$!no = Guess.new(:$.animal)) {
}
method Str { $.animal }
}
my $root = Guess.new(
:question("Does it swim"),
:yes(Guess.new(:animal<fish>)),
:no(Guess.new(:animal<bird>)),
);
sub quit {
multi animals($q where *.is-a-question) { animals($q.yes), animals($q.no) }
multi animals($q) { $q.animal }
say "";
say "I now know these animals:";
say " $_" for animals($root);
exit;
}
sub is-prompt-yes($question) {
my $answer = prompt $question;
quit() if !defined $answer;
return so $answer.lc eq "y" | "yes";
}
say "Play 'Guess the animal'";
say "Think of an animal and the computer will try to guess it.";
while say("") && is-prompt-yes "Are you thinking of an animal? " {
my $guess = $root;
while $guess.is-a-question {
if is-prompt-yes $guess.question ~ "? " {
$guess.=yes;
}
else {
$guess.=no;
}
}
if is-prompt-yes "Is it a $guess? " {
say "Why not try another animal?";
next;
}
my $animal = prompt "The animal you were thinking of was a? ");
my $actual = Guess.new(:$animal);
say "Please type a question that would distinguish a $actual from a $guess";
my $question = (prompt "? ").trim.subst(/'?'$/, '');
if is-prompt-yes "For a $actual the answer would be? " {
$guess.insert-question(:$question, :yes($actual));
}
else {
$guess.insert-question(:$question, :no($actual));
}
}
quit;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment