Class: PGN::MoveCalculator

Inherits:
Object
  • Object
show all
Defined in:
lib/pgn/move_calculator.rb

Overview

MoveCalculator is responsible for computing all of the ways that a specific move changes the current position. This includes which squares on the board need to be updated, new castling restrictions, the en passant square and whether to update fullmove and halfmove counters.

Constant Summary collapse

DIRECTIONS =

Specifies the movement of pieces who are allowed to move in a given direction until they reach an obstacle or the end of the board.

{
  'b' => [[1, 1], [-1,  1], [-1, -1], [1, -1]],
  'r' => [[-1, 0], [1,  0], [0, -1], [0,  1]],
  'q' => [[1,  1], [-1,  1], [-1, -1], [1, -1],
          [-1, 0], [1,  0], [0, -1], [0, 1]]
}.freeze
MOVES =

Specifies the movement of pieces that have a limited set of moves they are allowed to make.

{
  'k' => [[-1, -1], [0, -1], [1, -1], [1,  0],
          [1,  1], [0,  1], [-1,  1], [-1, 0]],
  'n' => [[-1, -2], [-1, 2], [1, -2], [1,  2],
          [-2, -1], [2, -1], [-2, 1], [2,  1]]
}.freeze
PAWN_MOVES =

Specifies possible pawn movements. It may seem backwards since it is used to compute the origin square and not the destination.

{
  'P' => {
    capture: [[-1, -1], [1, -1]],
    normal: [[0, -1]],
    double: [[0, -2]]
  },
  'p' => {
    capture: [[-1, 1], [1, 1]],
    normal: [[0,  1]],
    double: [[0,  2]]
  }
}.freeze
CASTLING =

The squares to update for each possible castling move.

{
  'Q' => {
    'a1' => nil,
    'c1' => 'K',
    'd1' => 'R',
    'e1' => nil
  },
  'K' => {
    'e1' => nil,
    'f1' => 'R',
    'g1' => 'K',
    'h1' => nil
  },
  'q' => {
    'a8' => nil,
    'c8' => 'k',
    'd8' => 'r',
    'e8' => nil
  },
  'k' => {
    'e8' => nil,
    'f8' => 'r',
    'g8' => 'k',
    'h8' => nil
  }
}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(board, move) ⇒ MoveCalculator

Returns a new instance of MoveCalculator.

Parameters:



90
91
92
93
94
# File 'lib/pgn/move_calculator.rb', line 90

def initialize(board, move)
  self.board = board
  self.move  = move
  self.origin = compute_origin
end

Instance Attribute Details

#boardPGN::Board

Returns the current board.

Returns:



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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
# File 'lib/pgn/move_calculator.rb', line 16

class MoveCalculator
  # Specifies the movement of pieces who are allowed to move in a
  # given direction until they reach an obstacle or the end of the
  # board.
  #
  DIRECTIONS = {
    'b' => [[1, 1], [-1,  1], [-1, -1], [1, -1]],
    'r' => [[-1, 0], [1,  0], [0, -1], [0,  1]],
    'q' => [[1,  1], [-1,  1], [-1, -1], [1, -1],
            [-1, 0], [1,  0], [0, -1], [0, 1]]
  }.freeze

  # Specifies the movement of pieces that have a limited set of moves
  # they are allowed to make.
  #
  MOVES = {
    'k' => [[-1, -1], [0, -1], [1, -1], [1,  0],
            [1,  1], [0,  1], [-1,  1], [-1, 0]],
    'n' => [[-1, -2], [-1, 2], [1, -2], [1,  2],
            [-2, -1], [2, -1], [-2, 1], [2,  1]]
  }.freeze

  # Specifies possible pawn movements. It may seem backwards since it is
  # used to compute the origin square and not the destination.
  #
  PAWN_MOVES = {
    'P' => {
      capture: [[-1, -1], [1, -1]],
      normal: [[0, -1]],
      double: [[0, -2]]
    },
    'p' => {
      capture: [[-1, 1], [1, 1]],
      normal: [[0,  1]],
      double: [[0,  2]]
    }
  }.freeze

  # The squares to update for each possible castling move.
  #
  CASTLING = {
    'Q' => {
      'a1' => nil,
      'c1' => 'K',
      'd1' => 'R',
      'e1' => nil
    },
    'K' => {
      'e1' => nil,
      'f1' => 'R',
      'g1' => 'K',
      'h1' => nil
    },
    'q' => {
      'a8' => nil,
      'c8' => 'k',
      'd8' => 'r',
      'e8' => nil
    },
    'k' => {
      'e8' => nil,
      'f8' => 'r',
      'g8' => 'k',
      'h8' => nil
    }
  }.freeze

  attr_accessor :board
  attr_accessor :move
  attr_accessor :origin

  # @param board [PGN::Board] the current board
  # @param move [PGN::Move] the current move
  #
  def initialize(board, move)
    self.board = board
    self.move  = move
    self.origin = compute_origin
  end

  # @return [PGN::Board] the board after the move is made
  #
  def result_board
    new_board = board.dup
    new_board.change!(changes)

    new_board
  end

  # @return [Array<String>] which castling moves are no longer available
  #
  def castling_restrictions
    restrict = []

    # when a king or rook is moved
    case move.piece
    when 'K'
      restrict += %w[K Q]
    when 'k'
      restrict += %w[k q]
    when 'R'
      restrict << { 'a1' => 'Q', 'h1' => 'K' }[origin]
    when 'r'
      restrict << { 'a8' => 'q', 'h8' => 'k' }[origin]
    end

    # when castling occurs
    restrict += %w[K Q] if %w[K Q].include? move.castle
    restrict += %w[k q] if %w[k q].include? move.castle

    # when a rook is taken
    restrict << 'Q' if move.destination == 'a1'
    restrict << 'q' if move.destination == 'a8'
    restrict << 'K' if move.destination == 'h1'
    restrict << 'k' if move.destination == 'h8'

    restrict.compact.uniq
  end

  # @return [Boolean] whether to increment the halfmove clock
  #
  def increment_halfmove?
    !(move.capture || move.pawn?)
  end

  # @return [Boolean] whether to increment the fullmove counter
  #
  def increment_fullmove?
    move.black?
  end

  # @return [String, nil] the en passant square if applicable
  #
  def en_passant_square
    return nil if move.castle

    if move.pawn? && (origin[1].to_i - move.destination[1].to_i).abs == 2
      if move.white?
        origin[0] + '3'
      else
        origin[0] + '6'
end
    end
  end

  private

  def changes
    changes = {}
    changes.merge!(CASTLING[move.castle]) if move.castle
    changes.merge!(
      origin => nil,
      move.destination => move.piece,
      en_passant_capture => nil
    )
    changes[move.destination] = move.promotion if move.promotion

    changes.reject! { |key, _| key.nil? or key.empty? }

    changes
  end

  # Using the current position and move, figure out where the piece
  # came from.
  #
  def compute_origin
    return nil if move.castle

    possibilities = case move.piece
                    when /[brq]/i then direction_origins
                    when /[kn]/i  then move_origins
                    when /p/i     then pawn_origins
                    else # don't care move, used in variations
                      return nil
                    end

    possibilities = disambiguate(possibilities) if possibilities.length > 1

    board.position_for(possibilities.first)
  end

  # From the destination square, move in each direction stopping if we
  # reach the end of the board. If we encounter a piece, add it to the
  # list of origin possibilities if it is the moving piece, or else
  # check the next direction.
  #
  def direction_origins
    directions    = DIRECTIONS[move.piece.downcase]
    possibilities = []

    directions.each do |dir|
      piece, square = first_piece(destination_coords, dir)
      possibilities << square if piece == move.piece
    end

    possibilities
  end

  # From the destination square, make each move. If it is a valid
  # square and matches the moving piece, add it to the list of origin
  # possibilities.
  #
  def move_origins(moves = nil)
    moves         ||= MOVES[move.piece.downcase]
    possibilities   = []
    file, rank      = destination_coords

    moves.each do |i, j|
      f = file + i
      r = rank + j

      possibilities << [f, r] if valid_square?(f, r) && board.at(f, r) == move.piece
    end

    possibilities
  end

  # Computes the possbile pawn origins based on the destination square
  # and whether or not the move is a capture.
  #
  def pawn_origins
    _, rank     = destination_coords
    double_rank = (rank == 3 && move.white?) || (rank == 4 && move.black?)

    pawn_moves = PAWN_MOVES[move.piece]

    moves = move.capture ? pawn_moves[:capture] : pawn_moves[:normal]
    moves += pawn_moves[:double] if double_rank

    move_origins(moves)
  end

  def disambiguate(possibilities)
    possibilities = disambiguate_san(possibilities)
    possibilities = disambiguate_pawns(possibilities)            if possibilities.length > 1
    possibilities = disambiguate_discovered_check(possibilities) if possibilities.length > 1

    possibilities
  end

  # Try to disambiguate based on the standard algebraic notation.
  #
  def disambiguate_san(possibilities)
    if move.disambiguation
      possibilities.select { |p| board.position_for(p).match(move.disambiguation) }
    else
      possibilities
end
  end

  # A pawn can't move two spaces if there is a pawn in front of it.
  #
  def disambiguate_pawns(possibilities)
    if move.piece.match(/p/i) && !move.capture
      possibilities.reject { |p| board.position_for(p).match(/2|7/) }
    else
      possibilities
end
  end

  # A piece can't move if it would result in a discovered check.
  #
  def disambiguate_discovered_check(possibilities)
    DIRECTIONS.each do |attacking_piece, directions|
      attacking_piece = attacking_piece.upcase if move.black?

      directions.each do |dir|
        piece, square = first_piece(king_position, dir)
        next unless piece == move.piece && possibilities.include?(square)

        piece, = first_piece(square, dir)
        possibilities.reject! { |p| p == square } if piece == attacking_piece
      end
    end

    possibilities
  end

  def first_piece(from, direction)
    file, rank = from
    i,    j    = direction

    piece = nil

    while valid_square?(file += i, rank += j)
      break if piece = board.at(file, rank)
    end

    [piece, [file, rank]]
  end

  # If the move is a capture and there is no piece on the
  # destination square, it must be an en passant capture.
  #
  def en_passant_capture
    return nil if move.castle

    move.destination[0] + origin[1] if !board.at(move.destination) && move.capture
  end

  def king_position
    king = move.white? ? 'K' : 'k'

    coords = nil
    0.upto(7) do |file|
      0.upto(7) do |rank|
        coords = [file, rank] if board.at(file, rank) == king
      end
    end

    coords
  end

  def valid_square?(file, rank)
    (0..7) === file && (0..7) === rank
  end

  def destination_coords
    board.coordinates_for(move.destination)
  end
end

#movePGN::Move

Returns the current move.

Returns:



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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
# File 'lib/pgn/move_calculator.rb', line 16

class MoveCalculator
  # Specifies the movement of pieces who are allowed to move in a
  # given direction until they reach an obstacle or the end of the
  # board.
  #
  DIRECTIONS = {
    'b' => [[1, 1], [-1,  1], [-1, -1], [1, -1]],
    'r' => [[-1, 0], [1,  0], [0, -1], [0,  1]],
    'q' => [[1,  1], [-1,  1], [-1, -1], [1, -1],
            [-1, 0], [1,  0], [0, -1], [0, 1]]
  }.freeze

  # Specifies the movement of pieces that have a limited set of moves
  # they are allowed to make.
  #
  MOVES = {
    'k' => [[-1, -1], [0, -1], [1, -1], [1,  0],
            [1,  1], [0,  1], [-1,  1], [-1, 0]],
    'n' => [[-1, -2], [-1, 2], [1, -2], [1,  2],
            [-2, -1], [2, -1], [-2, 1], [2,  1]]
  }.freeze

  # Specifies possible pawn movements. It may seem backwards since it is
  # used to compute the origin square and not the destination.
  #
  PAWN_MOVES = {
    'P' => {
      capture: [[-1, -1], [1, -1]],
      normal: [[0, -1]],
      double: [[0, -2]]
    },
    'p' => {
      capture: [[-1, 1], [1, 1]],
      normal: [[0,  1]],
      double: [[0,  2]]
    }
  }.freeze

  # The squares to update for each possible castling move.
  #
  CASTLING = {
    'Q' => {
      'a1' => nil,
      'c1' => 'K',
      'd1' => 'R',
      'e1' => nil
    },
    'K' => {
      'e1' => nil,
      'f1' => 'R',
      'g1' => 'K',
      'h1' => nil
    },
    'q' => {
      'a8' => nil,
      'c8' => 'k',
      'd8' => 'r',
      'e8' => nil
    },
    'k' => {
      'e8' => nil,
      'f8' => 'r',
      'g8' => 'k',
      'h8' => nil
    }
  }.freeze

  attr_accessor :board
  attr_accessor :move
  attr_accessor :origin

  # @param board [PGN::Board] the current board
  # @param move [PGN::Move] the current move
  #
  def initialize(board, move)
    self.board = board
    self.move  = move
    self.origin = compute_origin
  end

  # @return [PGN::Board] the board after the move is made
  #
  def result_board
    new_board = board.dup
    new_board.change!(changes)

    new_board
  end

  # @return [Array<String>] which castling moves are no longer available
  #
  def castling_restrictions
    restrict = []

    # when a king or rook is moved
    case move.piece
    when 'K'
      restrict += %w[K Q]
    when 'k'
      restrict += %w[k q]
    when 'R'
      restrict << { 'a1' => 'Q', 'h1' => 'K' }[origin]
    when 'r'
      restrict << { 'a8' => 'q', 'h8' => 'k' }[origin]
    end

    # when castling occurs
    restrict += %w[K Q] if %w[K Q].include? move.castle
    restrict += %w[k q] if %w[k q].include? move.castle

    # when a rook is taken
    restrict << 'Q' if move.destination == 'a1'
    restrict << 'q' if move.destination == 'a8'
    restrict << 'K' if move.destination == 'h1'
    restrict << 'k' if move.destination == 'h8'

    restrict.compact.uniq
  end

  # @return [Boolean] whether to increment the halfmove clock
  #
  def increment_halfmove?
    !(move.capture || move.pawn?)
  end

  # @return [Boolean] whether to increment the fullmove counter
  #
  def increment_fullmove?
    move.black?
  end

  # @return [String, nil] the en passant square if applicable
  #
  def en_passant_square
    return nil if move.castle

    if move.pawn? && (origin[1].to_i - move.destination[1].to_i).abs == 2
      if move.white?
        origin[0] + '3'
      else
        origin[0] + '6'
end
    end
  end

  private

  def changes
    changes = {}
    changes.merge!(CASTLING[move.castle]) if move.castle
    changes.merge!(
      origin => nil,
      move.destination => move.piece,
      en_passant_capture => nil
    )
    changes[move.destination] = move.promotion if move.promotion

    changes.reject! { |key, _| key.nil? or key.empty? }

    changes
  end

  # Using the current position and move, figure out where the piece
  # came from.
  #
  def compute_origin
    return nil if move.castle

    possibilities = case move.piece
                    when /[brq]/i then direction_origins
                    when /[kn]/i  then move_origins
                    when /p/i     then pawn_origins
                    else # don't care move, used in variations
                      return nil
                    end

    possibilities = disambiguate(possibilities) if possibilities.length > 1

    board.position_for(possibilities.first)
  end

  # From the destination square, move in each direction stopping if we
  # reach the end of the board. If we encounter a piece, add it to the
  # list of origin possibilities if it is the moving piece, or else
  # check the next direction.
  #
  def direction_origins
    directions    = DIRECTIONS[move.piece.downcase]
    possibilities = []

    directions.each do |dir|
      piece, square = first_piece(destination_coords, dir)
      possibilities << square if piece == move.piece
    end

    possibilities
  end

  # From the destination square, make each move. If it is a valid
  # square and matches the moving piece, add it to the list of origin
  # possibilities.
  #
  def move_origins(moves = nil)
    moves         ||= MOVES[move.piece.downcase]
    possibilities   = []
    file, rank      = destination_coords

    moves.each do |i, j|
      f = file + i
      r = rank + j

      possibilities << [f, r] if valid_square?(f, r) && board.at(f, r) == move.piece
    end

    possibilities
  end

  # Computes the possbile pawn origins based on the destination square
  # and whether or not the move is a capture.
  #
  def pawn_origins
    _, rank     = destination_coords
    double_rank = (rank == 3 && move.white?) || (rank == 4 && move.black?)

    pawn_moves = PAWN_MOVES[move.piece]

    moves = move.capture ? pawn_moves[:capture] : pawn_moves[:normal]
    moves += pawn_moves[:double] if double_rank

    move_origins(moves)
  end

  def disambiguate(possibilities)
    possibilities = disambiguate_san(possibilities)
    possibilities = disambiguate_pawns(possibilities)            if possibilities.length > 1
    possibilities = disambiguate_discovered_check(possibilities) if possibilities.length > 1

    possibilities
  end

  # Try to disambiguate based on the standard algebraic notation.
  #
  def disambiguate_san(possibilities)
    if move.disambiguation
      possibilities.select { |p| board.position_for(p).match(move.disambiguation) }
    else
      possibilities
end
  end

  # A pawn can't move two spaces if there is a pawn in front of it.
  #
  def disambiguate_pawns(possibilities)
    if move.piece.match(/p/i) && !move.capture
      possibilities.reject { |p| board.position_for(p).match(/2|7/) }
    else
      possibilities
end
  end

  # A piece can't move if it would result in a discovered check.
  #
  def disambiguate_discovered_check(possibilities)
    DIRECTIONS.each do |attacking_piece, directions|
      attacking_piece = attacking_piece.upcase if move.black?

      directions.each do |dir|
        piece, square = first_piece(king_position, dir)
        next unless piece == move.piece && possibilities.include?(square)

        piece, = first_piece(square, dir)
        possibilities.reject! { |p| p == square } if piece == attacking_piece
      end
    end

    possibilities
  end

  def first_piece(from, direction)
    file, rank = from
    i,    j    = direction

    piece = nil

    while valid_square?(file += i, rank += j)
      break if piece = board.at(file, rank)
    end

    [piece, [file, rank]]
  end

  # If the move is a capture and there is no piece on the
  # destination square, it must be an en passant capture.
  #
  def en_passant_capture
    return nil if move.castle

    move.destination[0] + origin[1] if !board.at(move.destination) && move.capture
  end

  def king_position
    king = move.white? ? 'K' : 'k'

    coords = nil
    0.upto(7) do |file|
      0.upto(7) do |rank|
        coords = [file, rank] if board.at(file, rank) == king
      end
    end

    coords
  end

  def valid_square?(file, rank)
    (0..7) === file && (0..7) === rank
  end

  def destination_coords
    board.coordinates_for(move.destination)
  end
end

#originString?

Returns the origin square in SAN.

Returns:

  • (String, nil)

    the origin square in SAN



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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
# File 'lib/pgn/move_calculator.rb', line 16

class MoveCalculator
  # Specifies the movement of pieces who are allowed to move in a
  # given direction until they reach an obstacle or the end of the
  # board.
  #
  DIRECTIONS = {
    'b' => [[1, 1], [-1,  1], [-1, -1], [1, -1]],
    'r' => [[-1, 0], [1,  0], [0, -1], [0,  1]],
    'q' => [[1,  1], [-1,  1], [-1, -1], [1, -1],
            [-1, 0], [1,  0], [0, -1], [0, 1]]
  }.freeze

  # Specifies the movement of pieces that have a limited set of moves
  # they are allowed to make.
  #
  MOVES = {
    'k' => [[-1, -1], [0, -1], [1, -1], [1,  0],
            [1,  1], [0,  1], [-1,  1], [-1, 0]],
    'n' => [[-1, -2], [-1, 2], [1, -2], [1,  2],
            [-2, -1], [2, -1], [-2, 1], [2,  1]]
  }.freeze

  # Specifies possible pawn movements. It may seem backwards since it is
  # used to compute the origin square and not the destination.
  #
  PAWN_MOVES = {
    'P' => {
      capture: [[-1, -1], [1, -1]],
      normal: [[0, -1]],
      double: [[0, -2]]
    },
    'p' => {
      capture: [[-1, 1], [1, 1]],
      normal: [[0,  1]],
      double: [[0,  2]]
    }
  }.freeze

  # The squares to update for each possible castling move.
  #
  CASTLING = {
    'Q' => {
      'a1' => nil,
      'c1' => 'K',
      'd1' => 'R',
      'e1' => nil
    },
    'K' => {
      'e1' => nil,
      'f1' => 'R',
      'g1' => 'K',
      'h1' => nil
    },
    'q' => {
      'a8' => nil,
      'c8' => 'k',
      'd8' => 'r',
      'e8' => nil
    },
    'k' => {
      'e8' => nil,
      'f8' => 'r',
      'g8' => 'k',
      'h8' => nil
    }
  }.freeze

  attr_accessor :board
  attr_accessor :move
  attr_accessor :origin

  # @param board [PGN::Board] the current board
  # @param move [PGN::Move] the current move
  #
  def initialize(board, move)
    self.board = board
    self.move  = move
    self.origin = compute_origin
  end

  # @return [PGN::Board] the board after the move is made
  #
  def result_board
    new_board = board.dup
    new_board.change!(changes)

    new_board
  end

  # @return [Array<String>] which castling moves are no longer available
  #
  def castling_restrictions
    restrict = []

    # when a king or rook is moved
    case move.piece
    when 'K'
      restrict += %w[K Q]
    when 'k'
      restrict += %w[k q]
    when 'R'
      restrict << { 'a1' => 'Q', 'h1' => 'K' }[origin]
    when 'r'
      restrict << { 'a8' => 'q', 'h8' => 'k' }[origin]
    end

    # when castling occurs
    restrict += %w[K Q] if %w[K Q].include? move.castle
    restrict += %w[k q] if %w[k q].include? move.castle

    # when a rook is taken
    restrict << 'Q' if move.destination == 'a1'
    restrict << 'q' if move.destination == 'a8'
    restrict << 'K' if move.destination == 'h1'
    restrict << 'k' if move.destination == 'h8'

    restrict.compact.uniq
  end

  # @return [Boolean] whether to increment the halfmove clock
  #
  def increment_halfmove?
    !(move.capture || move.pawn?)
  end

  # @return [Boolean] whether to increment the fullmove counter
  #
  def increment_fullmove?
    move.black?
  end

  # @return [String, nil] the en passant square if applicable
  #
  def en_passant_square
    return nil if move.castle

    if move.pawn? && (origin[1].to_i - move.destination[1].to_i).abs == 2
      if move.white?
        origin[0] + '3'
      else
        origin[0] + '6'
end
    end
  end

  private

  def changes
    changes = {}
    changes.merge!(CASTLING[move.castle]) if move.castle
    changes.merge!(
      origin => nil,
      move.destination => move.piece,
      en_passant_capture => nil
    )
    changes[move.destination] = move.promotion if move.promotion

    changes.reject! { |key, _| key.nil? or key.empty? }

    changes
  end

  # Using the current position and move, figure out where the piece
  # came from.
  #
  def compute_origin
    return nil if move.castle

    possibilities = case move.piece
                    when /[brq]/i then direction_origins
                    when /[kn]/i  then move_origins
                    when /p/i     then pawn_origins
                    else # don't care move, used in variations
                      return nil
                    end

    possibilities = disambiguate(possibilities) if possibilities.length > 1

    board.position_for(possibilities.first)
  end

  # From the destination square, move in each direction stopping if we
  # reach the end of the board. If we encounter a piece, add it to the
  # list of origin possibilities if it is the moving piece, or else
  # check the next direction.
  #
  def direction_origins
    directions    = DIRECTIONS[move.piece.downcase]
    possibilities = []

    directions.each do |dir|
      piece, square = first_piece(destination_coords, dir)
      possibilities << square if piece == move.piece
    end

    possibilities
  end

  # From the destination square, make each move. If it is a valid
  # square and matches the moving piece, add it to the list of origin
  # possibilities.
  #
  def move_origins(moves = nil)
    moves         ||= MOVES[move.piece.downcase]
    possibilities   = []
    file, rank      = destination_coords

    moves.each do |i, j|
      f = file + i
      r = rank + j

      possibilities << [f, r] if valid_square?(f, r) && board.at(f, r) == move.piece
    end

    possibilities
  end

  # Computes the possbile pawn origins based on the destination square
  # and whether or not the move is a capture.
  #
  def pawn_origins
    _, rank     = destination_coords
    double_rank = (rank == 3 && move.white?) || (rank == 4 && move.black?)

    pawn_moves = PAWN_MOVES[move.piece]

    moves = move.capture ? pawn_moves[:capture] : pawn_moves[:normal]
    moves += pawn_moves[:double] if double_rank

    move_origins(moves)
  end

  def disambiguate(possibilities)
    possibilities = disambiguate_san(possibilities)
    possibilities = disambiguate_pawns(possibilities)            if possibilities.length > 1
    possibilities = disambiguate_discovered_check(possibilities) if possibilities.length > 1

    possibilities
  end

  # Try to disambiguate based on the standard algebraic notation.
  #
  def disambiguate_san(possibilities)
    if move.disambiguation
      possibilities.select { |p| board.position_for(p).match(move.disambiguation) }
    else
      possibilities
end
  end

  # A pawn can't move two spaces if there is a pawn in front of it.
  #
  def disambiguate_pawns(possibilities)
    if move.piece.match(/p/i) && !move.capture
      possibilities.reject { |p| board.position_for(p).match(/2|7/) }
    else
      possibilities
end
  end

  # A piece can't move if it would result in a discovered check.
  #
  def disambiguate_discovered_check(possibilities)
    DIRECTIONS.each do |attacking_piece, directions|
      attacking_piece = attacking_piece.upcase if move.black?

      directions.each do |dir|
        piece, square = first_piece(king_position, dir)
        next unless piece == move.piece && possibilities.include?(square)

        piece, = first_piece(square, dir)
        possibilities.reject! { |p| p == square } if piece == attacking_piece
      end
    end

    possibilities
  end

  def first_piece(from, direction)
    file, rank = from
    i,    j    = direction

    piece = nil

    while valid_square?(file += i, rank += j)
      break if piece = board.at(file, rank)
    end

    [piece, [file, rank]]
  end

  # If the move is a capture and there is no piece on the
  # destination square, it must be an en passant capture.
  #
  def en_passant_capture
    return nil if move.castle

    move.destination[0] + origin[1] if !board.at(move.destination) && move.capture
  end

  def king_position
    king = move.white? ? 'K' : 'k'

    coords = nil
    0.upto(7) do |file|
      0.upto(7) do |rank|
        coords = [file, rank] if board.at(file, rank) == king
      end
    end

    coords
  end

  def valid_square?(file, rank)
    (0..7) === file && (0..7) === rank
  end

  def destination_coords
    board.coordinates_for(move.destination)
  end
end

Instance Method Details

#castling_restrictionsArray<String>

Returns which castling moves are no longer available.

Returns:

  • (Array<String>)

    which castling moves are no longer available



107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/pgn/move_calculator.rb', line 107

def castling_restrictions
  restrict = []

  # when a king or rook is moved
  case move.piece
  when 'K'
    restrict += %w[K Q]
  when 'k'
    restrict += %w[k q]
  when 'R'
    restrict << { 'a1' => 'Q', 'h1' => 'K' }[origin]
  when 'r'
    restrict << { 'a8' => 'q', 'h8' => 'k' }[origin]
  end

  # when castling occurs
  restrict += %w[K Q] if %w[K Q].include? move.castle
  restrict += %w[k q] if %w[k q].include? move.castle

  # when a rook is taken
  restrict << 'Q' if move.destination == 'a1'
  restrict << 'q' if move.destination == 'a8'
  restrict << 'K' if move.destination == 'h1'
  restrict << 'k' if move.destination == 'h8'

  restrict.compact.uniq
end

#en_passant_squareString?

Returns the en passant square if applicable.

Returns:

  • (String, nil)

    the en passant square if applicable



149
150
151
152
153
154
155
156
157
158
159
# File 'lib/pgn/move_calculator.rb', line 149

def en_passant_square
  return nil if move.castle

  if move.pawn? && (origin[1].to_i - move.destination[1].to_i).abs == 2
    if move.white?
      origin[0] + '3'
    else
      origin[0] + '6'
end
  end
end

#increment_fullmove?Boolean

Returns whether to increment the fullmove counter.

Returns:

  • (Boolean)

    whether to increment the fullmove counter



143
144
145
# File 'lib/pgn/move_calculator.rb', line 143

def increment_fullmove?
  move.black?
end

#increment_halfmove?Boolean

Returns whether to increment the halfmove clock.

Returns:

  • (Boolean)

    whether to increment the halfmove clock



137
138
139
# File 'lib/pgn/move_calculator.rb', line 137

def increment_halfmove?
  !(move.capture || move.pawn?)
end

#result_boardPGN::Board

Returns the board after the move is made.

Returns:

  • (PGN::Board)

    the board after the move is made



98
99
100
101
102
103
# File 'lib/pgn/move_calculator.rb', line 98

def result_board
  new_board = board.dup
  new_board.change!(changes)

  new_board
end