Class: MailChess::Piece::Pawn

Inherits:
Piece
  • Object
show all
Defined in:
lib/mail_chess/pieces/pawn.rb

Overview

Represents a pawn chess piece.

Instance Attribute Summary

Attributes inherited from Piece

#board, #color, #hits, #html, #id, #moves, #type

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Piece

#can_hit?, #can_move?, create_tables, #delete!, load!, #move, need_to_create_tables?, #position, #save!

Constructor Details

#initialize(db, piece_id, board = nil) ⇒ Pawn

Calls the superclass.



11
12
13
14
15
# File 'lib/mail_chess/pieces/pawn.rb', line 11

def initialize db, piece_id, board = nil
  super db, piece_id, board
  
  @html = @color == :white ? '♙' : '♟'
end

Class Method Details

.new!(db, board, position, color) ⇒ Object

Overwrite superclass method.



18
19
20
21
22
23
24
25
26
27
# File 'lib/mail_chess/pieces/pawn.rb', line 18

def self.new! db, board, position, color
  super db, board, position, color
  
  id = db[:pieces].insert(:type => 'pawn', 
                          :color => color.to_s,
                          :position => position,
                          :board_id => board.id)
                          
  return Pawn.new db, id, board
end

Instance Method Details

#generate_movesObject

Generate the possible moves.



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
# File 'lib/mail_chess/pieces/pawn.rb', line 30

def generate_moves
  super
  
  r, c = ROWS.index(position[1]), COLS.index(position[0])
  dir = @color == :white ? -1 : 1
  first_step = 
    ((@color == :white and position[1] == 2.to_s) or
     (@color == :black and position[1] == 7.to_s) ? true : false)
  
  # moves
  if (r + dir >= 0 and @color == :white) or (r + dir <= 7 and 
                                             @color == :black)
    f = COLS[c] + ROWS[r + dir]
    @moves << f unless @board.pieces[f]
  end
  
  if (r + dir * 2 >= 0 and @color == :white) or (r + dir * 2 <= 7 and
                                                 @color == :black)
    f = COLS[c] + ROWS[r + dir * 2]
    @moves << f if !@board.pieces[f] and first_step
  end
  
  # hits
  [-1, 1].each do |x|
    if c + x >= 0 and c + x <= 7
      if (r - 1 >= 0 and @color == :white) or (r + 1 <= 7 and
                                               @color == :black)
        f = COLS[c + x] + ROWS[r + dir]
        @hits << f if @board.pieces[f]
      end
    end
  end
end