井字游戏中 nil:NilClass (NoMethodError) 的未定义方法“[]”

undefined method `[]' for nil:NilClass (NoMethodError) in tic-tac-toe game

我正在构建一个在命令行上玩的井字游戏。

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') 更改数组的方法给我一个错误。我找不到我的代码抛出这个特定错误的原因。

您正在呼叫 spaces[cell]。错误是告诉你你在 nil 上调用 [],这意味着 spaces 必须是 nil。

也许你是说 @spaces?否则 - 您需要告诉程序 spaces 是如何定义的以及它是如何初始化的。一个简单的 spaces = {} unless spaces 就可以了

另一种初始化 spaces 变量的方法是在初始化游戏时调用 super:

class Game < Board 
    attr_reader :player1, :player2

    def initialize
      super
      play_game
    end
    ...

问题是您没有在 Game class 中调用父构造函数,因此 @spaces 未初始化。

您的层次结构决策有问题,但要使其起作用,您只需将 Game 构造函数更改为:

def initialize
  super
  play_game
end