Skip to content

Instantly share code, notes, and snippets.

@carpeliam
Last active December 18, 2015 04:18
Show Gist options
  • Save carpeliam/5724189 to your computer and use it in GitHub Desktop.
Save carpeliam/5724189 to your computer and use it in GitHub Desktop.
class Cell
attr_accessor :is_mine, :num_adjacent_mines
def initialize
self.num_adjacent_mines = 0
end
def to_s
if is_mine
'*'
else
num_adjacent_mines.zero? ? '.' : num_adjacent_mines.to_s
end
end
end
class Board
def initialize(size = 10, num_mines = 20)
@size = size
@num_mines = num_mines
clear
end
def clear
@cells = Array.new(@size) { Array.new(@size) { Cell.new } }
end
def populate
# populate mines
empty_cells = @cells.flatten
@num_mines.times do
mined_cell = empty_cells[rand(empty_cells.size)].tap { |cell| cell.is_mine = true }
empty_cells.delete mined_cell
end
# populate number of adjacent mines
@cells.each_with_index do |row, i|
row.each_with_index do |cell, j|
cell.num_adjacent_mines = num_adjacent_mines_to(i, j) unless cell.is_mine
end
end
end
def to_s
@cells.map(&:join).join("\n")
end
private
def num_adjacent_mines_to(x, y)
# don't go look past the borders of the board
range = lambda { |i| ([i - 1, 0].max..[i + 1, @size - 1].min) }
@cells[range.call(x)].inject(0) do |sum, row|
sum += row[range.call(y)].select(&:is_mine).size
end
end
end
def setup
@b = Board.new
@b.populate
puts @b
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment