Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Uncategorized category for Minesweeper by Moff
class MineSweeper(object):
MINE = 9
UNKNOWN = -1
def __init__(self, field):
self.field = field
def play(self):
for r, row in enumerate(self.field):
for c, v in enumerate(row):
if v == self.UNKNOWN:
if self.is_mine(r, c):
return [True, r, c]
if self.can_open(r, c):
return [False, r, c]
return [False, 0, 0]
def neighbours(self, i, j):
delta = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
return [(ci, cj) for ci, cj in ((i + di, j + dj) for di, dj in delta)
if 0 <= ci < len(self.field) and 0 <= cj < len(self.field[0])]
def count(self, r, c, value):
return sum(1 for i, j in self.neighbours(r, c) if self.field[i][j] == value)
def is_mine(self, r, c):
for i, j in self.neighbours(r, c):
if self.count(i, j, self.MINE) + self.count(i, j, self.UNKNOWN) == self.field[i][j]:
return True
return False
def can_open(self, r, c):
for i, j in self.neighbours(r, c):
if self.count(i, j, self.MINE) == self.field[i][j]:
return True
return False
def checkio(field):
return MineSweeper(field).play()
Sept. 16, 2015