Created
November 20, 2014 18:03
-
-
Save jesusgoku/7a5960de00e59832a549 to your computer and use it in GitHub Desktop.
Mines Weeper
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
#!/usr/bin/env python | |
import math | |
import sys | |
from random import randrange | |
class MinesWeeper: | |
CELL_BLANK = None | |
CELL_MINE = "M" | |
LEVEL_EASY = 0.1 | |
LEVEL_MEDIUM = 0.3 | |
LEVEL_HARD = 0.5 | |
board = None | |
width = None | |
height = None | |
mines = None | |
def __init__(self, width = 10, height = 10, level = 0.1): | |
self.width = width | |
self.height = height | |
self.mines = int(math.floor(width * height * level)) if 0.9 < level else int(math.ceil(width * height * level)) | |
self.makeBoard() | |
self.showBoard(True) | |
def showBoard(self, pretty = False): | |
if not pretty: | |
for x in self.board: | |
for y in x: | |
print y, | |
print "" | |
else: | |
for x in range(self.width): | |
for y in range(self.height): | |
print "+ -", | |
print "+" | |
for y in range(self.height): | |
print "|", self.board[x][y], | |
print "|" | |
def makeBoard(self): | |
# -- Initialize board | |
self.board = [] | |
for i in range(0,self.width): | |
row = [] | |
for j in range(0,self.height): | |
row.append(self.CELL_BLANK) | |
self.board.append(row) | |
# -- Fixes mines | |
fixed = self.mines | |
while fixed > 0: | |
x = randrange(self.width) | |
y = randrange(self.height) | |
if self.board[x][y] == self.CELL_BLANK: | |
self.board[x][y] = self.CELL_MINE | |
fixed = fixed - 1 | |
# -- Fixes clue | |
for x in range(self.width): | |
for y in range(self.height): | |
# -- Check if not mine | |
if self.board[x][y] != self.CELL_MINE: | |
self.board[x][y] = self.minesNeighborhood(x,y) | |
def minesNeighborhood(self, x, y): | |
minesFound = 0 | |
for i in range(x-1,x+2): | |
# -- Check out of range | |
if 0 > i or self.width <= i: | |
continue | |
for j in range(y-1,y+2): | |
# -- Check out of range | |
if 0 > j or self.height <= j: | |
continue | |
# -- Check equal cell | |
if i == x and j == y: | |
continue | |
# -- Check if mine | |
if self.board[i][j] == self.CELL_MINE: | |
minesFound = minesFound + 1 | |
return minesFound | |
if "__main__" == __name__: | |
width = int(sys.argv[1]) if len(sys.argv) > 1 else 10 | |
height = int(sys.argv[2]) if len(sys.argv) > 2 else 10 | |
level = float(sys.argv[3]) if len(sys.argv) > 3 and float(sys.argv[3]) < 1 else 0.1 | |
minesWeeper = MinesWeeper(width, height, level) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment