# Reads and writes to MegaHAL. # (Put this file in the same directory as megahal.exe) class MegaHAL def initialize @megahal = IO.popen("megahal.exe", "r+") while line = @megahal.gets puts "#{line}" # look for the end of the line that immediately precedes the first prompt if line =~ /(?:\.|\?|!)$/ then break end end end def putstr(s = '') s.strip! @megahal.puts("#{s}\n\n") getstr end def getResponse(s = '') return putstr(s) end def getstr full_response = "" while (line = @megahal.gets) =~ /^.*/ if line =~ /^(?: )?(?:\> )*(.*)/ then line = $1 end full_response << line.chomp << " " c = @megahal.getc # Check the first character of the next line if c == nil then break end if c.chr == ">" then break end # If it's the first chr of a prompt, break @megahal.ungetc(c) #If it's not a prompt, push the chr back on the stream. end return full_response end end if $0 == __FILE__ megahal = MegaHAL.new print "\n> "; $stdout.flush quitwords = [":q", "quit", "bye", "exit"] while (line = gets) !~ /^(#{quitwords.join('|')})+/ and line !~ /^$/ puts megahal.putstr(line.to_s) print "\n> "; $stdout.flush end megahal.putstr("\#quit\n") print "Bye!" end