Ruby为象棋网格命名Square对象

时间:2015-12-01 23:35:24

标签: ruby chess

我正在用Ruby写一个Chess程序。我试图创建一个包含64个Square对象的Board,它将跟踪piece_on_squarex位置,y位置和coordinatescoordinates变量将保留该特定空格的字母数字组合,例如' a8'或者' a1'。但是,我在使用#assign_coordinates方法生成这些字母数字组合时遇到问题。

以下是我所拥有的:

Square Class

class Square
  attr_accessor :piece_on_square, :x, :y, :coordinates
  def initialize(piece_on_square=nil, x=nil, y=nil, coordinates=nil)
    @piece_on_square = piece_on_square
    @x = x
    @y = y
    @coordinates = coordinates
  end
end

董事会成员

class Board
  def initialize
    @square_array = Array.new(64)
    setup_new_board
    assign_coordinates
  end

  def setup_new_board
    @square_array.each_with_index do |n, index|
      square_array[index] = Square.new
    end
  end

  def assign_coordinates
    letters = ["a", "b", "c", "d", "e", "f", "g", "h"]
    numbers = [1, 2, 3, 4, 5, 6, 7, 8]
    @square_array.each do |i|
      letters.each do |x|
        numbers.each do |n|
          i.coordinates = "#{x}#{n}"
        end
      end
    end
  end

当我这样做时,coordinates所有被列为" h8"。例如,在查看IRB时,@square_array[0]返回:

=> #<Square:0x007fd74317a0a8 @piece_on_square=nil, @x=nil, @y=nil, @coordinates="h8">

我做错了什么?如何正确创建和命名这些Square对象?

2 个答案:

答案 0 :(得分:3)

对于每个方块,您依次(重新)分配从"a1""h8"的每个值,最后分配"h8"

要做到这一点,你可以这样做:

class Board
  Letters = ("a".."h").to_a
  Numbers = ("1".."8").to_a
  def initialize
    @square_array = Array.new(64){Square.new}
    assign_coordinates
  end
  def assign_coordinates
    Letters.product(Numbers).zip(@square_array){|a, e| e.coordinates = a.join}
  end
end

答案 1 :(得分:0)

你想做

@square_array[i].coordinates = "#{x}#{n}"