Class: State
- Inherits:
-
Object
- Object
- State
- Defined in:
- lib/state.rb
Instance Method Summary collapse
- #diagonal_major?(board, mark) ⇒ Boolean
- #diagonal_minor?(board, mark) ⇒ Boolean
- #empty_indices(board) ⇒ Object
- #full?(board) ⇒ Boolean
- #horizontal?(board, mark) ⇒ Boolean
-
#initialize(manager) ⇒ State
constructor
A new instance of State.
- #terminal?(board) ⇒ Boolean
- #tie?(board) ⇒ Boolean
- #vertical?(board, mark) ⇒ Boolean
- #winner?(board, mark) ⇒ Boolean
Constructor Details
#initialize(manager) ⇒ State
Returns a new instance of State.
2 3 4 |
# File 'lib/state.rb', line 2 def initialize(manager) @manager = manager end |
Instance Method Details
#diagonal_major?(board, mark) ⇒ Boolean
45 46 47 48 49 50 51 52 |
# File 'lib/state.rb', line 45 def diagonal_major?(board, mark) count = 0 (0..board.size - 1).each do |pos| count += 1 if (pos % (Math.sqrt(board.size) + 1)) == 0 && board[pos] == mark return true if count == Math.sqrt(board.size) end return false end |
#diagonal_minor?(board, mark) ⇒ Boolean
54 55 56 57 58 59 60 61 |
# File 'lib/state.rb', line 54 def diagonal_minor?(board, mark) count = 0 (Integer(Math.sqrt(board.size) - 1)..board.size - (Math.sqrt(board.size))).each do |pos| count += 1 if (pos % (Math.sqrt(board.size) - 1)) == 0 && board[pos] == mark return true if count == Math.sqrt(board.size) end return false end |
#empty_indices(board) ⇒ Object
6 7 8 9 10 11 12 |
# File 'lib/state.rb', line 6 def empty_indices(board) indices = [] for i in 0..board.length - 1 indices.push(i) if board[i] == "-" end indices end |
#full?(board) ⇒ Boolean
14 15 16 |
# File 'lib/state.rb', line 14 def full?(board) empty_indices(board) == [] end |
#horizontal?(board, mark) ⇒ Boolean
22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/state.rb', line 22 def horizontal?(board, mark) count = 0 (0..board.size - 1).each do |pos| count = 0 if pos % Math.sqrt(board.size) == 0 if board[pos] == mark count += 1 return true if count == Math.sqrt(board.size) end end return false end |
#terminal?(board) ⇒ Boolean
67 68 69 |
# File 'lib/state.rb', line 67 def terminal?(board) winner?(board, @manager.first) || winner?(board, @manager.second) || tie?(board) end |
#tie?(board) ⇒ Boolean
18 19 20 |
# File 'lib/state.rb', line 18 def tie?(board) full?(board) && !winner?(board, @manager.first) && !winner?(board, @manager.second) end |
#vertical?(board, mark) ⇒ Boolean
34 35 36 37 38 39 40 41 42 43 |
# File 'lib/state.rb', line 34 def vertical?(board, mark) (0..Math.sqrt(board.size) - 1).each do |col| count = 0 for row in 0..board.size - 1 count += 1 if (row % Math.sqrt(board.size)) == 0 && board[col+row] == mark end return true if count == Math.sqrt(board.size) end return false end |
#winner?(board, mark) ⇒ Boolean
63 64 65 |
# File 'lib/state.rb', line 63 def winner?(board, mark) horizontal?(board, mark) || vertical?(board, mark) || diagonal_major?(board, mark) || diagonal_minor?(board, mark) end |