Skip to content

Instantly share code, notes, and snippets.

@TrevorS
Forked from mattantonelli/mastermind.rb
Created October 26, 2015 23:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TrevorS/a7892e044337bd6c8de8 to your computer and use it in GitHub Desktop.
Save TrevorS/a7892e044337bd6c8de8 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# encoding: utf-8
random = Random.new
code = ''
4.times { code << random.rand(1..6).to_s }
puts %q(
Can you guess the code?
You have 10 guesses.
The code is 4 digits between 1 and 6.
-: No match x: Wrong spot o: Match
)
10.times do
print 'Enter your guess: '
guess = gets.chomp
while !guess.match(/^[1-6]{4}$/)
puts "Your guess should be 4 digits between 1 and 6. Try again."
guess = gets.chomp
end
response = ''
guess.split('').each_with_index do |c, i|
if c == code[i]
response << 'o'
elsif code.match(c)
response << 'x'
else
response << '-'
end
end
puts response
if response == 'oooo'
puts "You win!"
exit
end
end
puts "You lose!"
puts "The code was #{code}."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment