如何从另一个类访问一个类实例变量而不创建该类的新实例

时间:2019-01-17 04:39:37

标签: ruby

我有一个创建哈希值的类Board

class Board
  attr_accessor :board

  def initialize
    @board = {}
  end

  def generate_board
    i = 0
    until i == 8
      @board[i] = [" . ", " . ", " . ", " . ", " . ", " . ", " . "," . "]
      i += 1
    end
  end
end

我正在尝试从其他类访问它:

class Pawn
  def legal_moves
    possible_moves = []
    if @board[@position[0] + 1][@position[1] + 1].is_a? Piece
      possible_moves << [[@position[0] + 1, @position[1] + 1]]
    end
    if @board[@position[0] + 1][@position[1] - 1].is_a? Piece
      possible_moves << [[@position[0] + 1, @position[1] - 1]]
    end
    @legal_moves = possible_moves
  end
end

如何在不创建新板对象的情况下访问此保存的板状态?我无法创建新的板对象,因为板的状态需要保持不变。我已经在另一个玩游戏的类中创建了一个原始实例。

2 个答案:

答案 0 :(得分:0)

您将面板传递给新的pawn实例。

class Pawn
  attr_reader :board, :location_x, :location_y

  def initialize(board)
    @board = board
    @location_x = nil
    @location_y = nil
  end

  def move(x, y)
    if board.get(x, y).nil?
      board.set(location_x, location_y, nil)
      self.location_x = x
      self.location_y = y
      board.set(x, y, self)
    else
      false
    end
  end
end

> board = Board.new
> pawn = Pawn.new(board)
> pawn.move(0,0)
> board.get(0,0) == pawn
=> true

答案 1 :(得分:0)

如果您想获得更多有关面向对象编程的经验,可以使用Singleton pattern

require 'singleton'

class Board
  include Singleton

  attr_accessor :board

  def generate_board
    @board = {}
    i = 0
    until i == 8
      @board[i] = [" . ", " . ", " . ", " . ", " . ", " . ", " . "," . "]
      i += 1
    end
  end
end

在这种情况下,要生成木板,您应该致电:Board.instance.generate_board

并且当您需要从其他类访问 board 时,可以向init添加一行:

class Pawn
  def initialize
    @board = Board.instance.board
  end
end

现在,您可以像在示例中一样在@board对象内使用Pawn

@board[@position[0] + 1][@position[1] + 1]

祝你好运!