Class: Egd::Builder

Inherits:
Object
  • Object
show all
Defined in:
lib/egd/builder.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(pgn) ⇒ Builder

Returns a new instance of Builder.



8
9
10
# File 'lib/egd/builder.rb', line 8

def initialize(pgn)
  @pgn = pgn
end

Instance Attribute Details

#pgnObject (readonly)

This is the real deal Takes in a PGN string and returns a Ruby or JSON hash representation of the game in EGD



6
7
8
# File 'lib/egd/builder.rb', line 6

def pgn
  @pgn
end

Instance Method Details

#to_hObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/egd/builder.rb', line 12

def to_h
  return @to_h if defined?(@to_h)

  @to_h = {}

  @to_h["game_tags"] = {"Result" => result_from_moves}.merge(game_tags)
  @to_h["moves"] = {}

  @previous_fen = Egd::FenBuilder::NULL_FEN

  moves.each_with_object(@to_h) do |move, mem|
    transition_key = "#{move[%r'\A\d+']}#{move.match?(%r'\.\.') ? "b" : "w"}" #=> "1w"

    san = move.match(%r'\A(?:\d+\.(?:\s*\.\.)?\s+)(?<san>\S+)\z')[:san] #=> "e4"
    end_fen = Egd::FenBuilder.new(start_fen: @previous_fen, move: move).call

    current_transition = {
      "start_position" => {
        "fen" => @previous_fen,
        "features" => {}, # TODO, no features can be discerned before the move yet
      },
      "move" => {
        "player" => transition_key[%r'\D\z'], #=> "w"
        "san" => san,
      }.merge(
        Egd::FenDifferenceDiscerner.new(
          start_fen: @previous_fen, move: san, end_fen: end_fen
        ).call
      ),
      "end_position" => {
        "fen" => end_fen,
        "features" => Egd::PositionFeatureDiscerner.new(
          move: move, end_fen: end_fen
        ).call
      }
    }

    # leave this breadcrumb for next run through loop
    @previous_fen = current_transition.dig("end_position", "fen")

    mem["moves"][transition_key] = current_transition
  end
end

#to_jsonObject



56
57
58
# File 'lib/egd/builder.rb', line 56

def to_json
  @to_json ||= to_h.to_json
end