Class: Game

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(player_white, player_black) ⇒ Game

Returns a new instance of Game.



9
10
11
12
13
14
15
16
# File 'lib/game.rb', line 9

def initialize(player_white, player_black)
  @board = Board.new
  @player_white = player_white
  @player_white.board = @board
  @player_black = player_black
  @player_black.board = @board
  @current_player = player_white
end

Instance Attribute Details

#boardObject

Returns the value of attribute board.



7
8
9
# File 'lib/game.rb', line 7

def board
  @board
end

Instance Method Details

#game_statusObject



30
31
32
33
34
35
36
# File 'lib/game.rb', line 30

def game_status
  message = ""
  if @board.in_check?(@current_player.color)
    message += "#{@current_player.color.to_s.capitalize} is in check \n"
  end
  message += "#{@current_player.color.to_s.capitalize}'s turn \n"
end

#playObject



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/game.rb', line 38

def play
  until @board.won? || @board.stalemate?(@current_player.color)
    begin
      board.render
      puts game_status
      start_pos, end_pos = @current_player.make_move
      @board.move(start_pos, end_pos, @current_player.color)
      switch_player
    rescue MoveError => e
      puts e.message
      puts "Enter to continue"
      gets
    end
  end
  board.render
  if @board.stalemate?(@current_player.color)
    puts "Stalemate"
  else
    switch_player
    puts "#{@current_player.color.to_s.capitalize} wins!"
  end
end

#right_color?(pos) ⇒ Boolean

Returns:

  • (Boolean)


18
19
20
# File 'lib/game.rb', line 18

def right_color?(pos)
  @board[pos].color == @current_player.color
end

#switch_playerObject



22
23
24
25
26
27
28
# File 'lib/game.rb', line 22

def switch_player
  if @current_player == @player_white
    @current_player = @player_black
  else
    @current_player = @player_white
  end
end