令人困惑的控制流程(Ruby)

时间:2015-04-28 21:49:34

标签: ruby control-flow

我试图在Ruby中创建一个游戏,包括按照certian顺序选择数字,并在有限次尝试中获得正确的序列,等等,等等,等等。我的问题是,无论我猜测的是什么数字,它都不会添加到@correct_r变量,如果它在正确的位置,也不会显示。

我差不多知道我在那里错过了if / else声明,但不确定在哪里。任何帮助表示赞赏。

代码

#by Touka, ©2015
actions = (0..9).to_a
@sequence = []
4.times do |key|
    key = actions.sample
    @sequence << key
end
@fails_left = 10
@correct_a = 0
@correct_r = 0
@a = " "
@b = " "
@c = " "
@d = " "
def sel
    system "cls"
    puts """
    __________________________________
   /   ___     ___     ___     ___    \\
   |  |   |   |   |   |   |   |   |   |
   |  | #{@a} |   | #{@b} |   | #{@c} |   | #{@d} |   |
   |  |___|   |___|   |___|   |___|   |
   \\__________________________________/

Tries left:                      #{@fails_left}
Correct numbers (in wrong spot): #{@correct_r}

Enter guess (x x x x):"""
    guess = gets.chomp
    guess = guess.split(" ")
    case guess[0]
    when @sequence[0]
        @correct_a += 1
        @a = "#"
    when @sequence[1]
        @correct_r += 1
    when @sequence[2]
        @correct_r += 1
    when @sequence[3]
        @correct_r += 1
    end
    case guess[1]
    when @sequence[0]
        @correct_r += 1
    when @sequence[1]
        @correct_a += 1
        @b = "#"
    when @sequence[2]
        @correct_r += 1
    when @sequence[3]
        @correct_r += 1
    end
    case guess[2]
    when @sequence[0]
        @correct_r += 1
    when @sequence[1]
        @correct_r += 1
    when @sequence[2]
        @correct_a += 1
        @c = "#"
    when @sequence[3]
        @correct_r += 1
    end
    case guess[3]
    when @sequence[0]
        @correct_r += 1
    when @sequence[1]
        @correct_r += 1
    when @sequence[2]
        @correct_r += 1
    when @sequence[3]
        @correct_a += 1
        @d = "#"
    end
    ct = @correct_r + @correct_a
    if ct == 0
        @fails_left -= 1
    else
        hi = " "
    end
    sel
end
sel

1 个答案:

答案 0 :(得分:1)

您的问题在于不同类型的序列和猜测变量。 Sequence是整数数组,guess是字符串数组。您需要将它们转换为相同的类型。

guess = guess.map(&:to_i)