Sha256: 0ca4f4abef859302c45d5a9defd7c8ae06006b58bb98d021adee2f71328e7b84

Contents?: true

Size: 1.49 KB

Versions: 1

Compression:

Stored size: 1.49 KB

Contents

# frozen_string_literal: true

module Codebreaker
  class Statistic
    include DataHandler

    DATE_FORMAT = '%Y.%m.%d - %T'

    attr_reader :headers, :items

    def initialize(db = __dir__ + '/storage.yml')
      @db = db
      @headers = %w[ratign name difficulty attempts_total attempts_used hints_total hints_used]
      @items = load || []
    end

    def statistic
      sort
      @items.each_with_index.map do |item, index|
        [
          index.next, item[:name], item[:difficulty], item[:attempts_total],
          item[:attempts_used], item[:hints_total], item[:hints_used]
        ]
      end
    end

    def add_item(game, username, date_format: DATE_FORMAT)
      @items << { name: username,
                  difficulty: game.current_difficulty[:name],
                  difficulty_id: game.current_difficulty[:id],
                  attempts_total: game.current_difficulty[:attempts],
                  attempts_used: game.attempts_counter,
                  hints_total: game.current_difficulty[:hints],
                  hints_used: hints_used(game),
                  time: Time.now.strftime(date_format) }
      save
    end

    private

    def hints_used(game)
      game.current_difficulty[:hints] - game.hinted_numbers.size
    end

    def load
      DataHandler.load(@db)
    end

    def save
      DataHandler.save(@db, @items)
    end

    def sort
      @items.sort_by! do |item|
        [-item[:difficulty_id], item[:attempts_used], item[:hints_used]]
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
codebreaker_gapdn-0.1.5 lib/database/statistic.rb