Module: Shogi::Format::CSA::Board

Defined in:
lib/shogi/format/csa/board.rb

Instance Method Summary collapse

Instance Method Details

#parse_from_csa(csa) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/shogi/format/csa/board.rb', line 35

def parse_from_csa(csa)
  table = []
  cell_pattern = '[+-][A-Z]{2}| \* '
  csa_lines = csa.each_line.to_a
  csa_lines.slice(0, 9).to_enum.with_index do |row, i|
    table_row = []
    row.chomp!
    unless /\AP#{i + 1}(#{cell_pattern}){9}\z/ =~ row
      raise FormatError, "Format Error: line P#{i + 1}"
    end
    row[2..28].scan(/#{cell_pattern}/) do |cell|
      if cell == " * "
        table_row << ""
      else
        table_row << cell
      end
    end
    table << table_row
  end

  captured = []
  csa_lines.slice(9, 2).each do |captured_line|
    captured_line.chomp!
    unless /\AP[+-](00[A-Z]{2})*\z/ =~ captured_line
      raise FormatError, "Invalid format: #{captured_line}"
    end
    turn = captured_line[1]
    captured_line[2..-1].scan(/00([A-Z]{2})/) do |cell|
      captured << turn + cell[0]
    end
  end

  [table, captured]
end

#to_csaObject



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/shogi/format/csa/board.rb', line 5

def to_csa
  csa_rows = ""

  @table.each_with_index do |row, i|
    csa_row = ""
    row.each do |cell|
      if cell == ""
        csa_row << " * "
      else
        csa_row << cell
      end
    end
    csa_rows << "P#{i + 1}#{csa_row}\n"
  end

  sente = "P+"
  gote = "P-"
  @captured.each do |piece|
    if piece[0] == "+"
      sente << "00#{piece[1..2]}"
    else
      gote << "00#{piece[1..2]}"
    end
  end
  csa_rows << "#{sente}\n"
  csa_rows << "#{gote}\n"

  csa_rows
end