Class: TaTeTi::SmartPlayer

Inherits:
Player
  • Object
show all
Defined in:
lib/ta_te_ti/smart_player.rb

Instance Attribute Summary

Attributes inherited from Player

#mark

Instance Method Summary collapse

Methods inherited from Player

#initialize

Constructor Details

This class inherits a constructor from TaTeTi::Player

Instance Method Details

#finish(final_board) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/ta_te_ti/smart_player.rb', line 40

def finish( final_board )
  print final_board
  
  if final_board.won? == @mark
    print "Congratulations, you win.\n\n"
win = 1
  elsif final_board.won? == " "
    print "Tie game.\n\n"
win = 0
  else
    print "You lost tic-tac-toe?!\n\n"
win = -1
  end
			win
end

#move(board) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/ta_te_ti/smart_player.rb', line 3

def move( board )
  moves = board.moves
  
  # If I have a win, take it.  If he is threatening to win, stop it.
  board.each_row do |row|
    if row.blanks == 1 and (row.xs == 2 or row.os == 2)
      (0..2).each do |e|
        return row.to_board_name(e) if row[e] == " "
      end
    end
  end

  # Take the center if open.
  return "b2" if moves.include? "b2"

  # Defend opposite corners.
  if board[0] != @mark and board[0] != " " and board[8] == " "
    return "c3"
  elsif board[8] != @mark and board[8] != " " and board[0] == " "
    return "a1"
  elsif board[2] != @mark and board[2] != " " and board[6] == " "
    return "c1"
  elsif board[6] != @mark and board[6] != " " and board[2] == " "
    return "a3"
  end
  
  # Defend against the special case XOX on a diagonal.
  if board.xs == 2 and board.os == 1 and board[4] == "O" and
     (board[0] == "X" and board[8] == "X") or
     (board[2] == "X" and board[6] == "X")
    return %w{a2 b1 b3 c2}[rand(4)]
  end
  
  # Or make a random move.
  moves[rand(moves.size)]
end