Class: Codebreaker::Game
- Inherits:
-
Object
- Object
- Codebreaker::Game
- Defined in:
- lib/edlvj_codebreaker.rb
Constant Summary collapse
- HINT =
1- ATTEMPS =
10- PROPER =
'+'- WRONG_POSITION =
'-'
Instance Attribute Summary collapse
-
#attempts ⇒ Object
Returns the value of attribute attempts.
Instance Method Summary collapse
- #get_hint ⇒ Object
-
#initialize ⇒ Game
constructor
A new instance of Game.
- #loose? ⇒ Boolean
- #match_guess(code) ⇒ Object
- #save_stat(username) ⇒ Object
- #stat ⇒ Object
- #win? ⇒ Boolean
Constructor Details
#initialize ⇒ Game
Returns a new instance of Game.
14 15 16 17 18 19 |
# File 'lib/edlvj_codebreaker.rb', line 14 def initialize @secret_code = Array.new(4) { rand(1..6) }.join @hint = HINT @attempts = ATTEMPS @win_status = false end |
Instance Attribute Details
#attempts ⇒ Object
Returns the value of attribute attempts.
6 7 8 |
# File 'lib/edlvj_codebreaker.rb', line 6 def attempts @attempts end |
Instance Method Details
#get_hint ⇒ Object
50 51 52 53 |
# File 'lib/edlvj_codebreaker.rb', line 50 def get_hint @hint -= 1 @hint >= 0 ? @secret_code[rand(4)] : "Not Available" end |
#loose? ⇒ Boolean
42 43 44 |
# File 'lib/edlvj_codebreaker.rb', line 42 def loose? @attempts == 0 end |
#match_guess(code) ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/edlvj_codebreaker.rb', line 21 def match_guess(code) return "Your code is not valid" unless code.match(/(^([1-6]{4})$)/) @win_status = true if @secret_code == code @attempts -= 1 secret = @secret_code.chars.map(&:to_i) res = [] code.chars.map(&:to_i).each_with_index do |number, index| if number == secret[index] secret[index] = nil res << PROPER elsif secret.include? number secret[secret.find_index(number)] = nil res << WRONG_POSITION end end res.join end |
#save_stat(username) ⇒ Object
55 56 57 58 59 |
# File 'lib/edlvj_codebreaker.rb', line 55 def save_stat( username ) File.open('./stat.yml','a+') do |f| f.write({user: username, attempts: @attempts, date: Time.now}.to_yaml) end end |
#stat ⇒ Object
61 62 63 64 65 |
# File 'lib/edlvj_codebreaker.rb', line 61 def stat records = [] records = Psych.load_stream(File.open('./stat.yml')) records.sort_by { |record| record[:attempts] } end |
#win? ⇒ Boolean
46 47 48 |
# File 'lib/edlvj_codebreaker.rb', line 46 def win? @win_status end |