#!/usr/bin/perl -w use strict; # This is the original version written by Merlyn, # http://www.perlmonks.org/?node_id=200391 ## I originally wrote this for a column, ## but haven't gotten around to using it yet. ## just think of an animal, and invoke it. ## It's an example of a self-learning game. ## When you choose not to continue, it'll dump out ## the data structure of knowledge it has accumulated. use Data::Dumper; my $info = "dog"; use Continuity; Continuity->new(port => 8080)->loop; sub stdin { my $request = shift; $request->print(qq{
}); $request->next; my $in = $request->param('in'); return $in; } sub main { my ($request) = @_; try($request, $info); redo if (yes($request,"play again?")); $request->print("Bye!\n"); $request->print(Dumper($info)); } sub try { my ($request, $this) = @_; if (ref $this) { return try($request,$this->{yes($request,$this->{Question}) ? 'Yes' : 'No' }); } if (yes($request,"Is it a $this")) { $request->print("I got it!\n"); return 1; }; $request->print("no!? What was it then? "); chomp(my $new = stdin($request)); $request->print("And a question that distinguishes a $this from a $new would be? "); chomp(my $question = stdin($request)); my $yes = yes($request,"And for a $new, the answer would be..."); $_[1] = { Question => $question, Yes => $yes ? $new : $this, No => $yes ? $this : $new, }; return 0; } sub yes { my $request = shift; $request->print("@_ (yes/no)?"); stdin($request) =~ /^y/i; }