2015-09-14 63 views
0

我正在構建一個井字棋遊戲,以在命令行中播放。在井字棋遊戲中,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')陣列的方法,是給我一個錯誤。我找不到爲什麼我的代碼拋出這個特定的錯誤。

+2

也應該是'提出self',而不是'把Board' –

+0

有什麼錯誤你得到? – sawa

+0

@sawa錯誤閱讀'tic_tac_toe.rb:34:在'space_available':未定義方法\'[]'爲零:NilClass(NoMethodError)' – scobo

回答

1

的問題是,你不調用父類的構造在Game類,因此@spaces未初始化。

你的層次決策是值得商榷的,但要使其工作,你可以簡單地將Game構造改變爲:

def initialize 
    super 
    play_game 
end 
+0

最好有疑問:) –

+0

@SergioTulentsev,非常非常:) – ndn

+0

謝謝@ndn。這對我有效。這不在我的問題的範圍之內,但是你能解釋一下你的意思嗎?你是指從Board類繼承的Game類嗎? – scobo

1

您正在致電spaces[cell]。錯誤是告訴你,你在nil上調用[],這意味着spaces必須爲零。

也許你的意思是@spaces?否則 - 您需要告訴程序如何定義spaces以及它是如何初始化的。一個簡單的spaces = {} unless spaces會工作

初始化你spaces變量將是超級調用的另一種方式,當你初始化遊戲:

class Game < Board 
    attr_reader :player1, :player2 

    def initialize 
     super 
     play_game 
    end 
    ... 
+0

'attr_reader'負責定義'空格' –

+0

也許 - 但它是未初始化。遊戲子類初始化程序不會調用超級 – Yule

+0

是的,這是真的。 –

相關問題