Class: Display

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

Overview

Graphics Display

Constant Summary collapse

BLACK =
'000'
WHITE =
'FFF'
DSTD_HEIGHT =
600
DSTD_WIDTH =
600

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(grid, framerate = 60) ⇒ Display

Returns a new instance of Display.



17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/display.rb', line 17

def initialize(grid, framerate=60)
  SDL2.init(SDL2::INIT_VIDEO | SDL2::INIT_TIMER | SDL2::INIT_EVENTS)
  @window      = create_window
  @renderer    = window.create_renderer(-1, 0)
  @framerate   = framerate

  @grid        = grid
  @grid_height = Grid::ROWS
  @grid_width  = Grid::COLS

  @cell_width  = DSTD_WIDTH / Grid::COLS
  @cell_height = DSTD_HEIGHT / Grid::ROWS
end

Instance Attribute Details

#event_functionObject

Returns the value of attribute event_function.



15
16
17
# File 'lib/display.rb', line 15

def event_function
  @event_function
end

#framerateObject

Returns the value of attribute framerate.



15
16
17
# File 'lib/display.rb', line 15

def framerate
  @framerate
end

#rendererObject

Returns the value of attribute renderer.



15
16
17
# File 'lib/display.rb', line 15

def renderer
  @renderer
end

#windowObject

Returns the value of attribute window.



15
16
17
# File 'lib/display.rb', line 15

def window
  @window
end

Class Method Details

.render_grid(grid) ⇒ Object



75
76
77
# File 'lib/display.rb', line 75

def self.render_grid(grid)
  new(grid).render
end

Instance Method Details

#event_handlerObject



44
45
46
47
48
49
50
# File 'lib/display.rb', line 44

def event_handler
  while ev = SDL2::Event.poll
    if SDL2::Event::KeyDown === ev && ev.scancode == SDL2::Key::Scan::ESCAPE
      exit
    end
  end
end

#plot_cell(cell) ⇒ Object



64
65
66
67
68
69
70
71
72
73
# File 'lib/display.rb', line 64

def plot_cell(cell)
  @renderer.draw_color = decode_color(cell.state == Cell::ALIVE ? WHITE : BLACK)
  @renderer.fill_rect(
    SDL2::Rect.new(
      cell.coordinates[0] * @cell_height,
      cell.coordinates[1] * @cell_width,
      @cell_height, @cell_width
    )
  )
end

#plot_gridObject



52
53
54
55
56
57
58
# File 'lib/display.rb', line 52

def plot_grid
  @grid.map do |row|
    row.map do |cell|
      plot_cell(cell)
    end
  end
end

#renderObject



31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/display.rb', line 31

def render
  loop do
    event_handler

    clear_screen
    plot_grid
    update_grid

    @renderer.present
    sleep 1.0 / @framerate
  end
end

#update_gridObject



60
61
62
# File 'lib/display.rb', line 60

def update_grid
  @grid.inc_gen
end