简体   繁体   English

将值分配给哈希内数组中的单个元素

[英]Assigning a Value to a Single Element in an Array Within a Hash

I am attempting to create a, "Connect Four," game to practice working with Ruby. 我正在尝试创建一个“四连环”游戏,以练习使用Ruby。

My issue lies with changing a single, "square," on the board. 我的问题在于在板上更改单个“正方形”。 My play_piece method changes the entire column above where I want the place to be played. 我的play_piece方法更改了我要播放该位置的上方的整个列。

Unabridged code snippet: 未删节的代码段:

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

and undesired result: 和不希望的结果:

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

After checking, only one of the if / elsif / else statements gets triggered. 检查后,只有一个if / elsif / else语句被触发。 I also attempted to assign values to lower rows and it leaves values below unchanged. 我还尝试将值分配给较低的行,并使下面的值保持不变。

For example: if I change the third row to be X , this changes the fourth, fifth and sixth rows to P . 例如:如果我将第三行更改为X ,这会将第四,第五和第六行更改为P

You use the same row seven times. 您使用同一row七次。 Object#dup comes to the rescue: 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

utilizing syntax idiomatic to Ruby: 利用Ruby惯用的语法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM