Since no one knew of one, I had to write it myself.  Hopefully someone
else can also make use of it.  This is my first Ruby script, so please
do criticize so I can learn.  Thanks.



class Gtp

  def initialize (engine, input, output)
    @engine = engine
    @input = input
    @output = output
    @commands = {}

    AutoRegister(self)
    AutoRegister(@engine)

    #Re-register commands that were auto-registered under the wrong
gtp command name
    RegisterCommand("kgs-genmove_cleanup",
@engine.method(:gtp_kgs_genmove_cleanup))
  end

  def AutoRegister(provider)
    #Assumes methods that start with "gtp_" are implemented gtp commands
    for functionName in provider.methods
      if functionName.slice(0,4) == "gtp_"
        RegisterCommand(functionName.slice(4, functionName.length -
1), provider.method(functionName))
      end
    end
  end

  def RegisterCommand(name, function)
    #Overrides any previous registration for name or function
    @commands.delete_if {| key, value | value == function }
    @commands[name] = function
  end

  def ProcessCommands()
    #Main GTP command processing loop
    continue = true
    while continue
      continue = ProcessCommand(@input.gets)
    end
  end

  def ProcessCommand(commandLine)
    commandParts = commandLine.strip.split(" ")
    command = commandParts[0]
    args = commandParts.slice(1, commandLine.length - 1)
    if command
      if @commands[command]
        @output.puts "= " + @commands[command].call(*args).to_s
      else
        @output.puts "? Command not implemented: " << command
      end
      @output.puts
      @output.flush
    end
    command != "quit"
  end

  def TestCommand(commandLine)
    @output.puts "TEST>" << commandLine
    ProcessCommand(commandLine)
  end

  def gtp_list_commands(*unused)
    list = ""
    @commands.keys.sort.each {| commandName | list << commandName << "\n"}
    list
  end

  def gtp_known_command(command, *unused)
    @commands.has_key?(command)
  end

  def gtp_quit(*unused)
    ""
  end

end

# ---- Testbench ------------------------

class TestEngine
  def non_gtp_function
    #This should not show up as an implemented GTP command
  end
  def gtp_name(*unused)
    "TestEngine"
  end
  def gtp_kgs_genmove_cleanup(color, *unused)
    "a1"
  end
end

@engine = TestEngine.new
gtp = Gtp.new(@engine, $stdin, $stdout)
gtp.TestCommand("list_commands")
gtp.TestCommand("known_command quit")
gtp.TestCommand("known_command asdf")
gtp.TestCommand("asdf")
gtp.TestCommand("name")
gtp.ProcessCommands
_______________________________________________
computer-go mailing list
[email protected]
http://www.computer-go.org/mailman/listinfo/computer-go/

Reply via email to