2008-04-28

KataMinesweeper

I've been playing around with a few of the katas at codingdojo.org these past few days. I'm new to the concept but I like the idea and since I'm going to attend a kata session led by Emily in a couple of weeks I thought I'd prepare.

Here's my best-so-far attempt at KataMinesweeper:

|def convert(rows, cols, field):
| """
| >>> print convert(1,1,['*'])
| *
| >>> print convert(2,2,['*.', '..'])
| *1
| 11
| >>> print convert(4,4,['*...', '....', '.*..', '....'])
| *100
| 2210
| 1*10
| 1110
| >>> print convert(3,5,['**...', '.....', '.*...'])
| **100
| 33200
| 1*100
| """
|
| _field = dict(zip(range(rows), [dict(zip(range(cols), f)) for f in field]))
|
| for r in range(rows):
| for c in range(cols):
| if _field[r][c] == '.':
| count = 0
| for _r,_c in [(r-1,c-1), (r-1,c), (r-1,c+1), (r,c-1), (r,c+1), (r+1,c-1), (r+1,c), (r+1,c+1)]:
| try:
| if _field[_r][_c] == '*':
| count += 1
| except:
| pass
|
| _field[r][c] = str(count)
|
| return "\n".join(["".join(f.values()) for f in _field.values()])
|
|def content(filename):
| f = open(filename)
| lines = f.readlines()
| f.close()
|
| return lines
|
|def solve(lines):
| """
| >>> solve(['4 4\\n','*...\\n','....\\n','.*..\\n','....\\n',
| ... '3 5\\n','**...\\n','.....\\n','.*...\\n',
| ... '0 0\\n'])
| Field #1:
| *100
| 2210
| 1*10
| 1110
| [BLANKLINE]
| Field #2:
| **100
| 33200
| 1*100
| [BLANKLINE]
| """
|
| l, n = 0, 1
| while True:
| rows, cols = map(int, lines[l].split())
| if rows == 0 and cols == 0:
| break
|
| print "Field #%s:" % n
| print convert(rows, cols, [line.strip() for line in lines[l+1:l+rows+1]])
| print
|
| n += 1
| l += rows+1
|
|if __name__ == '__main__':
| import doctest
| doctest.testmod()
|
| import sys
| solve(content(sys.argv[-1]))
and running it with the suggested test-case in a text-file (minesweeper.txt) gives the following output:
|C:\Playground\Katas>minesweeper.py minesweeper.txt
|Field #1:
|*100
|2210
|1*10
|1110
|
|Field #2:
|**100
|33200
|1*100
It needs more tests. I know ;-)

Inga kommentarer: