Class: Pathfinding::Grid

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

Overview

Responsible for manipulating and encapsulating behaviour of tiles related to pathfinding

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(nodes) ⇒ Grid

Returns a new instance of Grid.



11
12
13
# File 'lib/pathfinding/grid.rb', line 11

def initialize(nodes)
  @nodes = nodes
end

Instance Attribute Details

#nodesObject (readonly)

Returns the value of attribute nodes.



9
10
11
# File 'lib/pathfinding/grid.rb', line 9

def nodes
  @nodes
end

Instance Method Details

#edge_nodesObject



66
67
68
69
70
71
72
73
74
75
76
# File 'lib/pathfinding/grid.rb', line 66

def edge_nodes
  @edge_nodes ||=
    @nodes.map do |row|
      row.select do |obj|
        obj.x == min_max_coordinates[:min_x] ||
          obj.x == min_max_coordinates[:max_x] ||
          obj.y == min_max_coordinates[:min_y] ||
          obj.y == min_max_coordinates[:max_y]
      end
    end.flatten
end

#min_max_coordinatesObject



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
# File 'lib/pathfinding/grid.rb', line 40

def min_max_coordinates
  @min_max_coordinates ||= begin
    min_x = nil
    min_y = nil
    max_x = nil
    max_y = nil

    @nodes.each do |row|
      row.each do |object|
        x = object.x
        y = object.y

        # Update minimum x and y values
        min_x = x if min_x.nil? || x < min_x
        min_y = y if min_y.nil? || y < min_y

        # Update maximum x and y values
        max_x = x if max_x.nil? || x > max_x
        max_y = y if max_y.nil? || y > max_y
      end
    end

    { min_x: min_x, min_y: min_y, max_x: max_x, max_y: max_y }
  end
end

#neighbors(node) ⇒ Object

rubocop:enable Naming/MethodParameterName:



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/pathfinding/grid.rb', line 21

def neighbors(node)
  neighbors = []
  return neighbors unless node.can_haz_road?

  x = node.x
  y = node.y

  node_lookup = node(x - 1, y) if x.positive?
  neighbors << node_lookup if !node_lookup.nil? && node_lookup.can_haz_road?
  node_lookup = node(x + 1, y) if x < @nodes[0].size - 1
  neighbors << node_lookup if !node_lookup.nil? && node_lookup.can_haz_road?
  node_lookup = node(x, y - 1) if y.positive?
  neighbors << node_lookup if !node_lookup.nil? && node_lookup.can_haz_road?
  node_lookup = node(x, y + 1) if y < @nodes.size - 1
  neighbors << node_lookup if !node_lookup.nil? && node_lookup.can_haz_road?

  neighbors
end

#node(x, y) ⇒ Object

rubocop:disable Naming/MethodParameterName:



16
17
18
# File 'lib/pathfinding/grid.rb', line 16

def node(x, y)
  nodes[y][x]
end