Class: BoardGameGrid::Square

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

Overview

Square

A Square on a board

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(id:, x:, y:, piece: nil) ⇒ Square

New objects can be instantiated by passing in a hash with

Example:

# Instantiates a new Square
JustCheckers::Square.new({
  id: 1,
  x: 1,
  y: 0,
  piece: { player_number: 1, king: false }
})


32
33
34
35
36
37
# File 'lib/board_game_grid/square.rb', line 32

def initialize(id: , x: , y: , piece: nil)
  @id = id
  @x = x
  @y = y
  @piece = piece
end

Instance Attribute Details

#idFixnum (readonly)



40
41
42
# File 'lib/board_game_grid/square.rb', line 40

def id
  @id
end

#pieceHash, NilClass



49
50
51
# File 'lib/board_game_grid/square.rb', line 49

def piece
  @piece
end

#xFixnum (readonly)



43
44
45
# File 'lib/board_game_grid/square.rb', line 43

def x
  @x
end

#yFixnum (readonly)



46
47
48
# File 'lib/board_game_grid/square.rb', line 46

def y
  @y
end

Instance Method Details

#==(other) ⇒ Boolean

Is the square the same as another one?



92
93
94
# File 'lib/board_game_grid/square.rb', line 92

def ==(other)
  self.id == other.id
end

#as_jsonHash

A serialized version of the square as a hash



106
107
108
# File 'lib/board_game_grid/square.rb', line 106

def as_json
  { id: id, x: x, y: y, piece: piece }
end

#attribute_match?(attribute, value) ⇒ Boolean

checks if the square matches the attributes passed.

Example:

# Check if square has a piece owned by player 1
square.attribute_match?(:piece, player_number: 1)


62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/board_game_grid/square.rb', line 62

def attribute_match?(attribute, value)
  hash_obj_matcher = lambda do |obj, k, v|
    value = obj.send(k)
    if !value.nil? && v.is_a?(Hash)
      v.all? { |k2,v2| hash_obj_matcher.call(value, k2, v2) }
    else
      value == v
    end
  end

  hash_obj_matcher.call(self, attribute, value)
end

#occupied?Boolean

Is the square occupied by a piece?



78
79
80
# File 'lib/board_game_grid/square.rb', line 78

def occupied?
  !!piece
end

#pointPoint

A point object with the square’s co-ordinates.



99
100
101
# File 'lib/board_game_grid/square.rb', line 99

def point
  Point.new(x, y)
end

#unoccupied?Boolean

Is the square unoccupied by a piece?



85
86
87
# File 'lib/board_game_grid/square.rb', line 85

def unoccupied?
  !piece
end