I'm creating a game of tic-tac-toe. I am new to ruby, and have defined a class Game, with two inner-classes Player and GameBoard. Within Game I define two instance-variables player1 and player2. I am trying to access both player1 and player2 inside of the method GameBoard.update_gameboard like so
def update_gameboard(player)
move = if player == 1
@player1.moves[@player1.turn]
else
@player2.moves[@player2.turn]
end
.
.
.
And I get the error:
/Users/Jacob/Development/RubyDev/RubymineProjects/TicTacToe/tictactoe.rb:85:in `update_gameboard': undefined method `moves' for nil:NilClass (NoMethodError)
from /Users/Jacob/Development/RubyDev/RubymineProjects/TicTacToe/tictactoe.rb:44:in `play'
from /Users/Jacob/Development/RubyDev/RubymineProjects/TicTacTOe/main.rb:30:in `<top (required)>'
from -e:1:in `load'
from -e:1:in `<main>'
Process finished with exit code 1
moves is not a method, it's an array. (play is a method in Game which calls update_gameboard)
How do I access the instance-variables of an outer-class (Game) from an inner class (e.g. GameBoard)?
class Game
attr_accessor :winner, :player1, :player2, :gameboard
def initialize(player1_name, player2_name)
@player1 = Player.new(player1_name, 'X')
@player2 = Player.new(player2_name, 'O')
@gameboard = GameBoard.new
end
.
.
.
class GameBoard
attr_accessor :current_gameboard
attr_reader :gameboard_move_map
def initialize
# initialize irrelevant GameBoard variables
end
def update_gameboard(player)
move = if player == 1
@player1.moves[@player1.turn]
else
@player2.moves[@player2.turn]
end
#then some more stuff that uses @player1 and @player2
end
.
.
.
end
end