Class: TicTacToe
- Inherits:
-
Object
- Object
- TicTacToe
- Defined in:
- lib/tic_tac_toe.rb,
lib/tic_tac_toe/version.rb
Constant Summary collapse
- BOARD =
<<BOARD ------------- | X | X | X | ------------- | X | X | X | ------------- | X | X | X | ------------- BOARD
- PLAYERS =
['X','O']
- VERSION =
"0.2.3"
Instance Attribute Summary collapse
-
#player ⇒ Object
readonly
Returns the value of attribute player.
-
#position ⇒ Object
readonly
Returns the value of attribute position.
Instance Method Summary collapse
- #ai_move ⇒ Object
- #board ⇒ Object
- #draw? ⇒ Boolean
-
#initialize ⇒ TicTacToe
constructor
A new instance of TicTacToe.
- #move(x, y) ⇒ Object
- #set ⇒ Object
- #winner ⇒ Object
Constructor Details
Instance Attribute Details
#player ⇒ Object (readonly)
Returns the value of attribute player.
15 16 17 |
# File 'lib/tic_tac_toe.rb', line 15 def player @player end |
#position ⇒ Object (readonly)
Returns the value of attribute position.
15 16 17 |
# File 'lib/tic_tac_toe.rb', line 15 def position @position end |
Instance Method Details
#ai_move ⇒ Object
44 45 46 47 48 |
# File 'lib/tic_tac_toe.rb', line 44 def ai_move return unless position = ai_select_position @position = position set end |
#board ⇒ Object
23 24 25 26 27 28 29 30 |
# File 'lib/tic_tac_toe.rb', line 23 def board index = -1 BOARD.gsub(" X ") do index += 1 field = @fields[index] @position == index ? "[#{field}]" : " #{field} " end end |
#draw? ⇒ Boolean
50 51 52 |
# File 'lib/tic_tac_toe.rb', line 50 def draw? @fields.index(' ') == nil end |
#move(x, y) ⇒ Object
32 33 34 35 36 |
# File 'lib/tic_tac_toe.rb', line 32 def move(x,y) x = (@position + x) % 3 y = ((@position / 3) + y) % 3 @position = x + (y * 3) end |
#set ⇒ Object
38 39 40 41 42 |
# File 'lib/tic_tac_toe.rb', line 38 def set return if @fields[@position] != ' ' @fields[@position] = @player @player = next_player end |
#winner ⇒ Object
54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/tic_tac_toe.rb', line 54 def winner [ [0,1,2],[3,4,5],[6,7,8], # vertical [0,3,6],[1,4,7],[2,5,8], # horizontal [0,4,8],[2,4,6] # diagonal ].each do |pattern| players = pattern.map{|i| @fields[i] }.uniq next if players.size != 1 winner = players.first next if winner == ' ' return winner end nil end |