class TicTacToe::Gameplay

Attributes

board[R]

Public Class Methods

new(checker, ui, players_name) click to toggle source
# File lib/tic_tac_toe/gameplay.rb, line 9
def initialize(checker, ui, players_name)
  create_players(players_name)
  @ui = ui
  prepare_initial_conditions
  add_observer(checker)
end

Public Instance Methods

finish_game() click to toggle source
# File lib/tic_tac_toe/gameplay.rb, line 20
def finish_game
  @game_finished = true
end
finished_turn_status(args = { win: false, draw: false }) click to toggle source
# File lib/tic_tac_toe/gameplay.rb, line 24
def finished_turn_status(args = { win: false, draw: false })
  @ui.display_board(board: @board)
  @ui.display_msg_draw if args[:draw]
  @ui.display_msg_win(player_name: @players[@turn].name) if args[:win]
end
play() click to toggle source
# File lib/tic_tac_toe/gameplay.rb, line 16
def play
  player_turn while !@game_finished
end

Private Instance Methods

change_turn() click to toggle source
# File lib/tic_tac_toe/gameplay.rb, line 74
def change_turn
  @turn = (@turn + 1) % 2
end
completed_player_move(input) click to toggle source
# File lib/tic_tac_toe/gameplay.rb, line 67
def completed_player_move(input)
  @board.fill_board_space(input, @players[@turn])
  changed
  notify_observers(gameplay: self, player: @players[@turn])
  change_turn unless @game_finished
end
create_players(players_name) click to toggle source
# File lib/tic_tac_toe/gameplay.rb, line 31
def create_players(players_name)
  @players = players_name.map { |name| Player.new(name) }
  @players << Player.new('Computer', computer: true) if @players.size == 1
end
input_action(option) click to toggle source
# File lib/tic_tac_toe/gameplay.rb, line 54
def input_action(option)
  case option
  when 'help' then @ui.display_gameplay_instructions
  when 'quit' then finish_game
  when 'reset' then reset
  else completed_player_move(option)
  end
end
player_turn() click to toggle source
# File lib/tic_tac_toe/gameplay.rb, line 48
def player_turn
  @ui.display_turn_status(board: @board, player_name: @players[@turn].name)
  input = @ui.input_player_action(@players[@turn], @board)
  input_action(input)
end
prepare_initial_conditions() click to toggle source
# File lib/tic_tac_toe/gameplay.rb, line 36
def prepare_initial_conditions
  @game_finished = false
  @board = Board.new
  @turn = Kernel.rand(2)
  set_players_symbols
end
reset() click to toggle source
# File lib/tic_tac_toe/gameplay.rb, line 63
def reset
  prepare_initial_conditions
end
set_players_symbols() click to toggle source
# File lib/tic_tac_toe/gameplay.rb, line 43
def set_players_symbols
  @players[@turn].symbol = "X" 
  @players[(@turn + 1) % 2].symbol = "O"
end