Skip to content

Instantly share code, notes, and snippets.

@hmlON
Last active April 7, 2017 21:00
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 hmlON/c5b71db5f516703eb1415ceea346590e to your computer and use it in GitHub Desktop.
Save hmlON/c5b71db5f516703eb1415ceea346590e to your computer and use it in GitHub Desktop.
Minesweeper logic ruby code
class Field
attr_accessor :field, :dimenstions, :number_of_mines
def initialize(dimenstions, number_of_mines)
@dimenstions = dimenstions
@number_of_mines = number_of_mines
initialize_free_of_mines_coordinates
build_field
fill_field_with_mines
end
def open(x, y)
lose_game if field[x][y].mine?
field[x][y].open
reveal(x, y, mines_nearby(x, y))
if mines_nearby(x, y) == 0
coordinates_around(x, y) do |i, j|
open(i, j) unless field[i][j].opened?
end
end
end
def mines_nearby(x, y)
count = 0
coordinates_around(x, y) do |i, j|
count += 1 if field[i][j].mine?
end
count
end
private
attr_accessor :free_of_mines_coordinates
def coordinates_around(x, y)
x-1.upto x+1 do |i|
y-1.upto y+1 do |j|
if (i < 0 || j < 0) || (i >= dimenstions || j >= dimenstions)
yield i, j if !(i == x && j == y)
end
end
end
end
def initialize_free_of_mines_coordinates
@free_of_mines_coordinates = Array.new()
dimenstions.times do |i|
dimenstions.times do |j|
@free_of_mines_coordinates << [i, j]
end
end
end
def build_field(dimenstions, munber_of_mines)
field = Array.new dimenstions do
Array.new dimenstions do
Coordinate.new
end
end
end
def fill_field_with_mines
number_of_mines.times { add_mine_to_field }
end
def add_mine_to_field
coordinate = free_of_mines_coordinates[rand(free_of_mines_coordinates.size - 1)] # [x, y]
free_of_mines_coordinates.delete(coordinate)
field[coordinate[0]][coordinate[1]].mine = true
end
end
class Coordinate
attr_writer :mine
def initialize
@mine = false
@opened = false
end
def mine?
mine
end
def opened?
opened
end
def open
self.opened = true
end
private
attr_reader :mine
attr_accessor :opened
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment