Class: SvatokCodebreaker::Game

Inherits:
Object
  • Object
show all
Defined in:
lib/svatok_codebreaker/game.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(codebreaker_name = 'Test') ⇒ Game

Returns a new instance of Game.



7
8
9
10
11
12
13
# File 'lib/svatok_codebreaker/game.rb', line 7

def initialize(codebreaker_name = 'Test')
  @codebreaker_name = codebreaker_name
  @secret_code = Array.new(4) { rand(1..6) }.join
  @attempts = ATTEMPTS
  @hint = true
  @file_path = File.join(File.dirname(__FILE__), 'scores.txt')
end

Instance Attribute Details

#attemptsObject

Returns the value of attribute attempts.



5
6
7
# File 'lib/svatok_codebreaker/game.rb', line 5

def attempts
  @attempts
end

#codebreaker_nameObject

Returns the value of attribute codebreaker_name.



5
6
7
# File 'lib/svatok_codebreaker/game.rb', line 5

def codebreaker_name
  @codebreaker_name
end

#hintObject

Returns the value of attribute hint.



5
6
7
# File 'lib/svatok_codebreaker/game.rb', line 5

def hint
  @hint
end

#marking_guessObject

Returns the value of attribute marking_guess.



5
6
7
# File 'lib/svatok_codebreaker/game.rb', line 5

def marking_guess
  @marking_guess
end

Instance Method Details

#end_of_game?Boolean

Returns:

  • (Boolean)


28
29
30
# File 'lib/svatok_codebreaker/game.rb', line 28

def end_of_game?
  @marking_guess == '++++' || @attempts.zero?
end

#get_game_dataObject



43
44
45
46
47
48
49
50
51
52
# File 'lib/svatok_codebreaker/game.rb', line 43

def get_game_data
  {
    codebreaker_name: @codebreaker_name,
    secret_code: @secret_code,
    marking_guess: @marking_guess,
    attempts: @attempts,
    hint: @hint == true ? 'not used' : 'used',
    game_date: Time.now.strftime('%d/%m/%Y')
  }
end

#save_gameObject



37
38
39
40
41
# File 'lib/svatok_codebreaker/game.rb', line 37

def save_game
  score_file = File.open(@file_path, 'a')
  score_file.puts get_game_data.map { |k, v| "#{k}=#{v}" }.join(';')
  score_file.close
end

#show_hintObject



32
33
34
35
# File 'lib/svatok_codebreaker/game.rb', line 32

def show_hint
  @hint = false
  @secret_code.chars.sample
end

#submit_guess(guess) ⇒ Object



15
16
17
18
19
# File 'lib/svatok_codebreaker/game.rb', line 15

def submit_guess(guess)
  return if end_of_game?
  @attempts -= 1
  @marking_guess = Marker.new(@secret_code, guess).marking_guess
end

#valid_guess?(guess) ⇒ Boolean

Returns:

  • (Boolean)


21
22
23
24
25
26
# File 'lib/svatok_codebreaker/game.rb', line 21

def valid_guess?(guess)
  return false unless !!guess
  return false unless guess.length == 4
  return false unless /[1-6]+/=~guess
  true
end