Skip to content

Instantly share code, notes, and snippets.

@mindplace
Created January 18, 2016 20:55
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 mindplace/64931b7a58668ca239e0 to your computer and use it in GitHub Desktop.
Save mindplace/64931b7a58668ca239e0 to your computer and use it in GitHub Desktop.
Mastermind
class Code
attr_reader :pegs
def initialize
@pegs = random
end
def random
colors = ["R", "G", "B", "Y", "O", "P"]
[colors[rand(6)], colors[rand(6)], colors[rand(6)], colors[rand(6)]].join
end
def parse(input)
input = input.split("")
[exact_match(input), near_match(input)]
end
def exact_match(input)
exact_count = 0
pegs_array = pegs.dup.split("")
pegs_array.each_index do |i|
exact_count += 1 if pegs[i] == input[i]
end
exact_count
end
def near_match(input)
pegs_array = pegs.dup.split("")
near_count = 0
pegs.split("").each_index do |i|
pegs_array[i] = nil if pegs[i] == input[i]
end
input.each_index do |i|
if pegs_array.include?(input[i])
near_count += 1
item = pegs_array.index(input[i])
pegs_array[item] = nil
end
end
near_count
end
end
class Game
attr_reader :new_code, :secret_code, :last_input
def rules
puts "
There are six different peg colors:
* Red
* Green
* Blue
* Yellow
* Orange
* Purple
1. The computer selects a random code of four pegs.
2. The player gets ten turns to guess the code.
2. The player inputs their guess like so:
\"RGBY\" for red-green-blue-yellow.
3. The computer tells the player how many exact matches
(right color in right spot) and near matches (right
color, wrong spot) the player guessed.
4. The game ends when the player guesses the code, or
is out of turns.\n\n"
end
def initialize
@turns = 10
@new_code = Code.new
@secret_code = @new_code.pegs
@last_input = ""
end
def turns
@turns
end
def round
puts "Welcome to Mastermind!"
puts "Would you like to see the rules? (yes or no)"
answer = gets.chomp
rules if answer == "yes"
puts "Press enter to play:"
gets
puts "Computer has thought of a sequence."
while last_input != secret_code && turns > 0
puts "Last chance!" if turns == 1
puts "Make a guess:"
@last_input = gets.chomp.upcase
result = new_code.parse(last_input)
puts "Exact matches: #{result[0]}, Near matches: #{result[1]}"
@turns -= 1
end
if turns == 0 && last_input != secret_code
puts "You lost. The sequence was #{secret_code}."
else
puts "You won with #{turns} turns to go!"
end
end
end
if __FILE__ == $PROGRAM_NAME
game = Game.new
game.round
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment