Ruby序列化游戏类

时间:2015-07-09 02:46:38

标签: ruby serialization

我正在编写一个简单的命令行游戏。我有一个运行循环的Game类,并使用Board类来显示玩家的动作。我想要做的是当用户想要保存游戏的状态时将游戏类写入YAML文件,并在玩家恢复游戏时加载YAML。我的问题是,一旦打开YAML文件,我就不知道如何重新创建对象。

def save_game 
  yaml = YAML::dump(self)
  file = File.open("../data/Game.yml", 'w') {|file| file.write    yaml.to_yaml}
  exit 
end

def load_game 
  data = File.open("../data/Game.yml", "r") {|file| file.read}
  yaml = YAML::load(data)
end

保存游戏方法工作正常,我的对象序列化在正确的目录中。 load_file显示了yaml对象,但我不知道从哪里开始。

这是我尝试序列化和反序列化的第一个项目,所以如果有任何额外的资源你会建议我进一步了解这个主题,请告诉我。

1 个答案:

答案 0 :(得分:0)

我写了asciitrails.rb作为游戏来演示保存和加载游戏状态。

#!/usr/bin/env ruby -w
# asciitrails.rb
# Author: Andy Bettisworth
# Description: Walk the ASCII trails

module AsciiTrails
  require 'io/console'
  require 'yaml'

  attr_accessor :history

  class Game
    def start
      puts 'You are now walking the ASCII trails.'
      load_game
      game_loop
    end

    private

    def game_loop
      loop do
        move = get_move
        case move
        when "\e[A"
          @history << "MOVE UP"
          puts "[#{@history.count}] MOVE ARROW"
        when "\e[B"
          @history << "MOVE DOWN"
          puts "[#{@history.count}] MOVE DOWN"
        when "\e[C"
          @history << "MOVE RIGHT"
          puts "[#{@history.count}] MOVE RIGHT"
        when "\e[D"
          @history << "MOVE LEFT"
          puts "[#{@history.count}] MOVE LEFT"
        when "\u0003"
          @history << "PAUSE"
          puts "[#{@history.count}] PAUSE"
          save_game
          exit 0
        end
      end
    end

    def get_move
      STDIN.echo = false
      STDIN.raw!

      input = STDIN.getc.chr
      if input == "\e" then
        input << STDIN.read_nonblock(3) rescue nil
        input << STDIN.read_nonblock(2) rescue nil
      end
    ensure
      STDIN.echo = true
      STDIN.cooked!

      return input
    end

    def save_game
      File.open("./asciitrails.yml", 'w') { |f| YAML.dump([] << self, f) }
      exit
    end

    def load_game
      begin
        yaml = YAML.load_file("./asciitrails.yml")
        @history = yaml[0].history
      rescue
        @history = []
      end
    end
  end
end

if __FILE__ == $0
  include AsciiTrails

  game = Game.new
  game.start
end

保存游戏状态:

File.open("./asciitrails.yml", 'w') { |f| YAML.dump([] << self, f) }

加载游戏状态:

begin
   yaml = YAML.load_file("./asciitrails.yml")
   @history = yaml[0].history
rescue
   @history = []
end

当您加载游戏状态时,只需拉动您使用的变量。