Class: Codeguessing::Console

Inherits:
Object
  • Object
show all
Defined in:
lib/codeguessing/console.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opt = {}) ⇒ Console

Returns a new instance of Console.



5
6
7
8
9
# File 'lib/codeguessing/console.rb', line 5

def initialize(opt = {})
  @path = File.join(File.dirname(__FILE__), 'scores.yml')
  @scores = load(@path)
  @game = Game.new(opt)
end

Instance Attribute Details

#gameObject (readonly)

Returns the value of attribute game.



3
4
5
# File 'lib/codeguessing/console.rb', line 3

def game
  @game
end

#pathObject (readonly)

Returns the value of attribute path.



3
4
5
# File 'lib/codeguessing/console.rb', line 3

def path
  @path
end

#scoresObject (readonly)

Returns the value of attribute scores.



3
4
5
# File 'lib/codeguessing/console.rb', line 3

def scores
  @scores
end

Instance Method Details

#confirm?(action = gets.chomp) ⇒ Boolean

Returns:

  • (Boolean)


52
53
54
55
# File 'lib/codeguessing/console.rb', line 52

def confirm?(action = gets.chomp)
  return true if action.downcase == 'y'
  false
end

#gamingObject



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/codeguessing/console.rb', line 38

def gaming
  action = gets.chomp
  if action == 'hint'
    puts @game.hint
    return go(false)
  end
  if @game.valid?(action)
    puts @game.guess(action)
  else
    puts 'Invalid data'
  end
  go(false)
end

#go(know = true) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/codeguessing/console.rb', line 11

def go(know = true)
  rules if know
  puts "Attempt(s): #{@game.attempts} | Hint(s): #{@game.hint_count}"
  case @game.state
    when 'true'
      win
    when 'false'
      loose
    else
      gaming
  end
end

#load(path) ⇒ Object



57
58
59
# File 'lib/codeguessing/console.rb', line 57

def load(path)
  YAML.load(File.open(path)) if File.exist?(path)
end

#rulesObject



24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/codeguessing/console.rb', line 24

def	rules
  puts "Do you know rules? (Y/N)"
  rules = [
    '-----------------Rules!----------------------',
    "You need guess secret code. This four-digit number with symbols from 1 to 6",
    "You have #{@game.attempts} attempt(s) and #{@game.hint_count} hint(s)",
    "If you want get hint write 'hint'",
    '---------------------------------------------'
  ]
  unless confirm?
    puts rules.join("\n")
  end
end

#save!(name = 'Anonim') ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/codeguessing/console.rb', line 61

def save!(name = 'Anonim')
  if @game.state != 'true'
    return puts 'You cant save game'
  end
  name.chomp!
  @scores << @game.cur_score(name)
  File.new(@path, 'w') unless File.exist?(@path)
  File.open(@path, "r+") do |f|
    f.write(@scores.to_yaml)
  end
  @scores
end