Skip to content

Instantly share code, notes, and snippets.

@peiyush13
Created October 14, 2020 16:58
Show Gist options
  • Save peiyush13/a92cdebdcb83062046e5ac5c232e05a4 to your computer and use it in GitHub Desktop.
Save peiyush13/a92cdebdcb83062046e5ac5c232e05a4 to your computer and use it in GitHub Desktop.
Minesweeper Board Creation
#!/bin/ruby
require 'json'
require 'stringio'
#class here
class MineBoard
attr_accessor :height, :width, :num_mines, :board
def initialize(h, w, n)
@height = h
@width = w
@num_mines = n
@board = Array.new(h){Array.new(w) {0} }
initialise_board
end
def initialise_board
count = 0
while count < @num_mines do
rand_x_axis_value = rand(@width)
rand_y_axis_value = rand(@height)
next if @board[rand_x_axis_value][rand_y_axis_value] != 0
@board[rand_x_axis_value][rand_y_axis_value] = 'X'
assign_values_for_adjacent_pos(rand_x_axis_value, rand_y_axis_value)
count+=1
end
end
def show_board
@board.each do |row|
puts row.join(" ")
end
end
private
def assign_values_for_adjacent_pos(x, y)
@board[x-1][y] += 1 unless x <= 0
@board[x+1][y] += 1 unless x >= @width-1
@board[x][y+1] += 1 unless y >= @height-1
@board[x][y-1] += 1 unless y <= 0
end
end
#
# Complete the 'show_board' function below.
#
# The function is expected to return a STRING.
# The function accepts following parameters:
# 1. INTEGER height
# 2. INTEGER width
# 3. INTEGER num_mines
#
def show_board(height, width, num_mines)
board = MineBoard.new(height, width, num_mines)
board.show_board
end
fptr = File.open(ENV['OUTPUT_PATH'], 'w')
rand
height = 5
width = 5
num_mines = 6
result = show_board height, width, num_mines
fptr.write result
fptr.write "\n"
fptr.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment