我不知道如何退出游戏循环。我很努力地做了一个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?,但是为了能够结束游戏,我把它移到了这里。任何帮助都是非常感谢的!
发布于 2020-11-18 15:56:09
如果我们稍微扩展一下您的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方法
https://stackoverflow.com/questions/64875399
复制相似问题