Sha256: 381d9bfc3ee855ca4cc4348b0b5191774fc08bc73351ae603d9bba9a20448d1d

Contents?: true

Size: 1.85 KB

Versions: 2

Compression:

Stored size: 1.85 KB

Contents

# frozen_string_literal: true
module Codebreaker
  class Game
    attr_reader :attempts, :hints, :cb_numbers, :level, :cb_numbers, :name, :cb_numbers_copy
    include Storage

    WIN = :win
    LOSE = :lose
    LEVELS = { easy: 'easy', medium: 'medium', hard: 'hard' }.freeze
    COMPLEXITIES = { easy: { hints: 2, attempts: 15, level: LEVELS[:easy] },
                     medium: { hints: 1, attempts: 10, level: LEVELS[:medium] },
                     hard: { hints: 1, attempts: 5, level: LEVELS[:hard] } }.freeze

    def initialize(name, complexity)
      @name = name
      @level = complexity.to_sym
      generate_hints_attempts(@level)
      @cb_numbers = Core.new.generate_secret_code
      @cb_numbers_copy = @cb_numbers.clone
    end

    def generate_hints_attempts(level)
      level_hash = take_level_hash
      @hints = level_hash[:hints]
      @attempts = level_hash[:attempts]
    end

    def guess(user_guess)
      return LOSE if lose?

      @attempts -= 1
      user_guess_array = user_guess.split('').map(&:to_i)
      return WIN if win? user_guess_array

      Core.new.check(@cb_numbers, user_guess_array)
    end

    def hint
      return nil if @hints.zero?

      @hints -= 1
      @cb_numbers_copy.shuffle.pop
    end

    def calculate_hints
      take_level_hash[:hints] - @hints
    end

    def calculate_attempts
      take_level_hash[:attempts] - @attempts
    end


    def take_level_hash
      COMPLEXITIES[@level]
    end
    
    private

    def win?(user_guess_array)
      save_result if user_guess_array == @cb_numbers
    end

    def lose?
      @attempts.zero?
    end

    def save_result
      data = restore_storage
      data << { name: @name, attempts: calculate_attempts, hints: calculate_hints, level: @level, date: take_date }
      save(data)
    end

    def take_date
      Time.now.strftime("%d/%m/%Y %H:%M")
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
codebreaker_kolyanjy-0.1.7 lib/entities/game.rb
codebreaker_kolyanjy-0.1.6 lib/entities/game.rb