lib/codeguessing/game.rb in codeguessing-0.4.3 vs lib/codeguessing/game.rb in codeguessing-0.4.4
- old
+ new
@@ -2,10 +2,11 @@
class Game
attr_accessor :attempts, :hint_count, :state, :answer, :secret_code
MAX_HINT = 2
MAX_ATTEMPTS = 5
+ MAX_SIZE = 4
def initialize(opt = {})
@secret_code = opt[:secret_code] || random
@attempts = opt[:attempts] || MAX_ATTEMPTS
@hint_count = opt[:hint_count] || MAX_HINT
@@ -13,10 +14,11 @@
@answer = opt[:answer] || ''
end
def guess(code)
loose unless check?(use_attempt)
+ return false unless valid?(code)
hash = {}
res = ''
remaine_chars = code
right_chars = []
secret_code.each_char.with_index do |char, i|
@@ -29,17 +31,17 @@
when remaine_chars.include?(char)
hash[char] = '-'
end
end
res += hash.values.join('')
- win if res == '++++'
+ win if res == '+' * MAX_SIZE
@answer = res
end
def hint
res = ''
- need_index = rand(0...4)
+ need_index = rand(0...MAX_SIZE)
secret_code.each_char.with_index do |char, index|
if index == need_index
res += char
else
res += '*'
@@ -67,11 +69,11 @@
hash.delete(:state)
hash
end
def valid?(code)
- return true if code =~ /^[1-6]{4}$/s
+ return true if code =~ /^[1-6]{#{MAX_SIZE}}$/s
false
end
def check?(varible)
return false if varible == 0
@@ -94,10 +96,10 @@
@state = 'false'
end
def random
code = ''
- 4.times { code += rand(1..6).to_s }
+ MAX_SIZE.times { code += rand(1..6).to_s }
code
end
end
end