Class: MailChess::Piece::King

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

Overview

Represents a king 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) ⇒ King

Calls the superclass.



11
12
13
14
15
# File 'lib/mail_chess/pieces/king.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/king.rb', line 18

def self.new! db, board, position, color
  super db, board, position, color

  id = db[:pieces].insert(:type => 'king', 
                          :color => color.to_s,
                          :position => position,
                          :board_id => board.id)

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

def generate_moves
  super
  
  r, c = ROWS.index(position[1]), COLS.index(position[0])
  (r - 1..r + 1).each do |y|
    (c - 1..c + 1).each do |x|
      if x >= 0 and x <= 7 and y >= 0 and y <= 7
        f = COLS[x] + ROWS[y]
        if @board.pieces[f] # is there a piece
          @hits << f
        else
          @moves << f
        end
      end
    end
  end
  
  @hits.delete(position)
end

#in_check?Boolean

Decide wether this king is in check.

Returns: (Boolean)

Returns:

  • (Boolean)


53
54
55
56
57
58
59
60
61
# File 'lib/mail_chess/pieces/king.rb', line 53

def in_check?
  @board.pieces.values.each do |p|
    if p.color != @color # if opponent's piece
      return true if p.can_hit?(position)
    end
  end
  
  return false
end

#in_checkmate?Boolean

Decide wether this king is in checkmate. (dumb method, FIXME)

Returns: (Boolean)

Returns:

  • (Boolean)


66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/mail_chess/pieces/king.rb', line 66

def in_checkmate?
  return false if not in_check? # if not in even check
  
  original = @board.pieces
  
  @board.pieces.values.each do |p|
    if p.color == @color # if player's piece
      original_moves_hits = p.moves + p.hits
      original_moves_hits.each do |m|
        p.move m
        @board.generate_pieces_moves
        if not in_check?
          @board.pieces = original
          return false
        end
        @board.pieces = original
      end
    end
  end
  return true
end