Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # minesweeper.py
- # Resolve the problem minesweeper from the book programming challenges
- def readFile(input):
- x, y = input.readline().rstrip().split()
- x = int(x)
- y = int(y)
- field = []
- if x == 0 or y == 0:
- return None
- for i in range(x):
- line = list(input.readline().rstrip())
- field.append(line)
- return field
- def check(coord):
- if coord == '*':
- return 1
- return 0
- def processField(field):
- for i in range(len(field)):
- for j in range(len(field[i])):
- count = 0
- if field[i][j] == '*':
- continue
- if i == 0:
- count += check(field[i+1][j]) # Check Down
- if j == 0:
- count += check(field[i][j+1]) # Check Right
- count += check(field[i+1][j+1]) # Check DownRight
- elif j == len(field[i])-1:
- count += check(field[i][j-1]) # Check Left
- count += check(field[i+1][j-1]) # Check DownLeft
- else:
- count += check(field[i][j-1]) # Check Left
- count += check(field[i][j+1]) # Check Right
- count += check(field[i+1][j-1]) # Check DownLeft
- count += check(field[i+1][j+1]) # Check DownRight
- elif i == len(field)-1:
- count += check(field[i-1][j]) # Check Up
- if j == 0:
- count += check(field[i][j+1]) # Check Right
- count += check(field[i-1][j+1]) # Check UpRight
- elif j == len(field[i])-1:
- count += check(field[i][j-1]) # Check Left
- count += check(field[i-1][j-1]) # Check UpLeft
- else:
- count += check(field[i][j+1]) # Check Right
- count += check(field[i-1][j+1]) # Check UpRight
- count += check(field[i][j-1]) # Check Left
- count += check(field[i-1][j-1]) # Check UpLeft
- else:
- count += check(field[i-1][j]) # Check Up
- count += check(field[i+1][j]) # Check Down
- if j == 0 or j != len(field[i])-1:
- count += check(field[i-1][j+1]) # Check UpRight
- count += check(field[i][j+1]) # Check Right
- count += check(field[i+1][j+1]) # Check DownRight
- if j == len(field[i])-1 or j != 0:
- count += check(field[i-1][j-1]) # Check UpLeft
- count += check(field[i][j-1]) # Check Left
- count += check(field[i+1][j-1]) # Check DownLeft
- field[i][j] = count
- return field
- def writeFile(field, output, numField):
- print >> output,"Field #%s" % numField
- for line in field:
- for charac in line:
- output.write(str(charac))
- print >> output
- print >> output
- def main():
- try:
- input = open("input.in")
- output = open("output.out", "w")
- except IOError:
- return "Cannot open input file"
- try:
- field = readFile(input)
- numField = 1
- while field:
- field = processField(field)
- writeFile(field, output, numField)
- field = readFile(input)
- numField += 1
- input.close()
- output.close()
- return "Finishing the program"
- except StandardError:
- return "Something unexpected happened"
- raw_input(main())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement