Class: Knossos::Serializer::Bitmask

Inherits:
Object
  • Object
show all
Defined in:
lib/knossos/serializer/bitmask.rb

Constant Summary collapse

NORTH =
1
EAST =
2
SOUTH =
4
WEST =
8

Instance Method Summary collapse

Instance Method Details

#deserialize(encoded_maze:) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/knossos/serializer/bitmask.rb', line 45

def deserialize(encoded_maze:)
  rows = encoded_maze.length
  columns = encoded_maze.first.length
  grid = Knossos::Grid.new({rows: rows, columns: columns})

  encoded_maze.each_with_index do |cells, row|
    cells.each_with_index do |cell, column|
      current_cell = grid[row, column]

      grid.build_passage(current_cell, grid[row - 1, column]) if (cell & NORTH > 0)
      grid.build_passage(current_cell, grid[row, column + 1]) if (cell & EAST > 0)
      grid.build_passage(current_cell, grid[row + 1, column]) if (cell & SOUTH > 0)
      grid.build_passage(current_cell, grid[row, column - 1]) if (cell & WEST > 0)
    end
  end

  grid
end

#serialize(grid:) ⇒ Object



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
34
35
36
37
38
39
40
41
42
43
# File 'lib/knossos/serializer/bitmask.rb', line 9

def serialize(grid:)
  encoded_maze = Array.new(grid.columns) { Array.new(grid.rows, 0) }

  grid.each_row do |cells, row|
    cells.each_with_index do |cell, column|
      link_mask = 0

      cell.links.each do |link|
        link_mask |=
          case column <=> link.column
          when -1
            EAST
          when 0
            0
          when 1
            WEST
          end

        link_mask |=
          case row <=> link.row
          when -1
            SOUTH
          when 0
            0
          when 1
            NORTH
          end
        end

      encoded_maze[row][column] = link_mask
    end
  end

  encoded_maze
end