Advertisement
Guest User

Random Name Generator VX v1.0

a guest
Jan 29th, 2012
745
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 16.33 KB | None | 0 0
  1. #  Random Name Generator VX script
  2. #
  3. #  Created: 29 January 2012 by Logan Forrests
  4. #  Last Updated: 29 January 2012 by Logan Forrests
  5. #
  6. #  Based on the Perl scripts by Chris Pound
  7. #    http://www.ruf.rice.edu/~pound/
  8. #
  9. #  Translated to Ruby by Alan Skorkin
  10. #    http://www.skorks.com/2009/07/how-to-write-a-name-generator-in-ruby/
  11. #
  12. #  Includes the library for GetoptLong by Motoyuki Kasahara
  13. #    http://www.sra.co.jp/people/m-kasahr/ruby/getoptlong/getoptlong.rb
  14. #
  15. #  RPG Maker VX version & Compatibility Fix by Logan Forrests
  16. #
  17. #  Copyright belongs to the appropriate authors. Credit must be provided.
  18. #
  19. #     Random Name Generator
  20. #      
  21. #        Translated to Ruby by Alan Skorkin
  22. #        Original version (Perl) by Chris Pound
  23. #        Name Data Sets by Chris Pound, Alan Skorkin
  24. #        GetoptLong Library by Motoyuki Kasahara
  25. #
  26. #      Does not require credit:
  27. #        RPG Maker VX version & Compatibility Fix by Logan Forrests
  28. #
  29. # These are the only things that can be changed in this script.
  30. #
  31. # Specify the location of the data file:
  32. RNG_NUMBER_OF_WORDS = 10      #Number of words to generate; randomly picks one
  33. RNG_FOLDER_NAME = "Data/"          #The folder in which to find the file
  34. RNG_DATA_FILE = "name_input_data.txt"    #The data file; must be a .txt file
  35.  
  36. #############################################################################
  37. #############################################################################
  38. #         Do Not Change Anything Below This Line (line 38)
  39. #############################################################################
  40. #############################################################################
  41. class NameGenerator
  42.   def initialize(follower_letters, min_length = 3, max_length = 9)
  43.     @min_word_length = min_length
  44.     @max_word_length = max_length
  45.     @follower_letters = follower_letters
  46.   end
  47.  
  48.   def generate_name(word)
  49.     last_pair = word[-2, 2]
  50.     letter = @follower_letters[last_pair]
  51.     letter = letter.slice(rand(@follower_letters[last_pair].length), 1)
  52.     if word =~ /\s$/
  53.       return word[0, @max_word_length] unless word.length <= @min_word_length
  54.       return generate_name(word[-1, 1]+letter)
  55.     else
  56.       word = word.gsub(/^\s/, '')
  57.       return generate_name(word+letter)
  58.     end
  59.   end
  60.  
  61.   def generate_names(start_pairs, count = 10)
  62.     names = []
  63.     count.times do |i|
  64.       names.push(generate_name(start_pairs[rand start_pairs.length]).capitalize)
  65.     end
  66.     return names
  67.   end
  68. end
  69.  
  70.  
  71. class DataHandler
  72.   attr_reader :follower_letters, :start_pairs
  73.   def initialize
  74.     @start_pairs = []
  75.     @follower_letters = Hash.new('')
  76.   end
  77.  
  78.   def read_data_file(data_file)
  79.     File.open(data_file, 'r') do |file|
  80.       chars = file.read.chomp.downcase.gsub(/\s/, ' ').chars.to_a
  81.       chars.push(chars[0], chars[1])
  82.       populate_followers_and_start_pairs(chars)
  83.     end
  84.   end
  85.  
  86.   def populate_followers_and_start_pairs(chars)
  87.     (chars.length-2).times do |i|
  88.       if chars[i] =~ /\s/
  89.         @start_pairs.push(chars[i+1, 2].join)
  90.       end
  91.       @follower_letters[chars[i, 2].join]=@follower_letters[chars[i,2].join]+chars[i+2,1].join
  92.     end
  93.   end
  94.  
  95.   private :populate_followers_and_start_pairs
  96. end
  97.  
  98.  
  99. class ArgumentParser
  100.   attr_reader :data_file, :words_to_generate
  101.  
  102.   def initialize
  103.     @opts = GetoptLong.new(
  104.       ["--datafile", "-d", GetoptLong::OPTIONAL_ARGUMENT],
  105.       ["--number-of-words", "-n", GetoptLong::OPTIONAL_ARGUMENT]
  106.     )
  107.     @data_file = "data.txt"
  108.     @words_to_generate = 10
  109.   end
  110.  
  111.   def parse_arguments
  112.     @opts.each do |opt, arg|
  113.       case opt
  114.       when '--datafile'
  115.         @data_file = arg
  116.       when '--number-of-words'
  117.         @words_to_generate = arg
  118.       end
  119.     end
  120.   end
  121.  
  122.  
  123. #  def display_usage
  124. #    puts "Sample usage:"
  125. #    puts "ruby name_generator_main.rb -d <data-file>.txt -n <x>"
  126. #    puts "<data-file>.txt is the name of a file with sample names to use as input"
  127. #    puts "<x> -  the number of words to generate"
  128. #    puts "both arguments are optional"
  129. #  end
  130. end
  131.  
  132.  
  133. # RPG Maker VX Compatibility Fix by Logan Forrests
  134. #
  135. #   Due to the original scripts being written for a Ruby version higher than
  136. # that used by RPG Maker VX (1.8.1) some method calls do not exist. This fix
  137. # makes edits to the non-working code to bring it back to the 1.8.1 version.
  138. #
  139. class NameGenerator
  140.  
  141.   alias :lgnfrsts_rng_init_ru5j :initialize
  142.   def initialize(*args, &block)
  143.     lgnfrsts_rng_init_ru5j(*args, &block)
  144.     @limit = 0
  145.     @depth_limit = 20
  146.   end
  147.  
  148.   alias :lgnfrsts_rng_genname_eu84 :generate_name
  149.   def generate_name(*args, &block)
  150.     #run original unless reached depth limit
  151.     word = ""
  152.     if @limit < @depth_limit
  153.       @limit += 1
  154.       word = lgnfrsts_rng_genname_eu84(*args, &block)
  155.     end
  156.     @limit = 0 #reset limit
  157.     return word
  158.   end
  159.  
  160.   #Allow setting of max length, but ensure it cannot be more than
  161.   # the max allowed for NameInput
  162.   def max_length=(max)
  163.     @max_length = [max, 16].min
  164.   end
  165.  
  166.   #Allow setting of max length, but ensure it cannot be more than
  167.   # the max_length, nor less than 0.
  168.   def min_length=(min)
  169.     @min_length = [[@max_length, min].min, 0].max
  170.   end
  171.  
  172. end
  173.  
  174.  
  175. class DataHandler
  176.  
  177.   #In the original script, the call on the string object '.chars' is used.
  178.   # This is not available in Ruby 1.8.1. Here it has been replaced with
  179.   # a traditional method of extracting characters from a string via the use
  180.   # of .scan
  181.   def read_data_file(data_file)
  182.     File.open(data_file, 'r') do |file|
  183.       string = file.read.chomp.downcase.gsub(/\s/, ' ')
  184.       chars = []
  185.       string.scan(/./) { |re| chars.push(re) }
  186.       chars.push(chars[0], chars[1])
  187.       populate_followers_and_start_pairs(chars)
  188.     end
  189.   end
  190.  
  191. end
  192.  
  193.  
  194. class ArgumentParser
  195.  
  196.   #Overwritten to account for
  197.   def initialize
  198.     @opts = GetoptLong.new(
  199.       ["--datafile", "-d", GetoptLong::OPTIONAL_ARGUMENT],
  200.       ["--number-of-words", "-n", GetoptLong::OPTIONAL_ARGUMENT]
  201.     )
  202.     @data_file = RNG_FOLDER_NAME + RNG_DATA_FILE
  203.     @words_to_generate = RNG_NUMBER_OF_WORDS
  204.   end
  205.  
  206. end
  207.  
  208.  
  209. #===============================================================================
  210.  
  211. #                                                         -*- Ruby -*-
  212. # Copyright (C) 1998, 1999, 2000  Motoyuki Kasahara
  213. #
  214. # You may redistribute it and/or modify it under the same license
  215. # terms as Ruby.
  216. #
  217.  
  218. #
  219. # Documents and latest version of `getoptlong.rb' are found at:
  220. #    http://www.sra.co.jp/people/m-kasahr/ruby/getoptlong/
  221. #
  222.  
  223. #
  224. # Parse command line options just like GNU getopt_long().
  225. #
  226. class GetoptLong
  227.   #
  228.   # Orderings.
  229.   #
  230.   ORDERINGS = [REQUIRE_ORDER = 0, PERMUTE = 1, RETURN_IN_ORDER = 2]
  231.  
  232.   #
  233.   # Argument flags.
  234.   #
  235.   ARGUMENT_FLAGS = [NO_ARGUMENT = 0, REQUIRED_ARGUMENT = 1,
  236.     OPTIONAL_ARGUMENT = 2]
  237.  
  238.   #
  239.   # Status codes.
  240.   #
  241.   STATUS_YET, STATUS_STARTED, STATUS_TERMINATED = 0, 1, 2
  242.  
  243.   #
  244.   # Error types.
  245.   #
  246.   class AmbigousOption   < StandardError; end
  247.   class NeedlessArgument < StandardError; end
  248.   class MissingArgument  < StandardError; end
  249.   class InvalidOption    < StandardError; end
  250.  
  251.   #
  252.   # Initializer.
  253.   #
  254.   def initialize(*arguments)
  255.     #
  256.     # Current ordering.
  257.     #
  258.     if ENV.include?('POSIXLY_CORRECT')
  259.       @ordering = REQUIRE_ORDER
  260.     else
  261.       @ordering = PERMUTE
  262.     end
  263.  
  264.     #
  265.     # Hash table of option names.
  266.     # Keyes of the table are option names, and their values are canonical
  267.     # names of the options.
  268.     #
  269.     @canonical_names = Hash.new
  270.  
  271.     #
  272.     # Hash table of argument flags.
  273.     # Keyes of the table are option names, and their values are argument
  274.     # flags of the options.
  275.     #
  276.     @argument_flags = Hash.new
  277.  
  278.     #
  279.     # Whether error messages are output to stderr.
  280.     #
  281.     @quiet = FALSE
  282.  
  283.     #
  284.     # Status code.
  285.     #
  286.     @status = STATUS_YET
  287.  
  288.     #
  289.     # Error code.
  290.     #
  291.     @error = nil
  292.  
  293.     #
  294.     # Error message.
  295.     #
  296.     @error_message = nil
  297.  
  298.     #
  299.     # Rest of catinated short options.
  300.     #
  301.     @rest_singles = ''
  302.  
  303.     #
  304.     # List of non-option-arguments.
  305.     # Append them to ARGV when option processing is terminated.
  306.     #
  307.     @non_option_arguments = Array.new
  308.  
  309.     if 0 < arguments.length
  310.       set_options(*arguments)
  311.     end
  312.   end
  313.  
  314.   #
  315.   # Set ordering.
  316.   #
  317.   def ordering=(ordering)
  318.     #
  319.     # The method is failed if option processing has already started.
  320.     #
  321.     if @status != STATUS_YET
  322.       set_error(ArgumentError, "argument error")
  323.       raise RuntimeError,
  324.     "invoke ordering=, but option processing has already started"
  325.     end
  326.  
  327.     #
  328.     # Check ordering.
  329.     #
  330.     if !ORDERINGS.include?(ordering)
  331.       raise ArgumentError, "invalid ordering `#{ordering}'"
  332.     end
  333.     if ordering == PERMUTE && ENV.include?('POSIXLY_CORRECT')
  334.       @ordering = REQUIRE_ORDER
  335.     else
  336.       @ordering = ordering
  337.     end
  338.   end
  339.  
  340.   #
  341.   # Return ordering.
  342.   #
  343.   attr_reader :ordering
  344.  
  345.   #
  346.   # Set options
  347.   #
  348.   def set_options(*arguments)
  349.     #
  350.     # The method is failed if option processing has already started.
  351.     #
  352.     if @status != STATUS_YET
  353.       raise RuntimeError,
  354.     "invoke set_options, but option processing has already started"
  355.     end
  356.  
  357.     #
  358.     # Clear tables of option names and argument flags.
  359.     #
  360.     @canonical_names.clear
  361.     @argument_flags.clear
  362.  
  363.     arguments.each do |arg|
  364.       #
  365.       # Each argument must be an Array.
  366.       #
  367.       if !arg.is_a?(Array)
  368.     raise ArgumentError, "the option list contains non-Array argument"
  369.       end
  370.  
  371.       #
  372.       # Find an argument flag and it set to `argument_flag'.
  373.       #
  374.       argument_flag = nil
  375.       arg.each do |i|
  376.     if ARGUMENT_FLAGS.include?(i)
  377.       if argument_flag != nil
  378.         raise ArgumentError, "too many argument-flags"
  379.       end
  380.       argument_flag = i
  381.     end
  382.       end
  383.       raise ArgumentError, "no argument-flag" if argument_flag == nil
  384.  
  385.       canonical_name = nil
  386.       arg.each do |i|
  387.     #
  388.     # Check an option name.
  389.     #
  390.     next if i == argument_flag
  391.     begin
  392.       if !i.is_a?(String) || i !~ /^-([^-]|-.+)$/
  393.         raise ArgumentError, "an invalid option `#{i}'"
  394.       end
  395.       if (@canonical_names.include?(i))
  396.         raise ArgumentError, "option redefined `#{i}'"
  397.       end
  398.     rescue
  399.       @canonical_names.clear
  400.       @argument_flags.clear
  401.       raise
  402.     end
  403.  
  404.     #
  405.     # Register the option (`i') to the `@canonical_names' and
  406.     # `@canonical_names' Hashes.
  407.     #
  408.     if canonical_name == nil
  409.       canonical_name = i
  410.     end
  411.     @canonical_names[i] = canonical_name
  412.     @argument_flags[i] = argument_flag
  413.       end
  414.       raise ArgumentError, "no option name" if canonical_name == nil
  415.     end
  416.     return self
  417.   end
  418.  
  419.   #
  420.   # Set/Unset `quit' mode.
  421.   #
  422.   attr_writer :quiet
  423.  
  424.   #
  425.   # Return the flag of `quiet' mode.
  426.   #
  427.   attr_reader :quiet
  428.  
  429.   #
  430.   # `quiet?' is an alias of `quiet'.
  431.   #
  432.   alias quiet? quiet
  433.  
  434.   #
  435.   # Termintate option processing.
  436.   #
  437.   def terminate
  438.     return nil if @status == STATUS_TERMINATED
  439.     raise RuntimeError, "an error has occured" if @error != nil
  440.  
  441.     @status = STATUS_TERMINATED
  442.     @non_option_arguments.reverse_each do |argument|
  443.       ARGV.unshift(argument)
  444.     end
  445.  
  446.     @canonical_names = nil
  447.     @argument_flags = nil
  448.     @rest_singles = nil
  449.     @non_option_arguments = nil
  450.  
  451.     return self
  452.   end
  453.  
  454.   #
  455.   # Examine whether option processing is termintated or not.
  456.   #
  457.   def terminated?
  458.     return @status == STATUS_TERMINATED
  459.   end
  460.  
  461.   #
  462.   # Set an error (protected).
  463.   #
  464.   def set_error(type, message)
  465.     $stderr.print("#{$0}: #{message}\n") if !@quiet
  466.  
  467.     @error = type
  468.     @error_message = message
  469.     @canonical_names = nil
  470.     @argument_flags = nil
  471.     @rest_singles = nil
  472.     @non_option_arguments = nil
  473.  
  474.     raise type, message
  475.   end
  476.   protected :set_error
  477.  
  478.   #
  479.   # Examine whether an option processing is failed.
  480.   #
  481.   attr_reader :error
  482.  
  483.   #
  484.   # `error?' is an alias of `error'.
  485.   #
  486.   alias error? error
  487.  
  488.   #
  489.   # Return an error message.
  490.   #
  491.   def error_message
  492.     return @error_message
  493.   end
  494.  
  495.   #
  496.   # Get next option name and its argument as an array.
  497.   #
  498.   def get
  499.     option_name, option_argument = nil, ''
  500.  
  501.     #
  502.     # Check status.
  503.     #
  504.     return nil if @error != nil
  505.     case @status
  506.     when STATUS_YET
  507.       @status = STATUS_STARTED
  508.     when STATUS_TERMINATED
  509.       return nil
  510.     end
  511.  
  512.     #
  513.     # Get next option argument.
  514.     #
  515.     if 0 < @rest_singles.length
  516.       argument = '-' + @rest_singles
  517.     elsif (ARGV.length == 0)
  518.       terminate
  519.       return nil
  520.     elsif @ordering == PERMUTE
  521.       while 0 < ARGV.length && ARGV[0] !~ /^-./
  522.     @non_option_arguments.push(ARGV.shift)
  523.       end
  524.       if ARGV.length == 0
  525.     terminate
  526.     return nil
  527.       end
  528.       argument = ARGV.shift
  529.     elsif @ordering == REQUIRE_ORDER
  530.       if (ARGV[0] !~ /^-./)
  531.     terminate
  532.     return nil
  533.       end
  534.       argument = ARGV.shift
  535.     else
  536.       argument = ARGV.shift
  537.     end
  538.  
  539.     #
  540.     # Check the special argument `--'.
  541.     # `--' indicates the end of the option list.
  542.     #
  543.     if argument == '--' && @rest_singles.length == 0
  544.       terminate
  545.       return nil
  546.     end
  547.  
  548.     #
  549.     # Check for long and short options.
  550.     #
  551.     if argument =~ /^(--[^=]+)/ && @rest_singles.length == 0
  552.       #
  553.       # This is a long style option, which start with `--'.
  554.       #
  555.       pattern = $1
  556.       if @canonical_names.include?(pattern)
  557.     option_name = pattern
  558.       else
  559.     #
  560.     # The option `option_name' is not registered in `@canonical_names'.
  561.     # It may be an abbreviated.
  562.     #
  563.     match_count = 0
  564.     @canonical_names.each_key do |key|
  565.       if key.index(pattern) == 0
  566.         option_name = key
  567.         match_count += 1
  568.       end
  569.     end
  570.     if 2 <= match_count
  571.       set_error(AmbigousOption, "option `#{argument}' is ambiguous")
  572.     elsif match_count == 0
  573.       set_error(InvalidOption, "unrecognized option `#{argument}'")
  574.     end
  575.       end
  576.  
  577.       #
  578.       # Check an argument to the option.
  579.       #
  580.       if @argument_flags[option_name] == REQUIRED_ARGUMENT
  581.     if argument =~ /=(.*)$/
  582.       option_argument = $1
  583.     elsif 0 < ARGV.length
  584.       option_argument = ARGV.shift
  585.     else
  586.       set_error(MissingArgument,
  587.                 "option `#{argument}' requires an argument")
  588.     end
  589.       elsif @argument_flags[option_name] == OPTIONAL_ARGUMENT
  590.     if argument =~ /=(.*)$/
  591.       option_argument = $1
  592.     elsif 0 < ARGV.length && ARGV[0] !~ /^-./
  593.       option_argument = ARGV.shift
  594.     else
  595.       option_argument = ''
  596.     end
  597.       elsif argument =~ /=(.*)$/
  598.     set_error(NeedlessArgument,
  599.           "option `#{option_name}' doesn't allow an argument")
  600.       end
  601.  
  602.     elsif argument =~ /^(-(.))(.*)/
  603.       #
  604.       # This is a short style option, which start with `-' (not `--').
  605.       # Short options may be catinated (e.g. `-l -g' is equivalent to
  606.       # `-lg').
  607.       #
  608.       option_name, ch, @rest_singles = $1, $2, $3
  609.  
  610.       if @canonical_names.include?(option_name)
  611.     #
  612.     # The option `option_name' is found in `@canonical_names'.
  613.     # Check its argument.
  614.     #
  615.     if @argument_flags[option_name] == REQUIRED_ARGUMENT
  616.       if 0 < @rest_singles.length
  617.         option_argument = @rest_singles
  618.         @rest_singles = ''
  619.       elsif 0 < ARGV.length
  620.         option_argument = ARGV.shift
  621.       else
  622.         # 1003.2 specifies the format of this message.
  623.         set_error(MissingArgument, "option requires an argument -- #{ch}")
  624.       end
  625.     elsif @argument_flags[option_name] == OPTIONAL_ARGUMENT
  626.       if 0 < @rest_singles.length
  627.         option_argument = @rest_singles
  628.         @rest_singles = ''
  629.       elsif 0 < ARGV.length && ARGV[0] !~ /^-./
  630.         option_argument = ARGV.shift
  631.       else
  632.         option_argument = ''
  633.       end
  634.     end
  635.       else
  636.     #
  637.     # This is an invalid option.
  638.     # 1003.2 specifies the format of this message.
  639.     #
  640.     if ENV.include?('POSIXLY_CORRECT')
  641.       set_error(InvalidOption, "illegal option -- #{ch}")
  642.     else
  643.       set_error(InvalidOption, "invalid option -- #{ch}")
  644.     end
  645.       end
  646.     else
  647.       #
  648.       # This is a non-option argument.
  649.       # Only RETURN_IN_ORDER falled into here.
  650.       #
  651.       return '', argument
  652.     end
  653.  
  654.     return @canonical_names[option_name], option_argument
  655.   end
  656.  
  657.   #
  658.   # `get_option' is an alias of `get'.
  659.   #
  660.   alias get_option get
  661.  
  662.   #
  663.   # Iterator version of `get'.
  664.   #
  665.   def each
  666.     loop do
  667.       option_name, option_argument = get_option
  668.       break if option_name == nil
  669.       yield option_name, option_argument
  670.     end
  671.   end
  672.  
  673.   #
  674.   # `each_option' is an alias of `each'.
  675.   #
  676.   alias each_option each
  677. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement