Class: RoadToRubykaigi::Map

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

Constant Summary collapse

VIEWPORT_WIDTH =
100
VIEWPORT_HEIGHT =
30

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#heightObject (readonly)

Returns the value of attribute height.



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

def height
  @height
end

#widthObject (readonly)

Returns the value of attribute width.



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

def width
  @width
end

Instance Method Details

#build_buffer(offset_x:) ⇒ Object



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

def build_buffer(offset_x:)
  (0...VIEWPORT_HEIGHT).map do |row|
    @tiles[row][offset_x, VIEWPORT_WIDTH].map(&:character)
  end
end

#clamp_position(x:, y:, width:, height:, dx:, dy:) ⇒ Object



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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/road_to_rubykaigi/map.rb', line 13

def clamp_position(x:, y:, width:, height:, dx:, dy:)
  clamped_x = x.clamp(2, @width - width)
  clamped_y = y.clamp(2, @height - (Sprite::Player::BASE_HEIGHT - height))
  return [clamped_x, clamped_y] if box_passable?(clamped_x, clamped_y, width, height)

  attempt_count = 10
  delta_x = nil
  delta_y = nil
  unless dx == 0
    (1..attempt_count).each do |i|
      attempt_x = clamped_x + i * dx
      if box_passable?(attempt_x, clamped_y, width, height)
        break delta_x = attempt_x - clamped_x
      end
    end
  end
  unless dy == 0
    (1..attempt_count).each do |i|
      attempt_y = [clamped_y + i * dy, RoadToRubykaigi::Sprite::Player::BASE_Y].min
      if box_passable?(clamped_x, attempt_y, width, height)
        break delta_y = attempt_y - clamped_y
      end
    end
  end

  case
  when delta_x && delta_y
    if delta_x.abs <= delta_y.abs
      [clamped_x + delta_x, clamped_y]
    else
      [clamped_x, clamped_y + delta_y]
    end
  when delta_x && !delta_y
    [clamped_x + delta_x, clamped_y]
  when !delta_x && delta_y
    [clamped_x, clamped_y + delta_y]
  else
    coordinates = (1..attempt_count).select do |i|
      attempt_x = clamped_x + i * dx
      attempt_y = [clamped_y + i * dy, RoadToRubykaigi::Sprite::Player::BASE_Y].min
      if box_passable?(attempt_x, attempt_y, width, height)
        break [attempt_x, attempt_y]
      end
    end
    coordinates.empty? ? [clamped_x + dx, clamped_y + dy] : coordinates
  end
end

#passable_at?(col, row) ⇒ Boolean



61
62
63
# File 'lib/road_to_rubykaigi/map.rb', line 61

def passable_at?(col, row)
  @tiles[row-1][col-1].passable?
end