Skip to content

Instantly share code, notes, and snippets.

@shim0mura
Created May 11, 2012 03:07
Show Gist options
  • Save shim0mura/2657255 to your computer and use it in GitHub Desktop.
Save shim0mura/2657255 to your computer and use it in GitHub Desktop.
rubyでhit&blowゲーム
#!/usr/bin/env ruby
class Hit
def initialize
loop do
generate_answer
valid_answer? && break
end
puts "game start\n"
end
attr_accessor :answer
def valid_answer?
(@answer.uniq.size != 4 || @answer[0] === 0) ? false : true
end
def generate_answer
@answer = [*"0".."9"].sample(4)
end
def valid_input? input
return true if (1000..9999).include? input.to_i
puts "invalid number."
false
end
def check num
result = check_hit_blow num
if result[0] == 4
str = "correct!"
ret = true
else
str = "hit:#{result[0]}, blow:#{result[1]}"
ret = false
end
puts str
return ret
end
def check_hit_blow input
@hit = 0
@blow = 0
input_arr = input.to_s.scan(/\d/)
input_arr.each_with_index do |num, i|
if @answer[i] == num
@hit += 1
elsif @answer.index num
@blow += 1
end
end
return @hit, @blow
end
end
hit = Hit.new
begin
while num = gets
next unless hit.valid_input? num
break if hit.check num.to_i
end
rescue => ex
puts ex.message
puts "retry?"
retry if gets == "y"
end
puts "break"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment