Class: TicTacToe::Game

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parameters) ⇒ Game

Returns a new instance of Game.



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

def initialize(parameters)
  @player_marks = parameters[:player_marks] || [:x, :o]
  @board = parameters[:board] || create_default_board
  @interface = parameters[:interface] || create_default_interface
  @players = []
end

Instance Attribute Details

#boardObject (readonly)

Returns the value of attribute board.



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

def board
  @board
end

#interfaceObject (readonly)

Returns the value of attribute interface.



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

def interface
  @interface
end

#player_marksObject (readonly)

Returns the value of attribute player_marks.



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

def player_marks
  @player_marks
end

#playersObject (readonly)

Returns the value of attribute players.



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

def players
  @players
end

Instance Method Details

#get_valid_move(player) ⇒ Object



44
45
46
47
48
49
50
51
52
53
# File 'lib/game.rb', line 44

def get_valid_move(player)
  loop do
    coordinates = player.move
    if @board.out_of_bounds?(coordinates) || @board.marked?(coordinates)
      @interface.report_invalid_move(coordinates)
    else
      return coordinates
    end
  end
end

#handle_game_overObject



55
56
57
58
59
# File 'lib/game.rb', line 55

def handle_game_over
  @interface.show_game_board(@board)
  winning_player_mark = @board.has_winning_line? ? @board.last_mark_made : :none
  @interface.report_game_over(winning_player_mark)
end

#handle_one_turn(current_player) ⇒ Object



37
38
39
40
41
42
# File 'lib/game.rb', line 37

def handle_one_turn(current_player)
  @interface.show_game_board(@board)
  coordinates = get_valid_move(current_player)
  @board.mark_cell(current_player.player_mark, *coordinates)
  @interface.report_move(current_player.player_mark, coordinates)
end

#handle_turnsObject



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

def handle_turns
  catch(:game_over) do
    @players.cycle do |current_player|
      handle_one_turn(current_player)
      throw :game_over if over?
    end
  end
end

#over?Boolean

Returns:

  • (Boolean)


61
62
63
# File 'lib/game.rb', line 61

def over?
  @board.has_winning_line? || @board.all_marked?
end

#runObject



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

def run
  set_up
  handle_turns
  handle_game_over
end

#set_upObject



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

def set_up
  player_types = @interface.game_setup_interaction(@player_marks)

  @players = @player_marks.zip(player_types).map { |mark, type| create_player(mark, type) }
end