【问题标题】:Troubles with Mastermind gameMastermind游戏的问题
【发布时间】: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”。我不明白为什么。

【问题讨论】:

    标签: ruby oop


    【解决方案1】:

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

    def secret_code
      COLORS.sample(4)
    end
    

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

    [[ random values from COLORS constant ]]
    

    但您希望匹配的只是简单的数组。

    【讨论】:

    • 谢谢你!几个小时以来一直在努力解决这个问题。不敢相信它是如此简单..
    猜你喜欢
    • 2014-12-14
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    • 2013-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多