我正在构建一个井字棋游戏,以在命令行中播放。在井字棋游戏中,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