Jacob Moore Jacob Moore - 3 years ago 176
Ruby Question

Possible moves on a chess board, using instance from one class in another.

I'm working on making a chess game. I want to keep everything that has to do with possible moves inside each type of pieces class. In order to do this I need to refer back to @board[][]. The commented section of code in the possible_moves method is what I would like to do, except it does not work and throws an error.

class Board
attr_accessor :board, :choice
def initialize
@board = Array.new(8){Array.new(8," ")}
@choice = choice
end

def set_board
@board[0][2] = Bishop.new([0,2],false)
end
end

class Bishop
attr_accessor :x_position, :y_position, :piece, :color, :moves
def initialize(position,is_white)
@x_position = position[0]
@y_position = position[1]
@piece = is_white ? "♝" : "♗"
@color = is_white ? "white" : "black"
@moves = [[+1,-1],
[+1,+1],
[-1,+1],
[-1,-1]]
end

def possible_moves
move_list = Array.new
@moves.each do |moves|
x = @x_position
y = @y_position
loop do
x += moves[0]
y += moves[1]
break if x.between?(0,7) == false
break if y.between?(0,7) == false
# This is where I want to refer back to @board from the Board class.
# if @board[x][y].color.....
move_list << [x,y]
#end
end
end
p move_list
end


end

Answer Source

You can pass the board into the Bishop constructor:

class Bishop
  attr_reader :board
  # etc.
  def initialize(position,is_white,board) 
    @board = board.board # or just @board = board and you can fetch the matrix later
    # etc.
  end
end

class Board
  # etc.
  def set_board
    @board[0][2] = Bishop.new([0,2],false, self) 
  end 
end
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download