Pages

Search This Blog

April 09, 2013

Minesweeper


The game shows a number in a square which tells you how many mines there are
adjacent to that square. Each square has at most eight adjacent squares. The 4×4 field
on the left contains two mines, each represented by a “*” character. If we represent the
same field by the hint numbers described above, we end up with the field on the Output:

Input:

*...
....
.*..
....

Output:
*100
2210
1*10
1110

import os
import sys

filename = "minesweeper.txt"
file_contents = open(filename).readlines()

field = []

def is_mine(x, y):
    try:
        if x < 0 or y < 0: # -1 is a valid index in python ! not for us
            return False
        
        if field[x][y] == "*":
            return True
        return False
        
    except:
        return False

def get_nbr_adj_mines(x, y):
    cnt = 0
    for del_x, del_y in [(-1, -1), (-1, 0), (-1, 1),
                         (0, -1), (0, 1), (1, -1), (1, 0),
                         (1, 1)]:
        #print x + del_x, ":", y + del_y, "=", str(is_mine(x + del_x, y + del_y))
        if is_mine(x + del_x, y + del_y):
            cnt = cnt + 1
    return cnt

field_nbr = 1    
while True:
    line = file_contents.pop(0)
    line.replace("\\n", "")

    n, m = int(line.split()[0]), int(line.split()[1])

    if n == 0:
        break

    field = []
    while n > 0:
        field.append(list(file_contents.pop(0).replace("\\n", "")))
        n = n-1

    print "Field #:", field_nbr
    for x, row in enumerate(field):
        for y, elt in enumerate(row):
            #print x, ":", y, ":", elt, " ",
            if is_mine(x, y):
                print "%s" % (elt),
            else:
                print "%d" % (get_nbr_adj_mines(x, y)),
        print
    field_nbr = field_nbr + 1



minesweeper.txt:
4 4
*...
....
.*..
....
3 5
**...
.....
.*...
0 0

No comments:

Post a Comment