ここの数当てゲーム2を解いてみました
#コード
class Answer
def initialize(digits)
num = %w[1 2 3 4 5 6 7 8 9]
first_num = num.delete(num.sample)
remaining_num = num.push("0").sample(digits - 1)
@answer = [first_num, *remaining_num]
@count_hit_and_blow = Hash.new(0)
@digits = digits
end
def judge_hit(entry)
entry_judeged_hit = entry.dup
entry.zip(@answer) do |n|
if n.uniq!
@count_hit_and_blow[:hit] += 1
entry_judeged_hit.delete(n[0])
end
end
entry_judeged_hit
end
def judge_blow(entry_judeged_hit)
blow_count = entry_judeged_hit.intersection(@answer).size
entry_has_blow = blow_count != 0
@count_hit_and_blow[:blow] = blow_count if entry_has_blow
end
def judge_game
@count_hit_and_blow.each { |k, v| print "#{v}#{k} " }
print "\n"
if @count_hit_and_blow[:hit] == @digits
sleep 0.5
puts "game clear", "congratulations!!!!!"
exit
end
@count_hit_and_blow.clear
end
end
def input_digits
loop do
print "答えの桁数を入力してください: "
digits = gets
unless digits.match?(/^[0-9]+$/) && digits.to_i <= 10
puts "不正な値であるか""別の値を入力してください\n\n"
next
end
break digits.to_i
end
end
def input_entry(digits)
loop do
print "回答を入力してください: "
entry = gets.chomp
exit if entry.empty?
entry_is_suitable_number = entry.match?(/^[0-9]+$/) && entry.size == digits
entry_is_uniqe = (ary_entry = entry.chars) && !ary_entry.uniq!
unless entry_is_suitable_number && entry_is_uniqe
puts "不正なであるか重複した数字がある値です", "別の値を入力して下さい\n\n"
next
end
break ary_entry
end
end
# --------------実行部分--------------
puts "数当てゲーム、Hit&Blowを始めます(空行を入力すると終了します)\n\n"
sleep 1
digits = input_digits
answer = Answer.new(digits)
puts "\nゲームスタート!\n\n"
loop do
entry = input_entry(digits)
entry_judeged_hit = answer.judge_hit(entry)
answer.judge_blow(entry_judeged_hit)
answer.judge_game
end
~~~
#完走した感想
難しかった(小並感)
~~~Ruby
num = %w[1 2 3 4 5 6 7 8 9]
first_num = num.delete(num.sample)
remaining_num = num.push("0").sample(digits - 1)
@answer = [first_num, *remaining_num]
~~~
簡単にググってみた所、答えの生成にこれよりスリムなコードが無かったので嬉しかった