Sha256: 33429161df7ee92ec97bccf7b2a4a89036a8757ba5647283a5c2a6fa3fa2fa51

Contents?: true

Size: 1.05 KB

Versions: 1

Compression:

Stored size: 1.05 KB

Contents

module Mastermind
  class Game
    attr_reader :turns, :codemaker, :codebreaker, :max_attempts

    def initialize(secret: nil, codemaker: nil, codebreaker: nil)
      @secret = secret || Code.random
      @turns = []
      @codemaker = codemaker || Player.new(name: "AbstractCodemaker")
      @codebreaker = codebreaker || Player.new(name: "AbstractCodebreaker")
      @max_attempts = 12
    end

    def attempts
      turns.length
    end

    def secret_length
      @secret.length
    end

    def guess(code)
      @turns << Turn.new(
        guess: code, number: attempts + 1,
        exact: @secret.exact_matches_with(code),
        partial: @secret.partial_matches_with(code)
      )
    end

    def over?
      max_attempts_reached? || code_guessed?
    end

    def winner
      return codebreaker if code_guessed?
      return codemaker if max_attempts_reached?
    end


    private

    def max_attempts_reached?
      attempts >= max_attempts
    end

    def code_guessed?
      turns.first(max_attempts).any? { |turn| turn.guess == @secret }
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mastermind-game-0.0.2 lib/mastermind/game.rb