So I am trying to make get_move method in human_player class to take input from user and check if that position in the grid/board is empty and if not then ask the user to try again. For that I am trying to access board attribute but it throws me error for the code mentioned here. Also I tried to print value of board using p (the commented line) and it shows “nil” and hence the error message makes sense but what I cannot understand is why can’t it access board elements.
Code:
class HumanPlayer
attr_reader :name, :board
attr_accessor :mark
def initialize(name)
@name = name
end
def name
@name
end
def get_move
puts("where")
while true
ans = gets.chomp.split(",").map {|x| x.to_i}
#p board
if ans[0]>2 || ans[1] > 2 || board[ans] != nil
puts("try again")
ans = nil
else
break
end
end
ans
end
def display(x)
(0..2).each do |row|
(0..2).each do |col|
if x[[row,col]] == nil
print("| ")
else
print ("|#{x[[row,col]]} ")
end
end
puts("|\n")
puts("|---|---|---|")
end
end
end
Error Message:
/home/sky/Downloads/tic/lib/human_player.rb:18:in get_move': undefined method
[]’ for nil:NilClass (NoMethodError)
from game.rb:20:in play_turn' from game.rb:30:in
play’
from game.rb:54:in `’