class MastermindRuby::Game

Attributes

try_count[R]

Public Class Methods

new(ui, solution: nil) click to toggle source
# File lib/mastermind_ruby/game.rb, line 5
def initialize(ui, solution: nil)
  @solution_code = solution
  @ui = ui
  @try_count = 1
  @started = false
end

Public Instance Methods

start() click to toggle source

Method to start a game Requests by calling :read_playername on the UI for the playername Requests by calling :read_code_length on the UI for the code_length Requests by calling :display_welcome_message on the UI for displaying the welcome message

# File lib/mastermind_ruby/game.rb, line 16
def start
  @started = true
  @playername = @ui.read_playername
  @code_length = @ui.read_code_length
  @solution_code ||= Code.random(@code_length)
  @ui.display_welcome_message(@playername)
  run
end

Private Instance Methods

guess_valid_length?(guess) click to toggle source

Checks if the guess has a valid length

# File lib/mastermind_ruby/game.rb, line 28
def guess_valid_length?(guess)
  guess === /\A.{#{@code_length}}\z/
end
result_solution?(result) click to toggle source

Returns if the result passed is the solution

# File lib/mastermind_ruby/game.rb, line 33
def result_solution?(result)
  result == Code.solution(@code_length)
end
run() click to toggle source

Method to run the game (prevent from dying if the solution was not found yet) Requests by calling :read_next_guess for a new guess on the UI Shows an assessment on the UI by calling :display_assessment

# File lib/mastermind_ruby/game.rb, line 40
def run
  while running?
    guess = @ui.read_next_guess(@try_count)
    if guess_valid_length?(guess) && guess.valid?
      result = guess.assessment_for_solution(@solution_code)
      if result_solution?(result)
        stop
      else
        @try_count += 1
        @ui.display_assessment(result)
      end
    else
      @ui.display_invalid_code(guess)
    end
  end
end
running?() click to toggle source

Method to check if the game is running

# File lib/mastermind_ruby/game.rb, line 65
def running?
  @started
end
stop() click to toggle source

Method to stop the game On the ui display_end_game is called

# File lib/mastermind_ruby/game.rb, line 59
def stop
  @started = false
  @ui.display_end_game(@try_count)
end