与Mastermind游戏的麻烦

时间:2014-08-25 14:44:11

标签: ruby oop

我试图在OOP上变得更好并且想要创造一个Mastermind游戏。 该程序由三个类组成,一个计算机类,其中创建了一个随机的颜色代码。存储玩家输入的玩家类,以及运行游戏的游戏类。 我遇到的问题是当我需要将计算机类中的随机代码与播放器输入进行比较时。 这是代码:

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

我打印出随机代码并输入匹配的值,但所有内容都返回为&#34; false&#34;。我不明白为什么。

1 个答案:

答案 0 :(得分:1)

您必须将您的secret_code方法更改为:

def secret_code
  COLORS.sample(4)
end

在您的情况下,密码的输出是

[[ random values from COLORS constant ]]

但你期望匹配的只是简单的数组。

相关问题