Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
770 views
in Technique[技术] by (71.8m points)

refactoring - Minesweeper game board | ruby

I have written a code for the drawing board for the minesweeper game, can anyone help me to refactor this code more.

Please find my code below

def draw(height, width, mines)
  board = Array.new(height) { Array.new(width,0) }
  x =  Random.rand(height)
  y = Random.rand(width)
  mines.times do
   until board[x][y] != 'x'
    x =  Random.rand(height)
    y = Random.rand(width)
   end
   board[x][y] = 'x'
  end

  board.each_with_index do |row, i|
   row.each_with_index do |elem, j|
    next if board[i][j] == 'x'
    count = 0
    count += 1 if i+1 < height && board[i+1][j] == 'x'
    count += 1 if j+1 < width && board[i][j+1] == 'x'
    count += 1 if i-1 >= 0 && board[i-1][j] == 'x'
    count += 1 if j-1 >= 0 && board[i][j-1] == 'x'

    board[i][j] = count
  end
end

 board.each do |row|
   row.each do |e|
     print "#{e} "
    end
  print "
"
 end 
end

draw(4,4,3)

Thanks in advance.

question from:https://stackoverflow.com/questions/65871347/minesweeper-game-board-ruby

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you need to check 8 adjacent cells, not 4. Since this is a refactoring, I kept the original behavior.

def draw(height, width, mines)
  board = Array.new(height) { Array.new(width, 0) }

  mines.times do
    x = rand(height)
    y = rand(width)

    redo if board[x][y] == 'x'

    board[x][y] = 'x'

    [[x - 1, y], [x + 1, y], [x, y - 1], [x, y + 1]].each do |x, y|
      next if x < 0 || x >= height
      next if y < 0 || y >= width
      next if board[x][y] == 'x'

      board[x][y] += 1
    end
  end

  board.each { |row| puts row.join(' ') }
end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...