Class: Game

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeGame

Returns a new instance of Game.



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

def initialize
  @board = Board.new
  @scoring = Scoring.new
  @validate = Validate.new
  @players = []
end

Instance Attribute Details

#boardObject (readonly)

Returns the value of attribute board.



9
10
11
# File 'lib/ang_ttt_gem/game.rb', line 9

def board
  @board
end

#playersObject (readonly)

Returns the value of attribute players.



9
10
11
# File 'lib/ang_ttt_gem/game.rb', line 9

def players
  @players
end

Instance Method Details

#create_computer_player(mark) ⇒ Object



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

def create_computer_player(mark)
  @players << ComputerPlayer.new(mark)
end

#create_human_player(mark) ⇒ Object



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

def create_human_player(mark)
  @players << HumanPlayer.new(mark)
end

#gather_board_stateObject



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

def gather_board_state
  @board.current_state
end

#get_player_move(player) ⇒ Object



26
27
28
29
# File 'lib/ang_ttt_gem/game.rb', line 26

def get_player_move(player)
  index = player - 1
  @players[index].get_move(@board)
end

#is_over?Boolean

Returns:

  • (Boolean)


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

def is_over?
 @scoring.winner?(@board) || @scoring.draw?(@board)
end

#make_move(move, mark) ⇒ Object



43
44
45
# File 'lib/ang_ttt_gem/game.rb', line 43

def make_move(move,mark)
  @board.set(move, mark)
end

#make_move_player(player, move) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/ang_ttt_gem/game.rb', line 35

def make_move_player(player, move)
  index = player - 1
  mark = @players[index].mark
  return false unless move_valid?(move)
  make_move(move,mark)
  prepare_display_state
end

#move_valid?(move) ⇒ Boolean

Returns:

  • (Boolean)


31
32
33
# File 'lib/ang_ttt_gem/game.rb', line 31

def move_valid?(move)
  (0..8).include?(move)
end

#prepare_display_stateObject



51
52
53
54
55
# File 'lib/ang_ttt_gem/game.rb', line 51

def prepare_display_state
  gather_board_state.each_with_index.map do |cell, index|
    cell == " " ? (index + 1).to_s : cell
  end
end

#resultObject



65
66
67
68
69
70
71
72
73
74
# File 'lib/ang_ttt_gem/game.rb', line 65

def result
  message_key = :draw
  @players.each_with_index do |player, i|
    num = i + 1
    if @scoring.winning_mark(@board) == player.mark
      message_key = "player_#{num}_win".to_sym
    end
  end
  message_key
end

#square_taken?(cell_number) ⇒ Boolean

Returns:

  • (Boolean)


47
48
49
# File 'lib/ang_ttt_gem/game.rb', line 47

def square_taken?(cell_number)
   @board.cell_occupied?(cell_number)
end