Ruby Minesweeper

时间:2015-11-30 02:08:49

标签: ruby minesweeper

我试图让这个 Ruby 游戏在第一轮之后循环播出,如果玩家击中了我的游戏,则以“游戏结束”结束。我把它放在它将构建板的位置,这是.txt文件中的预构建布局,它将循环,但游戏不会结束。这是我的代码

def load_board
    mine_field = []
    File.open("mines.txt", 'r') do |f|
    f.gets
    f.each_line do |line|
      mine_field.push line.chomp.split('')
     end
   end 

    return mine_field
end

def create_hint_board(board)
    hint = Array.new

  for i in (0..board.size-1)
    hint[i] = []
    for j in (0..board[i].size-1)
      hint
      if board[i][j] == '*'
        hint[i].push '*'
      else
        bombs = 0
        for x in (-1..1)
          for y in (-1..1)
            if i-x >= 0 && 
              i-x < board.size && 
              j-y >= 0 && 
              j-y < board[i].size && 
              board [i-x][j-y] == '*'
              bombs += 1

            end
          end
        end
        hint[i][j] = bombs
      end
    end
  end
    return hint
end

def print_board (board)
    board.each do |row|
      p row
    end
end

def pp_board (board)
    puts Array.new(board[0].size*2+1, '-').join('')
    board.each do |row|
      puts "|" + row.join('|') + "|"
      puts Array.new(row.size*2+1, '-').join('')
    end
end

def copy_to_blank(board)
    blank = Array.new
    for i in 0..(board.size-1) 
        blank << Array.new(board[i].size, '.')
    end
    blank
end

def play(board)
  puts "Welcome to Minesweeper!" 
  puts
  puts
  puts
    hint = create_hint_board(board)
    game = copy_to_blank(board)
    puts "Starting"
    pp_board game
  #copy coords user puts in
  coords = gets.chomp.split(' ')
  i = coords[0].to_i
  j = coords[1].to_i
  game[i][j] = 
    hint[i][j]


  pp_board game

    puts
    puts "Hint"
    pp_board  hint
end
end

#start the game
play load_board

另外,mines.txt看起来像这样......

4 3
*...
..*.
....

我很感激您提供的任何反馈。

1 个答案:

答案 0 :(得分:0)

这会让你循环:

# start while loop
while true
  coords = gets.chomp.split
  i = coords[0].to_i
  j = coords[1].to_i

  if hint[i][j] == "*"
    puts "you lose"
    break
  end

  game[i][j] = hint[i][j]

  pp_board game

  puts "\nHint"
  pp_board hint
end
#end while loop

Ctrl-c破灭了。您也可以使用break退出循环:

break if game_over?