fork download
  1. class Baseball
  2. def initialize(count=3)
  3. @count = count
  4. setup
  5. end
  6.  
  7. def setup
  8. random = (1..9).sort_by { rand }
  9. @computer = random[0...@count]
  10. end
  11.  
  12. def get_score(u)
  13. s = b = 0
  14.  
  15. (0...@count).each do |i|
  16. (0...@count).each do |j|
  17. (i == j) ? s += 1 : b += 1 if @computer[i] == u[j]
  18. end
  19. end
  20.  
  21. return s, b
  22. end
  23.  
  24. def play
  25. count = 0
  26. begin
  27. print "user #{@count} numbers: "
  28. user = gets.delete(" ").split("").map(&:to_i)
  29.  
  30. if user[0] == 0
  31. print "Computer: "
  32. @computer.each { |x| print x, " " }
  33. puts
  34. break
  35. end
  36.  
  37. s, b = get_score(user[0...@count])
  38. count += 1
  39.  
  40. puts "(#{count}) Strike: #{s}, Ball: #{b}, Out: #{@count-s-b}"
  41. end until s == 3
  42.  
  43. puts "You played #{count} times."
  44. end
  45. end
  46.  
  47. b = Baseball.new
  48. b.play
  49.  
  50. b = Baseball.new(5)
  51. b.play
Success #stdin #stdout 0s 4760KB
stdin
1 2 3
456
78 9
0
12 3 4 5
5 6 7 8 9
0
stdout
user 3 numbers: (1) Strike: 0, Ball: 1, Out: 2
user 3 numbers: (2) Strike: 0, Ball: 0, Out: 3
user 3 numbers: (3) Strike: 0, Ball: 2, Out: 1
user 3 numbers: Computer: 9 3 7 
You played 3 times.
user 5 numbers: (1) Strike: 1, Ball: 1, Out: 3
user 5 numbers: (2) Strike: 2, Ball: 1, Out: 2
user 5 numbers: Computer: 1 8 7 3 9 
You played 2 times.