-1

我有一个针对角色的小班,我们可以从班外分配给它。

我需要知道如何将该类中的所有信息转储到另一个可用于创建 YAML 文件的信息中。

require "yaml"

module Save
  filename = "data.yaml"
  character = []
  sex = []
  race = []
  stats = [Str=[], Dex=[], Con=[], Int=[], Wis=[], Cha=[]]
  inventory = []
  saving_throws = [fortitude=[], reflex=[], will=[]]
  #Armor Class, Flat footed Armor Class, and Touch armor Class
  armor_class = [ac=[], fac=[], tac=[]]
  armor_worn = [head=[], eyes=[], neck=[], shoulders=[], body=[], torso=[],     arms_wrists=[], hands=[], ring1=[], ring2=[], waist=[], feet=[]] 
  money = []
  god = []
  speciality_school = [] #wizard
  companion = [] #also used for familirs and psicrystals
  skills = []
  class_race_traits = []
  feats = []
  languages = []

  program_data = {
    character: character,
    sex: sex,
    race: race,
    stats: stats,
    inventory: inventory,
    saving_throws: saving_throws,
    armor_class: armor_class,
    armor_worn: armor_worn,
    mony: money,
    god: god,
    speciality_school: speciality_school,
    companion: companion,
    skills: skills,
    class_race_traits: class_race_traits,
    feats: feats,
    languages: languages
  }

  File.write filename, YAML.dump(program_data)
end

这是我想用来从播放器获取用户内容的代码:

class Character
  attr_reader :name, :race, :description

  def initialize (name, race, description)
    @name = name
    @race = race
    @description = description  
  end
end

def prompt
  print "Enter Command >"
end

puts "What is your name?"
prompt; name = gets.chomp.downcase

puts "What is your race?"
prompt; race = gets.chomp.downcase

puts "What do you look like?"
prompt; desc = gets.chomp.downcase

player_one = Character.new(name, race, desc)
puts player_one

我被困在如何重新加载它并重新填充角色内容以使其从玩家离开的地方继续。

4

1 回答 1

1

思考一下这段虚构的代码:

require 'yaml'

SAVED_STATE_FILE = 'saved_state.yaml'

class User
  def initialize(name=nil, address=nil)
    @name = name
    @address = address
  end

  def to_h
    {
      'name'    => @name,
      'address' => @address
    }
  end

  def save
    File.write(SAVED_STATE_FILE, self.to_h.to_yaml)
  end

  def reload
    state = YAML.load_file(SAVED_STATE_FILE)
    @name, @address = state.values
  end
end

我们可以创建一个具有一些属性的新用户:

user = User.new('Popeye', '123 E. Main St.')
# => #<User:0x007fe361097058 @name="Popeye", @address="123 E. Main St.">

要将这些信息写入文件,您可能应该从使用 YAML 开始,这会产生非常可读的输出,并且可以被许多不同的语言读取,从而使数据文件可重用。哈希会产生非常易读的输出:

user.to_h
# => {"name"=>"Popeye", "address"=>"123 E. Main St."}
user.to_h.to_yaml
# => "---\nname: Popeye\naddress: 123 E. Main St.\n"

保存 YAML 序列化哈希:

user.save

创建没有任何状态的新版本用户:

user = User.new
# => #<User:0x007fe361094a88 @name=nil, @address=nil>

将文件中保存的信息加载回空白对象:

user.reload

结果是:

user
# => #<User:0x007fe361094a88 @name="Popeye", @address="123 E. Main St.">

这将给你足够的工作。

但是,您当前的代码不会很好地工作;我建议阅读一些关于 Ruby 类和模块的教程,因为模块不是您想要的,至少对于您的初始代码而言。

于 2016-01-29T22:35:33.813 回答