简体   繁体   中英

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.

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.

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. 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 .

You use the same row seven times. Object#dup comes to the rescue:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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