mastermind; basic logic, color highlighting, etc

This commit is contained in:
Mikayla Dobson
2023-05-29 22:37:51 -05:00
parent fdb5b211b3
commit a347e5a776
10 changed files with 177 additions and 54 deletions

View File

@@ -1,11 +1,34 @@
require_relative "../common/BoardBase.rb"
class Board < BoardBase
def initialize(turn = 1)
super(turn)
class Board
attr_accessor :turn
attr_reader :guesses, :keys
include BoardBase
def initialize
@turn = 0
@guesses = Array.new(12)
@keys = Array.new(12)
# generate a random solution code from values between 1 and 6
solution_code = Array.new(4).map { rand(1..6) }
@solution = CodeSet.new(solution_code)
end
def to_s
print "wew"
end
def put_code(code)
@guesses[turn] = code
status = nil
if (code == @solution)
status = "win"
end
status
end
end

View File

@@ -0,0 +1,35 @@
require_relative "../common/String.rb"
class CodeSet
attr_accessor :code
def initialize(array_code = nil)
if (array_code)
if (array_code.any? { |code| code < 0 or code > 6 })
raise ArgumentError, "Code must be between 1 and 6"
end
@code = array_code
else
@code = Array.new(4)
end
end
def to_s
output = ""
for cell in @code
colorcode = cell + 31
output += "\e[#{colorcode}m#{cell.to_s}\e[0m\n"
end
output
end
def put_codes(array_code)
@code << array_code
end
end
thing = CodeSet.new([1,2,3,4])
print thing.to_s

View File

@@ -1,16 +1,39 @@
require_relative "../common/GameBase.rb"
require_relative "../common/Player.rb"
require_relative "../common/Board.rb"
require_relative "KeySet.rb"
require_relative "CodeSet.rb"
class Game
include GameBase
class Game < GameBase
def initialize
puts "Welcome to Mastermind!"
puts "Player 1, what is your name?"
player_one_name = gets.chomp
super("Mastermind")
end
puts "Player 2, what is your name?"
player_two_name = gets.chomp
# inherits "play"
def turn
# clear the terminal on each turn
puts "\e[H\e[2J"
print self.to_s
puts "Player #{@turn % 2 == 0 ? @playerTwo.name : @playerOne.name}, please enter a guess."
player_input = gets.chomp
unless player_input.is_a?(String) and player_input.length == 4 and player_input.split("").all? { |code| code.to_i.between?(1, 6) }
@statusMessage = "Invalid input. Expected a 4-digit code between 1 and 6."
self.turn
end
@playerOne = Player.new(player_one_name)
@playerTwo = Player.new(player_two_name)
@statusMessage = ""
# convert the player's input into a CodeSet object
player_code = CodeSet.new(player_input.split("").map { |code| code.to_i })
# pass object to the board, which will also check it against the solution
result = @board.put_code(player_code)
@board.turn(@turn)
end
end

View File

@@ -0,0 +1,12 @@
class KeySet
def initialize(array_keys = nil)
@key = Array.new(4)
if (array_keys)
@key << array_keys
end
end
def put_keys(array_keys)
@key << array_keys
end
end

View File

@@ -0,0 +1,4 @@
require_relative "Game.rb"
game = Game.new
game.play