Skip to content

Instantly share code, notes, and snippets.

@kevinjqiu
Last active November 24, 2016 04:48
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 kevinjqiu/6c5731ad3c8053f80e1f0b9a2a6caac7 to your computer and use it in GitHub Desktop.
Save kevinjqiu/6c5731ad3c8053f80e1f0b9a2a6caac7 to your computer and use it in GitHub Desktop.
module MineSweeper
class Tile
attr_accessor :state, :value
def initialize()
@state = :closed
@value = nil
end
def to_s
if @state == :closed
'.'
elsif @state == :flagged
'F'
else
@value.to_s
end
end
end
class Board
attr_accessor :height, :width, :num_of_mines
def initialize(width, height, num_of_mines)
raise RuntimeError.new if num_of_mines >= height * width
@width = width
@height = height
@num_of_mines = num_of_mines
@tiles = (0...@height).collect { |_|
(0...@width).collect { |_|
Tile.new
}
}
place_mines
fill_clues
end
def at(x, y)
@tiles[y][x]
end
def neighbours(x, y)
neighbour_coordinates = [
[x-1, y-1], [x-1, y], [x-1, y+1],
[x, y-1], [x, y+1],
[x+1, y-1], [x+1, y], [x+1, y+1]
]
neighbour_coordinates = neighbour_coordinates.find_all { |c|
x, y = c
x >=0 and x < @width and y >= 0 and y < @height
}
neighbour_coordinates.collect { |c|
x, y = c
at(x, y)
}
end
def to_s
(@tiles.collect { |row|
(row.collect { |cell| " #{cell} " }).join('')
}).join("\n")
end
private
def place_mines
rnd = Random.new
remaining = @num_of_mines
until remaining == 0
x, y = rnd.rand(0...@width), rnd.rand(0...@height)
tile = at(x, y)
if tile.value != :m
tile.value = :m
remaining -= 1
end
end
end
def fill_clues
(0...@height).each { |y|
(0...@width).each { |x|
tile = at(x, y)
if tile.state != :m
n = neighbours(x, y)
clue = (n.find_all { |tile| tile.state == :m }).length
tile.value = clue
end
}
}
end
end
class Game
def initialize(height, width, num_of_mines)
@board = Board.new(height, width, num_of_mines)
end
def display_board
puts @board.to_s
end
def solve
end
end
end
game = MineSweeper::Game.new(24, 24, 80)
game.display_board
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment