Search code examples
rubyminesweeper

Ruby Minesweeper


I am trying to get this Ruby game I made to loop after the first round, and end with a "game over" if the player hits a mine. I have it to where it will build the board, which is a pre-built layout in a .txt file, and it will loop, but the game doesn't end. Here is my code

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

Also, mines.txt looks like this...

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

I would appreciate any feedback you can give.


Solution

  • This will get you looping:

    # 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 to bust out. You can also use break to exit the loop:

    break if game_over?