Created
November 20, 2017 20:34
-
-
Save oguzalb/c2b1326c5fab787a1381661867f7aaab to your computer and use it in GitHub Desktop.
This file contains 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
import random | |
def put_mines(m, n, minecount): | |
flat_area = ["*"]*minecount + [0]*((m*n)-minecount) | |
random.shuffle(flat_area) | |
return [ | |
flat_area[i:i+n] | |
for i in range(0, m*n-n+1, n) | |
] | |
def neighbours(i, j): | |
return ((i-1, j-1), (i, j-1), (i+1, j-1), | |
(i-1, j), (i+1, j), | |
(i-1, j+1), (i, j+1), (i+1, j+1)) | |
def is_in_boundries(area, x, y): | |
line_len = len(area[0]) | |
return (x < len(area) and y < line_len | |
and x >= 0 and y >= 0) | |
def count_mines(area, i, j): | |
count = 0 | |
for x, y in neighbours(i, j): | |
if is_in_boundries(area, x, y) \ | |
and area[x][y] == "*": | |
count += 1 | |
return count | |
def calculate_numbers(area): | |
for i, line in enumerate(area): | |
line_len = len(line) | |
for j in range(0, len(line)): | |
if area[i][j] != "*": | |
area[i][j] = count_mines(area, i, j) | |
return area | |
def stringify_area(area): | |
strings = [] | |
for line in area: | |
newline = [str(x) for x in line] | |
strings.append("".join(newline)) | |
return "\n".join(strings) | |
print stringify_area(calculate_numbers(put_mines(2, 3,2))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment