Ruby naming Square objects for chess grid

scobo

I am writing a Chess program in Ruby. I'm attempting to create a Board of 64 Square objects, which will keep track of piece_on_square, x position, y position, and coordinates. The coordinates variable will hold the letter-number combo of that particular space, such as 'a8' or 'a1'. However, I am having trouble generating these letter-number combinations, using my #assign_coordinates method.

Here's what I have:

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

Board Class

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

When I do this, all of the coordinates are listed as "h8". For example, when looking in IRB, @square_array[0] returns:

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

What am I doing wrong? How can I properly create and name each of these Square objects?

sawa

For each square, you are (re-)assigning each values from "a1" to "h8" in turn, ending up assigning "h8".

To do it correctly, you can do like this:

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related