0
這是用於在特定位置的棋類遊戲中生成每個棋子的移動的代碼。使用attr_accessor獲取NameError代碼
class Characters
def initialize(behaviours)
@position=behaviours.fetch(:assigning_position)
@right=behaviours.fetch(:moving_right)
end
def perform_position
@position.kmoves
end
def perform_right
@right.rightmove
end
end
這是爲特定典當分配位置的方法。
class Position
def kmoves
print "enter x value"
xpos=STDIN.gets.chomp
print "enter y value"
ypos=STDIN.gets.chomp
print "#{xpos}, #{ypos}\n"
end
end
這是一個位置移動棋子其右邊
class Right_move < Position
def rightmove
puts "compute right moves"
xpos+=1
end
end
king = Characters.new(assigning_position:Position.new,moving_right:Right_move.new)
king.perform_position
king.perform_right
我得到了錯誤的方法:
in
kmoves': undefined local variable or method
xpos' for # (NameError)
我實際上正在嘗試創建一個通用的移動方法,比如右對角線和左對角線等,並且實現了一個rake文件,其中的ill根據這些棋子調用for循環中的每個方法。 'rightmove'中的 –
:未定義的方法'+'for nil:NilClass(NoMethodError –