I am creating a tic tac toe game where I would like the computer to go in strategic spots based on the available winning combos on the board. For some reason, the computer_index
method works until turn_count == 4
, where it outputs the entire WIN_COMBINATIONS
array instead of just one value. Understandably, this creates an error in the valid_move?
method. The relevant error and code are as follows.
Traceback (most recent call last):
3: from tictactoe.rb:12:in `<main>'
2: from /Users/irosen419/Flatiron/code/tictactoe/tic_tac_toe.rb:201:in `play'
1: from /Users/irosen419/Flatiron/code/tictactoe/tic_tac_toe.rb:117:in `comp_turn'
/Users/irosen419/Flatiron/code/tictactoe/tic_tac_toe.rb:40:in `valid_move?': undefined method `between?' for #<Array:0x00007fbe650d8268> (NoMethodError)
WIN_COMBINATIONS = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 4, 8], [2, 4, 6], [0, 3, 6], [1, 4, 7], [2, 5, 8]]
def valid_move?(index)
index.between?(0,8) && !position_taken?(index)
end
def computer_index
if turn_count == 0
CORNERS.sample
elsif turn_count == 2
CORNERS.sample
elsif turn_count == 4 || turn_count == 6
WIN_COMBINATIONS.each do |combo|
if @board[combo[0]] == "X" && @board[combo[1]] == "X"
@board[combo[2]]
elsif @board[combo[1]] == "X" && @board[combo[2]] == "X"
@board[combo[0]]
elsif @board[combo[0]] == "X" && @board[combo[2]] == "X"
@board[combo[1]]
elsif @board[combo[0]] == "O" && @board[combo[1]] == "O"
@board[combo[2]]
elsif @board[combo[1]] == "O" && @board[combo[2]] == "O"
@board[combo[0]]
elsif @board[combo[0]] == "O" && @board[combo[2]] == "O"
@board[combo[1]]
else
CORNERS.sample
end
end
else
@board.each do |space|
if space == " "
space
end
end
end
end
def comp_turn
index = computer_index
if valid_move?(index)
move(index, current_player)
display_board
else
comp_turn
end
end
def turn_count
count = 0
@board.each do |space|
if space == "X" || space == "O"
count +=1
end
end
count
end
I think you are missing return
statements :
def computer_index
if turn_count == 0
CORNERS.sample
elsif turn_count == 2
CORNERS.sample
elsif turn_count == 4 || turn_count == 6
WIN_COMBINATIONS.each do |combo|
if @board[combo[0]] == "X" && @board[combo[1]] == "X"
return @board[combo[2]]
elsif @board[combo[1]] == "X" && @board[combo[2]] == "X"
return @board[combo[0]]
elsif @board[combo[0]] == "X" && @board[combo[2]] == "X"
return @board[combo[1]]
elsif @board[combo[0]] == "O" && @board[combo[1]] == "O"
return @board[combo[2]]
elsif @board[combo[1]] == "O" && @board[combo[2]] == "O"
return @board[combo[0]]
elsif @board[combo[0]] == "O" && @board[combo[2]] == "O"
return @board[combo[1]]
else
return CORNERS.sample
end
end
else
@board.each do |space|
if space == " "
space
end
end
end
end