Skip to content

Instantly share code, notes, and snippets.

@arunthampi
Created April 24, 2017 01:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arunthampi/8a403ed931b7dcafc707a3f6830b45c4 to your computer and use it in GitHub Desktop.
Save arunthampi/8a403ed931b7dcafc707a3f6830b45c4 to your computer and use it in GitHub Desktop.
Mine Sweeper Game
class Cell
attr_accessor :has_mine, :revealed
def initialize(has_mine, grid, row, col)
self.has_mine = has_mine
self.revealed = false
@row = row
@col = col
@grid = grid
end
def neighboring_mines
starting_row = [0,@row-1].max
starting_col = [0,@col-1].max
ending_row = [@row+1, @grid.size-1].min
ending_col = [@col+1, @grid.size-1].min
number_of_mines = 0
(starting_row..ending_row).each do |row_index|
(starting_col..ending_col).each do |col_index|
number_of_mines += @grid[row_index][col_index].has_mine ? 1 : 0
end
end
number_of_mines
end
def inspect
if revealed
self.has_mine ? "" : self.neighboring_mines
else
""
end
end
def debug
self.has_mine ? "" : ""
end
end
class Grid
attr_accessor :size, :num_mines
attr_reader :grid
def initialize(size, num_mines)
self.size = size
self.num_mines = num_mines
if num_mines >= size*size
raise ArgumentError.new("number of mines should be less than size of grid")
end
init_random_mines!
end
def print_grid
@grid.each do |row|
row.each { |cell| print " #{cell.inspect} " }
puts ""
end
end
def start_game_loop
while true do
self.print_grid
print "Enter the coordinates of the square you want to reveal (e.g. 1x2)> "
coordinates = gets.chomp
x, y = parse_coordinates(coordinates)
cell = @grid[x][y]
if cell.revealed
puts "This cell has already been revealed"
else
cell.revealed = true
if cell.has_mine
self.print_grid
puts "Oops, you have encountered a mine.\nGame Over"
exit(1)
else
if @grid.flatten.select { |c| !c.revealed }.length == @num_mines
puts "Congrats! You have swept for all mines"
exit(0)
end
end
end
end
end
private
def parse_coordinates(str)
res = str.match(/(\d)x(\d)/)
if res.nil?
puts "Not valid coordiantes.\nGoodbye!"
exit(1)
else
x = res[1].to_i
y = res[2].to_i
if x < 0 || x >= self.size || y < 0 || y >= self.size
puts "Not valid coordiantes.\nGoodbye!"
exit(1)
end
return [x, y]
end
end
def init_random_mines!
index = 0
@grid = []
with_mines = {}
(0...size*size).to_a.shuffle.slice!(0, self.num_mines).each do |x|
with_mines[x] = true
end
self.size.times do |i|
@grid[i] ||= []
self.size.times do |j|
@grid[i][j] = Cell.new(!!with_mines[index], @grid, i, j)
index += 1
end
end
end
end
g = Grid.new(4,4)
g.start_game_loop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment