首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >RUBY退出扫雷游戏循环

RUBY退出扫雷游戏循环
EN

Stack Overflow用户
提问于 2020-11-17 20:35:15
回答 1查看 47关注 0票数 0

我不知道如何退出游戏循环。我很努力地做了一个lose?函数,我试着像lose?(x)一样,在x==1的时候返回true,但是没有让它退出run方法。这是我为Game类编写的代码。

代码语言:javascript
复制
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?,但是为了能够结束游戏,我把它移到了这里。任何帮助都是非常感谢的!

EN

回答 1

Stack Overflow用户

发布于 2020-11-18 15:56:09

如果我们稍微扩展一下您的run方法,问题就会变得更加明显:

代码语言:javascript
复制
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方法返回一个值,则可以使用该值。请注意,在该方法中执行的最后一件事的结果是返回的:

代码语言:javascript
复制
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方法可以检查结果:

代码语言:javascript
复制
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方法

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64875399

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档