![](/img/trans.png)
[英]undefined method `keys' for nil:NilClass in tic tac toe game RUBY
[英]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
变量的另一种方法是在初始化Game时调用super:
class Game < Board
attr_reader :player1, :player2
def initialize
super
play_game
end
...
问题在于您不会在Game
类中调用父构造函数,因此@spaces
不会初始化。
您的层次结构决定值得怀疑,但是要使其起作用,您只需将Game
构造函数更改为:
def initialize
super
play_game
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.