Class: Square

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

Overview

Represents a location on the board. Immutable.

Constant Summary collapse

OFF_BOARD =
Square.new

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Square

Returns a new instance of Square.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/bangkok/square.rb', line 6

def initialize(*args)
  @file = @rank = @color = nil
  case args[0]
  when Square                 # copy values from another Square
    @file = args[0].file
    @rank = args[0].rank
    @color = args[0].color
  when Numeric                # (file number, rank number)
    @file = args[0].to_i      # If floating point, make integer
    @rank = args[1].to_i
    @color = (((@file & 1) == (@rank & 1)) ? :black : :white) if on_board?
  when /[a-h][1-8]/           # a3, d8
    @file = args[0][0] - ?a
    @rank = args[0][1,1].to_i - 1
    @color = ((@file & 1) == (@rank & 1)) ? :black : :white
  when /[a-h]/                # Either (file letter, rank) or a file 'a'
    @file = args[0][0] - ?a
    @rank = (args[1].to_i - 1) if args[1]
  when /[1-8]/                # 1, 5
    @rank = args[0].to_i - 1
  when nil
    # both file and rank are nil
  else
    raise "don't understand Square ctor args (#{args.join(',')})"
  end
end

Instance Attribute Details

#colorObject (readonly)

:white or :black



4
5
6
# File 'lib/bangkok/square.rb', line 4

def color
  @color
end

#fileObject (readonly)

Always 0-7



3
4
5
# File 'lib/bangkok/square.rb', line 3

def file
  @file
end

#rankObject (readonly)

Always 0-7



3
4
5
# File 'lib/bangkok/square.rb', line 3

def rank
  @rank
end

Instance Method Details

#==(square) ⇒ Object



33
34
35
# File 'lib/bangkok/square.rb', line 33

def ==(square)
  @file == square.file && @rank == square.rank
end

#on_board?Boolean

Returns:

  • (Boolean)


37
38
39
# File 'lib/bangkok/square.rb', line 37

def on_board?
  return @file && @rank
end

#to_sObject



41
42
43
44
# File 'lib/bangkok/square.rb', line 41

def to_s
  return "<off-board>" if @file.nil? || @rank.nil?
  return "#{@file ? (?a + file).chr : ''}#{@rank + 1}"
end