[英]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.