Created
April 5, 2017 02:46
-
-
Save fogonthedowns/010561b92eb625e29ecd0d2a28e144f1 to your computer and use it in GitHub Desktop.
counts neighbors in a 2D array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require 'matrix' | |
| width = 6 | |
| height = 5 | |
| number_of_mines = 25 | |
| def generate_board(width, height, number_of_mines) | |
| two_d_array = Array.new(height) {Array.new(width, 0)} | |
| height_index_max = height | |
| width_index_max = width | |
| placed_mines = 0 | |
| until (placed_mines == number_of_mines) do | |
| next if two_d_array[rand(height_index_max)][rand(width_index_max)] == '*' | |
| two_d_array[rand(height_index_max)][rand(width_index_max)] = '*' | |
| placed_mines = two_d_array.flatten.count('*') | |
| end | |
| mine_locations(two_d_array, number_of_mines) | |
| end | |
| def mine_locations(board, number_of_mines) | |
| mine_locations = [] | |
| board.each_with_index do |row, row_index| | |
| row.each_with_index do |cell, col_index| | |
| count_neighbors(row_index, col_index, board) unless cell == '*' | |
| mine_locations << [row_index, col_index] if cell == '*' | |
| end | |
| end | |
| print_b(board) | |
| mine_locations | |
| end | |
| def count_neighbors(x,y, board) | |
| return if board[x][y] == '*' | |
| topLeft = board.another_dig((x - 1),(y - 1)) == '*' | |
| top = board.another_dig(x, y - 1) == '*' | |
| topRight = board.another_dig(x + 1, y - 1) == '*' | |
| midLeft = board.another_dig(x - 1, y) == '*' | |
| midRight = board.another_dig(x + 1,y) == '*' | |
| botLeft = board.another_dig(x - 1,y + 1)== '*' | |
| bot = board.another_dig(x,y + 1) == '*' | |
| botRight = board.another_dig(x + 1,y + 1) == '*' | |
| mine_count = [] | |
| mine_count << topLeft << top << topRight << midLeft << midRight << botLeft << bot << botRight | |
| mine_count = mine_count.count(true) | |
| board[x][y] = mine_count | |
| board[x][y] | |
| end | |
| def print_b(b) | |
| b.each do |a| | |
| p(a) | |
| end | |
| end | |
| class Array | |
| def another_dig(*args) | |
| self.dig(*args) unless args.any?{|num| num<0} | |
| end | |
| end | |
| b = generate_board(width,height,number_of_mines) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment