Class: Chess::Pieces::Knight

Inherits:
Piece
  • Object
show all
Defined in:
lib/chess/pieces/knight.rb

Overview

Knight

Instance Attribute Summary

Attributes inherited from Piece

#color, #pos, #valid_moves

Instance Method Summary collapse

Methods inherited from Piece

#black?, #initialize, #white?

Constructor Details

This class inherits a constructor from Chess::Pieces::Piece

Instance Method Details

#east_moves(board, file, rank) ⇒ Object



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

def east_moves(board, file, rank)
  moves = []
  east_steps = 2
  two_step_east = [(file.ord + east_steps).chr, rank]
  north = board.north_pos(*two_step_east)
  south = board.south_pos(*two_step_east)
  [north, south].each do |pos|
    moves << pos if board.pos_in_range?(pos) && (board.empty_at?(*pos) || board.enemy_at?(*pos))
  end
  moves
end

#north_moves(board, file, rank) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/chess/pieces/knight.rb', line 24

def north_moves(board, file, rank)
  moves = []
  north_steps = 2
  two_step_north = [file, rank + north_steps]

  east = board.east_pos(*two_step_north)
  west = board.west_pos(*two_step_north)
  moves << east if board.pos_in_range?(east) && (board.empty_at?(*east) || board.enemy_at?(*east))
  moves << west if board.pos_in_range?(west) && (board.empty_at?(*west) || board.enemy_at?(*west))
  moves
end

#possible_moves(board) ⇒ Array

all possible_moves of Knight

Parameters:

Returns:

  • (Array)

    possible_moves_arr



13
14
15
16
17
18
19
20
21
22
# File 'lib/chess/pieces/knight.rb', line 13

def possible_moves(board)
  file = @pos[0]
  rank = @pos[1]
  moves = []
  moves += north_moves(board, file, rank)
  moves += south_moves(board, file, rank)
  moves += west_moves(board, file, rank)
  moves += east_moves(board, file, rank)
  moves
end

#south_moves(board, file, rank) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/chess/pieces/knight.rb', line 36

def south_moves(board, file, rank)
  moves = []
  south_steps = 2
  two_step_south = [file, rank - south_steps]

  return moves unless board.pos_in_range?(two_step_south)

  east = board.east_pos(*two_step_south)
  west = board.west_pos(*two_step_south)
  [east, west].each do |pos|
    moves << pos if board.pos_in_range?(pos) && (board.empty_at?(*pos) || board.enemy_at?(*pos))
  end
  moves
end

#west_moves(board, file, rank) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/chess/pieces/knight.rb', line 51

def west_moves(board, file, rank)
  moves = []
  west_steps = 2
  two_step_west = [(file.ord - west_steps).chr, rank]

  return moves unless board.pos_in_range?(two_step_west)

  north = board.north_pos(*two_step_west)
  south = board.south_pos(*two_step_west)
  [north, south].each do |pos|
    moves << pos if board.pos_in_range?(pos) && (board.empty_at?(*pos) || board.enemy_at?(*pos))
  end
  moves
end