[英]Assigning a Value to a Single Element in an Array Within a Hash
我正在嘗試創建一個“四連環”游戲,以練習使用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
您使用同一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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.