Class: WhirledPeas::Graphics::PixelGrid

Inherits:
Object
  • Object
show all
Defined in:
lib/whirled_peas/graphics/pixel_grid.rb

Defined Under Namespace

Classes: Pixel

Instance Method Summary collapse

Constructor Details

#initialize(width, height) ⇒ PixelGrid

Returns a new instance of PixelGrid.



6
7
8
# File 'lib/whirled_peas/graphics/pixel_grid.rb', line 6

def initialize(width, height)
  @pixels = Array.new(height) { Array.new(width) { Pixel.new } }
end

Instance Method Details

#add_stroke(left, top, fstring) ⇒ Object



10
11
12
13
14
15
# File 'lib/whirled_peas/graphics/pixel_grid.rb', line 10

def add_stroke(left, top, fstring)
  fstring.each_char.with_index do |char, offset|
    pixels[top][left + offset].char = char
    pixels[top][left + offset].formatting = fstring.formatting
  end
end

#diff(other) ⇒ Object



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
# File 'lib/whirled_peas/graphics/pixel_grid.rb', line 21

def diff(other)
  str = ''
  formatting = nil
  chars = ''
  pixels.each.with_index do |row, row_index|
    row.each.with_index do |pixel, col_index|
      if pixel == other.pixel_at(col_index, row_index)
        if chars != ''
          str += Utils::FormattedString.new(chars, formatting).to_s
          chars = ''
          formatting = nil
        end
      elsif chars == ''
        str += Utils::Ansi.cursor_pos(left: col_index, top: row_index)
        chars = pixel.char
        formatting = pixel.formatting
      elsif formatting != pixel.formatting
        str += Utils::FormattedString.new(chars, formatting).to_s
        chars = pixel.char
        formatting = pixel.formatting
      else
        chars += pixel.char
      end
    end
  end
  if chars != ''
    str += chars
    chars = ''
    formatting = nil
  end
  str
end

#pixel_at(col, row) ⇒ Object



17
18
19
# File 'lib/whirled_peas/graphics/pixel_grid.rb', line 17

def pixel_at(col, row)
  pixels[row][col]
end

#to_sObject



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/whirled_peas/graphics/pixel_grid.rb', line 54

def to_s
  str = Utils::Ansi.cursor_pos(left: 0, top: 0) + Utils::Ansi.clear_down
  formatting = nil
  chars = ''
  pixels.each.with_index do |row, row_offset|
    str += Utils::Ansi.cursor_pos(left: 0, top: row_offset) if row_offset > 0
    row.each do |pixel|
      if pixel.formatting != formatting
        str += Utils::FormattedString.new(chars, formatting).to_s if chars != ''
        chars = ''
        formatting = pixel.formatting
      end
      chars << pixel.char
    end
    if chars != ''
      str += Utils::FormattedString.new(chars, formatting).to_s
      chars = ''
    end
  end
  str
end