class Game

Attributes

turn[R]

Public Class Methods

new() click to toggle source
# File lib/game.rb, line 4
def initialize
  @board = Board.new
  @king_to_check = {black: @board.at(3,0), white: @board.at(3,7)}
  @moves = []
  @turn = :white
  @over = false
end

Public Instance Methods

at(x,y) click to toggle source
# File lib/game.rb, line 20
def at(x,y)
  @board.at(x,y)
end
over?() click to toggle source
# File lib/game.rb, line 16
def over?
  @over
end
play(point_a, point_b) click to toggle source
# 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,
  }
  switch_turn

  if @king_to_check[@turn].checked?(@board)
    undo
    raise Game::IllegalMove, "#{@turn}'s king is in check!"
  end
end
resign() click to toggle source
# File lib/game.rb, line 63
def resign
  @over = true
  print "#{@turn.to_s.capitalize} resigns, "
  switch_turn
  puts "#{@turn.to_s.capitalize} wins!" 
end
show() click to toggle source
# File lib/game.rb, line 12
def show
  puts @board
end
undo() click to toggle source
# File lib/game.rb, line 24
def undo
  move = @moves.pop
  piece = at(*move[:piece][:point_b])
  new_piece = piece.class.new(*move[:piece][:point_a])
  capture = move[:capture]

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

  switch_turn
end

Private Instance Methods

switch_turn() click to toggle source
# File lib/game.rb, line 71
def switch_turn 
  @turn = @turn == :white ? :black : :white
end