Elegant command-parsing in an OOP-based text game

前端 未结 5 1394
情话喂你
情话喂你 2021-02-09 01:52

I\'m playing with writing a MUD/text adventure (please don\'t laugh) in Ruby. Can anyone give me any pointers towards an elegant, oop-based solution to parsing input text? <

5条回答
  •  一生所求
    2021-02-09 02:37

    For command interpreters, I'm rather fond of this simple, not all that elegant pattern. Patterns in dynamic languages tend to involve fewer boxes and lines than GOF patterns.

    class Thing
    
      # Handle a command by calling the method "cmd_" + command.
      # Raise BadCommand exception if there is no method for that command.
    
      def handle_command(command, args)
        method_name = "cmd_#{command}"
        raise BadCommand, command unless respond_to?(method_name)
        send(method_name, args)
      end
    
      def cmd_quit(args)
        # the code for command "quit"
      end
    
      def cmd_list(args)
        # the code for command "list"
      end
    
      ...
    
    end
    

    In this way, adding a new command is just adding a new method. No tables or case statements need to be adjusted.

提交回复
热议问题