Created
July 20, 2018 20:16
-
-
Save tdeo/6b8f509eb657bdf0a76675e4b4aa71dc to your computer and use it in GitHub Desktop.
A command-line mastermind game
This file contains hidden or 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
class Mastermind | |
COLOURS = 'A'.upto('Z').to_a | |
def initialize(colour_count = 6, size = 4) | |
fail "Size must be <= #{COLOURS.size}" unless size <= COLOURS.size | |
@size = size | |
@colours = COLOURS.first(colour_count) | |
@code = size.times.map { @colours.sample } | |
@moves = 0 | |
puts "Guess the code, size #{@size}, letters are (#{@colours.join(', ')})" | |
end | |
def check(input) | |
chars = input.chars.select { |c| @colours.include?(c) } | |
unless chars.size == @size | |
puts "Input must be #{@size} letters in (#{@colours.join(', ')})" | |
return | |
end | |
@moves += 1 | |
rest_code = [] | |
rest_input = [] | |
exact = 0 | |
input.chars.each_with_index do |c, i| | |
if c == @code[i] | |
exact += 1 | |
else | |
rest_code << @code[i] | |
rest_input << c | |
end | |
end | |
if exact == @size | |
puts "\tCongratz, you beat the game in #{@moves} tries!" | |
exit 0 | |
end | |
misplaced = (rest_code & rest_input).size | |
puts "\t#{exact} in the right place, #{misplaced} in the wrong place\n" | |
end | |
end | |
size, colours = ARGV[0], ARGV[1] | |
if ARGV.size != 2 | |
puts <<~HELP | |
Usage: ruby mastermind.rb <size> <alphabet_size> | |
size: the length of the code you want to guess | |
alphabet_size: number of letters in your alphabet (max #{Mastermind::COLOURS.size}) | |
HELP | |
exit 0 | |
end | |
m = Mastermind.new(colours.to_i, size.to_i) | |
while true | |
m.check($stdin.gets.strip) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment