为哈希中的数组中的单个元素赋值

时间:2016-03-10 16:27:22

标签: arrays ruby hash element

我正在尝试创建一个" Connect Four,"练习使用Ruby的游戏。

我的问题在于改变单个"方形,"在板上。我的play_piece方法会将整个列更改为我希望播放该地点的位置。

未删节的代码段:

class Connect_four

  def initialize
    row = Array.new(7, '- ')
    @board = {first: row, second: row, third: row,
              fourth: row, fifth: row, sixth: row}
  end

  def display
    puts @board[:sixth].join
    puts @board[:fifth].join
    puts @board[:fourth].join
    puts @board[:third].join
    puts @board[:second].join
    puts @board[:first].join
    puts "1 2 3 4 5 6 7"
  end

  def play_piece
    input = get_input
    if @board[:first][input] == '- '
      @board[:first][input] = 'P '
    elsif @board[:second][input] == '- '
      @board[:second][input] = 'P '
    elsif @board[:third][input] == '- '
      @board[:third][input] = 'P '
    elsif @board[:fourth][input] == '- '
      @board[:fourth][input] = 'P '
    elsif @board[:fifth][input] == '- '
      @board[:fifth][input] = 'P '
    elsif @board[:sixth][input] == '- '
      @board[:sixth][input] = 'P '
    end
  end

  def get_input
    begin
      puts "Enter the column # you wish to play in"
      input = gets.chomp
      puts "Invalid input!" unless input =~ /[1-7]/
    end while (!input =~ /[1-7]/)
    input = (input.to_i) - 1 #return array adjusted number
  end

end

game = Connect_four.new
game.display
game.play_piece
game.display

gets

和不良结果:

- - P - - - -
- - P - - - -
- - P - - - -
- - P - - - -
- - P - - - -
- - P - - - -
1 2 3 4 5 6 7

检查后,只会触发if / elsif / else个语句中的一个。我还尝试将值分配给较低的行,并使值保持不变。

例如:如果我将第三行更改为X,则会将第四行,第五行和第六行更改为P

1 个答案:

答案 0 :(得分:3)

您使用相同的row七次。 Object#dup来救援:

def initialize
  row = Array.new(7, '- ')
  @board = {first: row.dup, second: row.dup, third: row.dup,
            fourth: row.dup, fifth: row.dup, sixth: row.dup}
end

利用Ruby的语法惯用语:

def initialize
  @board = %i|first second third fourth fifth sixth|.zip(
    6.times.map { ['- '] * 7 }
  ).to_h
end