【发布时间】:2014-08-25 14:44:11
【问题描述】:
我正在努力在 OOP 方面做得更好,并想创建一个 Mastermind 游戏。 该程序由三个类组成,一个创建随机颜色代码的计算机类。存储玩家输入的玩家类,以及运行游戏的 Game 类。 我遇到的问题是当我需要将 Computer 类中的随机代码与玩家输入进行比较时。 代码如下:
class Game
def initialize
@theComputer = Computer.new
@player = Player.new
end
def play
print "\n\nThe Random code is:\n#{@theComputer.random_code}\n\n"
10.times do |i|
current_guess = @player.guess_code
standing = evaluate_guess(current_guess)
end
end #end play
def evaluate_guess(current_guess)
current_guess.each_with_index do |color, position|
print "#{match?(color, position)} "
end
puts ""
end
def almost_match?(color)
@theComputer.random_code.include?(color)
end
def match?(color, position)
color == @theComputer.random_code[position]
end
end
class Computer
COLORS = ["B", "G", "R", "O", "Y", "P"]
attr_reader :random_code
def initialize
@random_code = secret_code
end
def secret_code
sample_code = []
sample_code << COLORS.sample(4)
sample_code
end
end
class Player
def guess_code
puts "Guess the code! Choose 4 colors from B, G, R, O, Y, P"
guess = gets.chomp
guess.split(" ")
end
end
g = Game.new
g.play
我打印了随机码并输入了匹配值,但所有内容都返回为“false”。我不明白为什么。
【问题讨论】: