class Codeguessing::Game

Constants

MAX_ATTEMPTS
MAX_HINT
MAX_SIZE

Attributes

answer[RW]
attempts[RW]
hint_count[RW]
secret_code[RW]
state[RW]

Public Class Methods

new() click to toggle source
# File lib/codeguessing/game.rb, line 9
def initialize
  @secret_code = random
  @attempts = MAX_ATTEMPTS
  @hint_count = MAX_HINT
  @state = ''
  @answer = ''
end

Public Instance Methods

cur_game() click to toggle source
# File lib/codeguessing/game.rb, line 73
def cur_game
  attributes = instance_variables.map do |var|
    [var[1..-1].to_sym, instance_variable_get(var)]
  end
  attributes.to_h
end
cur_score(name = 'Anonim') click to toggle source
# File lib/codeguessing/game.rb, line 64
def cur_score(name = 'Anonim')
  scores = cur_game
  scores[:name] = name
  scores[:attempts] = MAX_SIZE - attempts
  scores[:hint_count] = MAX_HINT - hint_count
  scores[:date] = Time.now.to_i
  scores
end
get_mark(code) click to toggle source
# File lib/codeguessing/game.rb, line 26
def get_mark(code)
  raise 'Invalid data' unless valid?(code)
  mark = ''
  secret_codes = secret_code.chars
  codes = code.chars

  secret_codes.each_with_index do |char, index|
    next unless char == codes[index]
    secret_codes[index] = nil
    codes[index] = nil
    mark += '+'
  end

  secret_codes.compact.each_with_index do |char, index|
    next unless code_index = codes.index(char)
    codes[code_index] = nil
    mark += '-'
  end

  mark
end
guess(code) click to toggle source
# File lib/codeguessing/game.rb, line 17
def guess(code)
  @state = 'loose' unless natural?(use_attempt)
  if code == secret_code
    @state = 'win'
    return @answer = '+' * MAX_SIZE
  end
  @answer = get_mark(code)
end
hint() click to toggle source
# File lib/codeguessing/game.rb, line 48
def hint
  return '' unless natural?(hint_count)
  use_hint
  hint = '*' * MAX_SIZE
  index = rand(0...MAX_SIZE)
  hint[index] = secret_code[index]
  hint
end
valid?(code) click to toggle source
# File lib/codeguessing/game.rb, line 80
def valid?(code)
  return true if code =~ /^[1-6]{#{MAX_SIZE}}$/s
  false
end
win?() click to toggle source
# File lib/codeguessing/game.rb, line 57
def win?
  case @state
  when 'win' then true
  when 'loose' then false
  end
end

Private Instance Methods

natural?(number) click to toggle source
# File lib/codeguessing/game.rb, line 87
def natural?(number)
  number <= 0 ? false : true
end
random() click to toggle source
# File lib/codeguessing/game.rb, line 91
def random
  Array.new(MAX_SIZE) { rand(1..6) }.join
end
use_attempt() click to toggle source
# File lib/codeguessing/game.rb, line 95
def use_attempt
  @attempts -= 1
end
use_hint() click to toggle source
# File lib/codeguessing/game.rb, line 99
def use_hint
  @hint_count -= 1
end