我正在構建一個井字棋遊戲,以在命令行中播放。在井字棋遊戲中,nil:NilClass(NoMethodError)的未定義方法`[]'
module TicTacToe
class Player
attr_accessor :symbol
def initialize(symbol)
@symbol = symbol
end
end
class Board
attr_reader :spaces
def initialize
@spaces = Array.new(9)
end
def to_s
output = ""
0.upto(8) do |position|
output << "#{@spaces[position] || position}"
case position % 3
when 0, 1 then output << " | "
when 2 then output << "\n-----------\n" unless position == 8
end
end
output
end
def space_available(cell, sym)
if spaces[cell].nil?
spaces[cell] = sym
else
puts "Space unavailable"
end
end
end
class Game < Board
attr_reader :player1, :player2
def initialize
play_game
end
def play_game
@player1 = Player.new("X")
@player2 = Player.new("O")
puts Board.new
@current_turn = 1
turn
end
def move(player)
while victory != true
puts "Where would you like to move?"
choice = gets.chomp.to_i
space_available(choice, player.symbol)
puts Board
@current_turn += 1
turn
end
end
def turn
@current_turn.even? ? move(@player2) : move(@player1)
end
def victory
#still working on this
end
end
end
puts TicTacToe::Game.new
即取一個用戶的小區的選擇(space_available
),並改變與他們的片('X'
或'O'
)陣列的方法,是給我一個錯誤。我找不到爲什麼我的代碼拋出這個特定的錯誤。
也應該是'提出self',而不是'把Board' –
有什麼錯誤你得到? – sawa
@sawa錯誤閱讀'tic_tac_toe.rb:34:在'space_available':未定義方法\'[]'爲零:NilClass(NoMethodError)' – scobo