Created
March 3, 2015 16:07
-
-
Save JoshCheek/adbdf5140babeb851467 to your computer and use it in GitHub Desktop.
How I would start mastermind
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'minitest/autorun' | |
require 'minitest/spec' | |
require 'minitest/pride' | |
require 'stringio' | |
# I *might* wind up with classes like this | |
class RandomInputGenerator | |
def call | |
4.times.map { ['R', 'G', 'B', 'Y'].sample }.join | |
end | |
end | |
class PredeterminedInputGenerator | |
def initialize(input) | |
@input = input | |
end | |
def call | |
@input | |
end | |
end | |
class Cli | |
class Input | |
def initialize(input) | |
@input = (input || 'q').chomp.downcase | |
end | |
def instructions? | |
@input == 'i' | |
end | |
def quit? | |
@input == 'q' || @input == 'quit' | |
end | |
end | |
# this *might* take an input_generator, | |
# which would either be an instance of RandomInputGenerator or PredeterminedInputGenerator | |
def initialize(instream, outstream) | |
self.instream, self.outstream = instream, outstream | |
end | |
def call | |
outstream.puts "Welcome to MASTERMIND" | |
outstream.puts "Would you like to (p)lay, read the (i)nstructions, or (q)uit?" | |
loop do | |
outstream.print "> " | |
input = Input.new(instream.gets) | |
if input.instructions? | |
outstream.puts 'Instructions: FIXME' | |
elsif input.quit? | |
outstream.puts 'Goodbye!' | |
break | |
end | |
end | |
end | |
private | |
attr_accessor :instream, :outstream | |
end | |
class MastermindTest < Minitest::Spec | |
def input_for(input_string) | |
StringIO.new(input_string) | |
end | |
def output_stream | |
@output_stream ||= StringIO.new | |
end | |
it 'prints instructions when I say "i", and quits when I say "q"' do | |
mastermind = Cli.new input_for("i\nq\n"), output_stream | |
mastermind.call | |
assert_match /welcome/i, output_stream.string | |
assert_match /instructions:/i, output_stream.string | |
assert_match /goodbye/i, output_stream.string | |
end | |
it 'treats inputs as case insensitive' do | |
assert Cli::Input.new("q").quit? | |
assert Cli::Input.new("Q").quit? | |
end | |
it 'treats no-input as a quit' do | |
assert Cli::Input.new(nil).quit? | |
end | |
it 'ignores newlines after the input' do | |
assert Cli::Input.new("quit").quit? | |
assert Cli::Input.new("quit\n").quit? | |
end | |
it 'treats "q" and "quit" as quit' do | |
refute Cli::Input.new("i").quit? | |
assert Cli::Input.new("q").quit? | |
assert Cli::Input.new("quit").quit? | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment