Skip to content

Instantly share code, notes, and snippets.

@mkweick
Last active November 26, 2015 17:18
Show Gist options
  • Save mkweick/824812bcc5e4491c2873 to your computer and use it in GitHub Desktop.
Save mkweick/824812bcc5e4491c2873 to your computer and use it in GitHub Desktop.
Minesweeper
class Board
def self.transform(input)
output = []
fail ValueError unless valid_game?(input)
input.each_with_index do |row, row_index|
if row_index == 0 || row_index == (input.size - 1)
output << row
else
output_row = ''
row.split('').each_with_index do |tile, tile_index|
if %w(| *).include? tile
output_row += tile
else
output_row += bomb_count(input, row_index, tile_index)
end
end
output << output_row
end
end
output
end
private
def self.bomb_count(input, row_index, tile_index)
count = 0
touching_tiles = []
touching_tiles << row_above(input, row_index, tile_index)
touching_tiles << row_current(input, row_index, tile_index)
touching_tiles << row_below(input, row_index, tile_index)
touching_tiles.flatten.each { |value| count += 1 if value == '*' }
if count > 0
count.to_s
else
' '
end
end
def self.row_above(input, row_index, tile_index)
row = input[row_index - 1].split('')
touching_tiles = [row[tile_index - 1], row[tile_index], row[tile_index + 1]]
end
def self.row_current(input, row_index, tile_index)
row = input[row_index].split('')
touching_tiles = [row[tile_index - 1], row[tile_index + 1]]
end
def self.row_below(input, row_index, tile_index)
row = input[row_index + 1].split('')
touching_tiles = [row[tile_index - 1], row[tile_index], row[tile_index + 1]]
end
def self.valid_game?(input)
valid_length?(input) && valid_border?(input) && valid_char?(input)
end
def self.valid_length?(input)
lengths = input.map { |row| row.length }
lengths.uniq.size == 1
end
def self.valid_border?(input)
[input[0], input[-1]].each do |row|
invalid_border = row.split('').any? do |char|
!['+', '-', '|'].include? char
end
return nil if invalid_border
end
end
def self.valid_char?(input)
input.each do |row|
invalid_chars = row.split('').any? do |char|
!['+', '-', ' ', '|', '*'].include? char
end
return nil if invalid_chars
end
end
end
ValueError = Class.new(StandardError)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment