【问题标题】:RUBY Exit minesweeper game loopRUBY 退出扫雷游戏循环
【发布时间】:2021-02-28 16:15:43
【问题描述】:

我不知道如何退出游戏循环。我正在努力创建一个lose? 函数,我尝试像lose?(x) 那样做,当x==1 时返回true,但没有让它退出run 方法。这是我的 Game 类代码。

class Minesweeper

    attr_accessor :board

    def initialize
        @board = Board.new
    end

    def run
        puts "Welcome to minesweeper!"
        x = nil
        play_turn until win? || lose?(x)
    end

    def play_turn
            board.render
            pos, command = get_input
            debugger
            if !explode?(pos, command)
                board.set_input(pos,command)
            else
                puts "You lose!"
                lose?(1)
            end
    end

    def explode?(pos, cmd)
        board.grid[pos[0]][pos[1]].bomb && cmd == "reveal"
    end

    def get_input
        pos = nil
        command = nil
        until pos && check_pos(pos)
            puts "What position?"
            pos = parse_pos(gets.chomp)
        end
        until command && check_command(command)
            puts
            puts "What would you like to do (e.g. reveal, flag... ~ else?)"
            command = gets.chomp
            puts
        end
        [pos, command]
    end

#Some code here (check_pos, etc)



    def lose?(x)
        return true if x == 1
        false
    end

    def win?
        # board.all? {}
    end


end

我之前在Board 类中有explode?,但是为了能够结束游戏,把它移到了这里。非常感谢任何帮助!

【问题讨论】:

  • 它永远不会退出,因为在每个循环中你检查lose?(x) 并且x 总是相同的 - nil,所以你每次都得到错误。 else 内的 else 子句毫无意义 - 对于当前的 until,您需要 play_turn 之外的此控制流才能工作。从技术上讲,您可以将 lose(1) 替换为 play_turn 内的 exit 并且您的代码应该可以工作(有点),但我建议您进行一些重构......
  • @KonstantinStrukov,你会建议什么样的重构?也许直到win? || lose?

标签: ruby minesweeper


【解决方案1】:

如果我们将您的run 方法扩展一点,问题就变得更加明显:

def run
  puts "Welcome to minesweeper!"
  x = nil
  until(win? || lose(x)) do
    play_turn
  end
end

在此方法中,您将创建一个新变量x,它的作用域是此方法,其值为nil。这个变量永远不会设置在该方法的范围内,nil 总是如此,这意味着检查win? || lose(x) 也可以写成win? || lose(nil),而lose 永远不会返回true。

如果您从 play_turn 方法返回一个值,则可以使用它。请注意,方法中执行的最后一件事的结果就是返回的内容:

def play_turn
  board.render
  pos, command = get_input
  debugger

  if !explode?(pos, command)
    board.set_input(pos,command)
    true
  else
    puts "You lose!"
    false
  end
end

这意味着您的 run 方法可以检查结果:

def run
  puts "Welcome to minesweeper!"

  # we now know that play_turn returns true if the turn was not a loser
  # (i.e. it should continue to the next loop) and false if the player
  # lost, so we can use that returned value in our loop.
  while(play_turn) do
    if win?
      puts "looks like you won!"
      # if the player wins, we want to exit the loop as well. This is done
      # using break
      break
    end
  end
end

请注意,这也意味着您不需要单独的 lose 方法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多