Class: Square

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

Overview

Represents a location on the board. Immutable.

Constant Summary collapse

SQUARES =
[]
OFF_BOARD =
Square.new

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Square

Returns a new instance of Square.



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

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

Class Method Details

.at(file, rank) ⇒ Object



6
7
8
# File 'lib/bangkok/square.rb', line 6

def Square.at(file, rank)
  SQUARES[file][rank]
end

Instance Method Details

#==(square) ⇒ Object



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

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

#distance_to(square) ⇒ Object

Return the distance between this square and the other. Returns nil of eithr square is off the board.



47
48
49
50
51
52
# File 'lib/bangkok/square.rb', line 47

def distance_to(square)
  return nil unless on_board? && square.on_board?
  d_file = square.file - @file
  d_rank = square.rank - @rank
  return Math.sqrt(d_file * d_file + d_rank * d_rank)
end

#on_board?Boolean

Returns:

  • (Boolean)


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

def on_board?
  return @file && @rank
end

#to_sObject



54
55
56
57
# File 'lib/bangkok/square.rb', line 54

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