Class: Game

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

Defined Under Namespace

Classes: IllegalMove

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeGame

Returns a new instance of Game.



4
5
6
7
8
9
10
# File 'lib/game.rb', line 4

def initialize
  @board = Board.new
  @kings = {white: @board.at(4,0), black: @board.at(3,7)}
  @moves = []
  @turn = :white
  @over = false
end

Instance Attribute Details

#turnObject (readonly)

Returns the value of attribute turn.



3
4
5
# File 'lib/game.rb', line 3

def turn
  @turn
end

Instance Method Details

#at(x, y) ⇒ Object



20
21
22
# File 'lib/game.rb', line 20

def at(x,y)
  @board.at(x,y)
end

#over?Boolean

Returns:

  • (Boolean)


16
17
18
# File 'lib/game.rb', line 16

def over?
  @over
end

#play(point_a, point_b) ⇒ Object

Raises:



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/game.rb', line 37

def play(point_a, point_b) 
  raise Game::IllegalMove, "Game over" if @over

  piece, at_destination = at(*point_a), at(*point_b) 

  unless piece.color == @turn
      raise Game::IllegalMove, 
        "It is #{@turn.to_s.capitalize}'s turn" 
  end

  @board.move(piece, *point_b)
  @moves << {
    piece: {
      point_a: point_a,
      point_b: point_b,
    },
    capture: at_destination,
  }

  if @kings[@turn].checked?(@board)
    undo
    raise Game::IllegalMove, "#{@turn}'s king is in check!"
  end

  switch_turn
end

#resignObject



64
65
66
67
68
69
# File 'lib/game.rb', line 64

def resign
  @over = true
  print "#{@turn.to_s.capitalize} resigns, "
  switch_turn
  puts "#{@turn.to_s.capitalize} wins!" 
end

#showObject



12
13
14
# File 'lib/game.rb', line 12

def show
  puts @board
end

#undoObject



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

def undo
  move = @moves.pop
  piece = at(*move[:piece][:point_a])
  new_piece = piece.class.new(*move[:piece][:point_b])
  capture = move[:capture]

  @board.remove(piece)
  @board.place(new_piece)
  @board.place(capture)

  switch_turn
end