Class: Termfront::Map

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(rows) ⇒ Map

Returns a new instance of Map.



7
8
9
10
11
# File 'lib/termfront/map.rb', line 7

def initialize(rows)
  @grid = rows.map { |r| r.is_a?(Array) ? r : r.chars }
  @height = @grid.size
  @width = @grid[0].size
end

Instance Attribute Details

#gridObject (readonly)

Returns the value of attribute grid.



5
6
7
# File 'lib/termfront/map.rb', line 5

def grid
  @grid
end

#heightObject (readonly)

Returns the value of attribute height.



5
6
7
# File 'lib/termfront/map.rb', line 5

def height
  @height
end

#widthObject (readonly)

Returns the value of attribute width.



5
6
7
# File 'lib/termfront/map.rb', line 5

def width
  @width
end

Instance Method Details

#blocked?(px, py, radius = Config::PLAYER_RADIUS) ⇒ Boolean

Returns:

  • (Boolean)


21
22
23
24
# File 'lib/termfront/map.rb', line 21

def blocked?(px, py, radius = Config::PLAYER_RADIUS)
  wall_at?(px - radius, py - radius) || wall_at?(px + radius, py - radius) ||
    wall_at?(px - radius, py + radius) || wall_at?(px + radius, py + radius)
end

#line_of_sight?(x1, y1, x2, y2) ⇒ Boolean

Returns:

  • (Boolean)


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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/termfront/map.rb', line 26

def line_of_sight?(x1, y1, x2, y2)
  dx = x2 - x1
  dy = y2 - y1
  dist = Math.sqrt(dx * dx + dy * dy)
  return true if dist < 0.01

  dx /= dist
  dy /= dist

  mx = x1.floor
  my = y1.floor
  ddx = dx == 0 ? 1e30 : (1.0 / dx).abs
  ddy = dy == 0 ? 1e30 : (1.0 / dy).abs

  if dx < 0
    step_x = -1
    sd_x = (x1 - mx) * ddx
  else
    step_x = 1
    sd_x = (mx + 1.0 - x1) * ddx
  end
  if dy < 0
    step_y = -1
    sd_y = (y1 - my) * ddy
  else
    step_y = 1
    sd_y = (my + 1.0 - y1) * ddy
  end

  loop do
    if sd_x < sd_y
      return true if sd_x > dist

      sd_x += ddx
      mx += step_x
    else
      return true if sd_y > dist

      sd_y += ddy
      my += step_y
    end
    return false if my < 0 || my >= @height || mx < 0 || mx >= @width
    return false if @grid[my][mx] == "#"
  end
end

#wall_at?(fx, fy) ⇒ Boolean

Returns:

  • (Boolean)


13
14
15
16
17
18
19
# File 'lib/termfront/map.rb', line 13

def wall_at?(fx, fy)
  ix = fx.floor
  iy = fy.floor
  return true if iy < 0 || iy >= @height || ix < 0 || ix >= @width

  @grid[iy][ix] == "#"
end