Minsweeper API design (Python)

by hekevintran

JavaScript

import random

MINE = '*'

def generate_board(width, height, number_of_mines):
    board = get_blank_board(width, height)
    place_mines(width, height, board, number_of_mines)
    count_mines(width, height, board)
    return board


def get_blank_board(width, height):
    ret = []
    for i in range(height):
        row = []
        for j in range(width):
            row.append(0)
        ret.append(row)
    return ret


# def place_mines(width, height, board, number_of_mines):
#     while number_of_mines > 0:
#         y = random.choice(range(height))
#         x = random.choice(range(width))
#         if board[y][x] != MINE:
#             board[y][x] = MINE
#             number_of_mines -= 1


def place_mines(width, height, board, number_of_mines):
    while number_of_mines > 0:
        y = random.choice(range(height))
        x = random.choice(range(width))
        if board[y][x] != MINE:
            board[y][x] = MINE
            number_of_mines -= 1


def count_mines(width, height, board):
    deltas = [[-1, 0], [1, 0], [0, -1], [0, 1], [-1, -1], [-1, 1], [1, -1], [1, 1]]
    for y in range(height):
        for x in range(width):
            if board[y][x] != MINE:
                count = 0
                for dx, dy in deltas:
                    y2 = y + dy
                    x2 = x + dx
                    if (y2 < 0 or y2 > max(range(height))) or (x2 < 0 or x2 > max(range(width))):
                        continue
                    else:
                        if board[y2][x2] == MINE:
                            count += 1
                board[y][x] = count


def print_board(board):
    for row in board:
      print ''.join([str(item) for item in row])


print_board(generate_board(5, 5, 3))